How to add a value in an array to the values before and after it

后端 未结 4 1238
说谎
说谎 2021-01-26 04:06

I am trying to turn an array of numbers into steps of the value of the Non-Zero integer element i.e

spread([0,0,n,0,0] returns => 
[0 + n-2, 0 + n-1, n, 0 +         


        
4条回答
  •  忘了有多久
    2021-01-26 04:59

    You could reduce the array by using a copy of the array and go left and right with a recursive function which checks the value to spread and the index.

    function spread(array) {
        return array.reduce((r, v, i, a) => {
            const
                iter = (v, i, d) => {
                    if (v < 1 || !(i in a)) return;
                    r[i] += v;
                    iter(v - 1, i + d, d);
                };
            iter(v - 1, i - 1, -1);
            iter(v - 1, i + 1, 1);
            return r;
        }, array.slice());
    }
    
    console.log(...spread([0, 0, 0, 4, 0, 0, 0])); // [1, 2, 3, 4, 3, 2, 1]
    console.log(...spread([0, 0, 0, 3, 0, 2, 0])); // [0, 1, 2, 3, 3, 3, 1]
    console.log(...spread([3, 0, 0, 0]));          // [3, 2, 1, 0]

    A different approach by moving arrays and adding them.

    function spread(array) {
        const dec = v => Math.max(v - 1, 0);
    
        var result = array.slice(),
            temp = array.slice(1).map(v => Math.max(v - 1, 0)),
            offset;
        
        while (temp.length) {
            temp.forEach((v, i) => result[i] += v);
            temp = temp.slice(1).map(dec);
        }
    
        temp = array.slice(0, -1).map(dec);
        while (temp.length) {
            offset = result.length - temp.length;
            temp.forEach((v, i) => result[i + offset] += v);
            temp = temp.slice(0, -1).map(dec);
        }
        return result;
    }
    
    console.log(...spread([0, 0, 0, 4, 0, 0, 0])); // [1, 2, 3, 4, 3, 2, 1]
    console.log(...spread([0, 0, 0, 3, 0, 2, 0])); // [0, 1, 2, 3, 3, 3, 1]
    console.log(...spread([3, 0, 0, 0]));          // [3, 2, 1, 0]

提交回复
热议问题