We have 4 dimensional array. It is necessary to write a program that will add even its number, which is to the right, and it will be made 0, but only once.

function solution(x){ for (var i = 0; i < x.length; i++) { for (var j = 0; j < x.length; j++) { if (x[i][j]==x[i][j+1]) { x[i][j]=0 x[i][j+1]*=2 } } } return JSON.stringify(x) } console.log(solution([[2,2,4,8], [4,8,4,8], [8,8,8,8], [64,8,16,8]])) 

he will return

  [0,0,0,16], [4,8,4,8], [0,16,0,16], [64,8,16,8] 

but it is necessary that the second time is not folded, that is, instead of [0,0,0,16], you need [0,4,4,8]

It is necessary that the program worked correctly for all such examples, but at that time was very simple ..

    1 answer 1

     x[i][j+1]*=2 
     x[i][++j]*=2 

     function solution(x){ for (var i = 0; i < x.length; i++) { for (var j = 0; j < x.length; j++) { if (x[i][j]==x[i][j+1]) { x[i][j]=0 x[i][++j]*=2 } } } return JSON.stringify(x) } console.log(solution([[2,2,4,8], [4,8,4,8], [8,8,8,8], [64,8,16,8]])) 

    • Of course, this is an option, but only in the example I wrote, but there are matrices in which the code does not work, what can you offer? - Tyom Arshakyan
    • I have to guess them? - Qwertiy pm
    • I just have a test with hidden matrices, I also can not guess, there is no option where the code will always work? - Tyom Arshakyan
    • @TyomArshakyan, I corrected. - Qwertiy
    • awesome, thank you very much))) - Tyom Arshakyan