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

后端 未结 4 1212
说谎
说谎 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:42

    Somehow "old-school", but seems to work:

    let spread = a => {
    
        let add = a.map(_ => 0);
    
        a.forEach((x, i) => {
            for (let c = 1; x > 1 && c < a.length; c++, x--) {
                add[i + c] += x - 1;
                add[i - c] += x - 1;
            }
        });
    
        return a.map((x, i) => x + add[i]);
    };
    
    //
    
    console.log(spread([0, 0, 0, 4, 0, 0, 0]).join())
    console.log(spread([0, 0, 0, 3, 0, 2, 0]).join())
    console.log(spread([3, 0, 0, 0, 0, 0]).join())

提交回复
热议问题