su matriz anxn 2d que representa una imagen, cómo rotar la imagen 90 grados [[1,2,3],[4,5,6],[7,8,9]] a [[7,4,1], [8,5,2],[9,6,3]]?
function rotate(matrix){ for(let r=0;r<matrix.length;r++){ for(let c=r;c<matrix[0].length;c++){ [matrix[r][c],matrix[c][r]] = [matrix[c][r],matrix[r][c]] } } for(row of matrix){ return row.reverse() } } console.log(rotate([[1,2,3],[4,5,6],[7,8,9]]))la salida solo muestra [7,4,1]
Tiene una declaración de retorno incondicional en un bucle. Eso no tiene sentido. La función siempre devuelve la primera row.reverse() . Mueva la declaración de retorno fuera del bucle:
function rotate(matrix){ for(let r=0;r<matrix.length;r++){ for(let c=r;c<matrix[0].length;c++){ [matrix[r][c],matrix[c][r]] = [matrix[c][r],matrix[r][c]] } } for(row of matrix){ row.reverse() } return matrix; } console.log(rotate([[1,2,3],[4,5,6],[7,8,9]]))