0

this is my first question here. hope for getting help from you guys (: I have trouble on changing 2D array element by dynamic input. by the input every element should go forwad input steps. here is my code for now:

    function warpTunnel(mtx, n) {
  let temporary;
  // run over array
  for(let i = 0; i < mtx.length; i++) {
        // run over inside array
          for(let j = 0; j < mtx[i].length; j++) {
                      temporary = mtx[i][j + n]
                      // move the current element n times right
                      mtx[i].splice(j, 1, temporary)
          }  
  }
  console.log(mtx)
  return mtx;
}

warpTunnel([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 2)

1 Answers1

1

        function warpTunnel(mtx, n) {
  let arr;
  // run over array
  for(let i = 0; i < mtx.length; i++) {
        // run over inside array
        arr = [...mtx[i]];
        for(let j = 0; j < mtx[i].length; j++) {
            if (j + n < mtx[i].length) {
              mtx[i][j + n] = arr[j]
            } else {
              mtx[i][((j + n) % mtx[i].length)] = arr[j]
            }
        }  
  }
  console.log(mtx)
  return mtx;
}

warpTunnel([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 2)
Wgg12
  • 181
  • 5