用条件递增的数字序列填充数组

时间:2019-07-06 17:22:52

标签: javascript

在这些情况下,如何用递增的数字序列填充数组:

  • 数组中的第一个元素是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.8888888888888888, 1.1111111111111112, 1.3333333333333333, 1.5555555555555554, 1.7777777777777777, 2]

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

2 个答案:

答案 0 :(得分:3)

您可以取整数值。

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; }

答案 1 :(得分:1)

sum / length是数组中的中间值
sum / length * 2是数组中的最后一个值
/ (length - 1) * index将根据索引获取上一个值的百分比
+ .5 | 0代表Math.round

const sequence = (L, S) => [...Array(L)].map((v, i) => S / L * 2 / (L - 1) * i + .5 | 0)

const test = (L, S, arr = sequence(L, S)) => arr.reduce((a, b) => a + b) + ' : ' + arr

console.log( test(10, 10) )
console.log( test(10, 30) )
console.log( test(20, 50) )