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

后端 未结 4 1187
说谎
说谎 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 05:00

    In three steps: 1. Explode the input array in an array of arrays, every containing single non-zero value. 2. Process every of those trivial cases separately. 3. Reduce them back into a single array.

    (Not the optimal solution for sure, performance-wise).

    const explode = arr => {
       const len = arr.length;
    
       return arr.map((val, index) => new Array(len)
          .fill(0)
          .map((x, j) => index === j ? val : 0)
       );
    }
    
    const pop = arr => {
       const nonZeroIndex = arr.findIndex(x => !!x);
       const nonZeroValue = arr.find(x => !!x);
    
       return nonZeroIndex !== -1 ?
          arr.map((x, i) => Math.max(0, nonZeroValue - Math.abs(i - nonZeroIndex))) :
          arr;
    }
    
    const sum2Arrays = (arrA, arrB) => arrA.map((x, i) => x + arrB[i]);
    const sumArrays = arrs => arrs.reduce(sum2Arrays, Array(arrs[0].length).fill(0));
    
    const spread = (arr) => sumArrays(explode(arr).map(pop));
    
    console.log(spread([0, 0, 0, 0, 4, 0, 0, 3, 0]));
    
    

提交回复
热议问题