Estoy tratando de rotar una matriz bidimensional en javascript
el código fuera del bucle for para cambiar los valores funciona, pero cuando intento hacerlo dentro del bucle for, las variables no cambian
creo que es algún tipo de problema de referencia y lo busqué pero no puedo encontrar una solución a este problema
temp = tempboard[0][1]; console.log("unchanged:"+tempboard[0][1]+""+tempboard[6][1]); tempboard[0][1] = tempboard[6][1]; tempboard[6][1] = temp; console.log("changed:"+tempboard[0][1]+""+tempboard[6][1]); for(i = 0; i < board.length; i++){ for(j = 0; j < board[0].length; j++){ /*a = tempboard[i][j]; b = tempboard[j][i]; temp = a; a = b; b = temp; console.log(a+" "+b);*/ temp = tempboard[i][j]; console.log("unchanged:"+tempboard[i][j]+""+tempboard[j][i]); tempboard[i][j] = tempboard[j][i]; tempboard[j][i] = temp; console.log("changed:"+tempboard[j][i]+""+tempboard[i][j]); } }Creo que será más fácil construir una nueva matriz basada en la anterior.
En el siguiente código, se crea una nueva matriz a la inversa en función de la original.
arr = [[11, 12, 13], [21, 22, 23], [31, 32, 33], [41, 42, 43]]; console.log(JSON.stringify(Rotate2D(arr))); function Rotate2D(array) { //Create a new empty array with the same size as the original one. let returnArr = [...Array(array.length)].map(e => Array(array[0].length)); let maxIndexI = array.length - 1; let maxIndexJ = array[0].length - 1; //Fill the return array rotated for (let i = 0; i < array.length; i++) { for (let j = 0; j < array[0].length; j++) { returnArr[maxIndexI - i][maxIndexJ - j] = array[i][j] } } return returnArr; }Intente agregar la palabra clave "let" a su ciclo for, podría ser un problema de elevación;
for(let i = 0; i < board.length; i++){ for(let j = 0; j < board[0].length; j++){ /*a = tempboard[i][j]; b = tempboard[j][i]; temp = a; a = b; b = temp; console.log(a+" "+b);*/ temp = tempboard[i][j]; console.log("unchanged:"+tempboard[i][j]+""+tempboard[j][i]); tempboard[i][j] = tempboard[j][i]; tempboard[j][i] = temp; console.log("changed:"+tempboard[j][i]+""+tempboard[i][j]); } }