gpt4 book ai didi

javascript - 给定正数、负数和零数数组,返回百分比数组

转载 作者:行者123 更新时间:2023-12-01 00:37:30 32 4
gpt4 key购买 nike

我需要一些帮助来解决需要此操作的问题:

我们需要一个函数 FractionOf 来接收一个数组并返回另一个包含以下三个数字的数组:

 in the first position, the fraction of numbers that are positive
in the second position, the fraction of numbers that are zero
in the last position, the fraction of numbers that are negative

例如,FractionOf ([1, 2, 0, -1]) 应返回 [0.5, 0.25, 0.25],假设有 50% 为正值,25% 为零,25% 为负值。

所以我尝试至少以某种形式来回答他们问我的问题,但我坚持如何将百分比转换为分数并将它们添加到位置。

var nums=[1,2,0,0,-1,-4]
function FractionOf(nums){
var result=[]
var num1=0
var num2=0
var num3=0
for(var i=0; i<nums.length; i++){
var num=nums[i]
if(num>0){
num1= num1 + 0.25}
if (num==0){
num2=num2 + 0.25}
if(num<0){
num3=num3 + 0.25}
result.push(num1)
result.push(num2)
result.push(num3)
return result
}

最佳答案

function FractionOf(nums) {
return nums
.reduce((acc, cur) => {
if (cur > 0) acc[0]++;
else if (cur === 0) acc[1]++;
else acc[2]++;
return acc;
}, [0, 0, 0])
.map(result => result / nums.length);
}

此解决方案使用 reduce计算这三种情况的出现次数,从填充 0 的数组开始。结果通过管道传送到map函数,它将每个值除以输入 num 的长度,以获得 0-1 范围内的百分比。

关于javascript - 给定正数、负数和零数数组,返回百分比数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57985964/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com