gpt4 book ai didi

javascript - 根据条件用数字的升序填充数组

转载 作者:行者123 更新时间:2023-11-30 09:13:22 25 4
gpt4 key购买 nike

如何在满足这些条件的情况下用数字的升序填充数组:

  • 数组中的第一个元素是let a = 0;

  • 数组元素之和等于var sum = 10;

  • 数组的长度应该是var length = 10;

这是我创建的代码:

    var length = 10;
var array = [];
var sum = 10; // the sum of all elements in the array should be equal to this

for (let i = 0; i < length; i++) {
let a = 0; // the very first element of array
// Math equations
let last = (sum - (length / 2 * a)) * 2 / length
let dd = (last - a) / (length - 1)

sume = (dd * (i));
array.push(sume);

}

// check to see if array elemements sum is equal to "var sum = 10"
let reducer = (accumulator, currentValue) => accumulator + currentValue;
let sumArray = array.reduce(reducer);
console.log("sumArray: " + sumArray)

console.log(array) // results

但问题不是像这样有整数(它仍然符合我的所有条件):

[0, 0, 0, 0, 1, 1, 1, 2, 2, 3]

但是我得到了这些结果:

[0, 0.2222222222222222, 0.4444444444444444, 0.6666666666666666, 0.888888888888888, 1.1111111111111112, 1.33333333333 33333, 1.5555555555555554, 1.777777777777777, 2]

注意:我在这里计算了最后一项:让 last = (sum - length/2 * a) * 2/length 并且第一个总是 0...

最佳答案

您可以四舍五入这些值。

sume = Math.round(dd * i);

    var length = 10;
var array = [];
var sum = 10; // the sum of all elements in the array should be equal to this

for (let i = 0; i < length; i++) {
let a = 0; // the very first element of array
// Math equations
let last = (sum - length / 2 * a) * 2 / length
let dd = (last - a) / (length - 1)

sume = Math.round(dd * i);
array.push(sume);

}

// check to see if array elemements sum is equal to "var sum = 10"
let reducer = (accumulator, currentValue) => accumulator + currentValue;
let sumArray = array.reduce(reducer);
console.log("sumArray: " + sumArray)

console.log(array) // results

一种更短的舍入方法(它可能不适用于所有情况)。

const add = (a, b) => a + b;

function disperse(length, sum) {
var min = 0,
max = sum * 2 / length,
array = Array.from({ length }, (_, i) => Math.round(min + i * max / (length - 1)));
return [array.reduce(add), array.join(', ')];
}

console.log(disperse(10, 10));
console.log(disperse(10, 30));
console.log(disperse(20, 50));
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 根据条件用数字的升序填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56916227/

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