'its a n x n 2d matrix representing an image ,rotate the image by 90deg

its a n x n 2d matrix representing an image ,how to rotate the image by 90deg [[1,2,3],[4,5,6],[7,8,9]] to [[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]]))

the output is only showing [7,4,1]



Solution 1:[1]

You have an unconditional return statement in a loop. That doesn't make sense. The function always returns the first row.reverse(). Move th return statement out of the loop:

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]]))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jabaa