1

I'm trying to rotate a matrix 90 degrees by transposing and rotating elements row by row, but the transposed part, the first i,j loop, isn't getting saved.

def rotate(matrix)

size = matrix.length

for i in 0..size-1
    for j in 0..size-1
      matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
    end
end

if size.even?
  for i in 0..size-1
    for j in 0..(size-1)/2
      matrix[i][j], matrix[i][size-1-j] = matrix[i][size-1-j], matrix[i][j]
    end
  end

else
  for i in 0..size-1
    for j in 0..((size-1)/2 + 1)
      matrix[i][j], matrix[i][size-1-j] = matrix[i][size-1-j], matrix[i][j]
    end
  end
end
matrix
end

would anyone have any explanations for that?

Imran Ali
  • 2,223
  • 2
  • 28
  • 41
Clyde Brown
  • 217
  • 4
  • 17
  • Is there any particular reason you are not using the [`matrix`](http://ruby-doc.org/stdlib/libdoc/matrix/rdoc/Matrix.html#method-i-transpose) stdlib library? – Jörg W Mittag May 08 '17 at 07:48

2 Answers2

0

The reason the code doesn't do anything is because you are swapping each pair of elements and then swapping them back.

For each pair i,j if i and j are the same then swapping doesn't do anything, and if they are different then the pair will be encountered twice, once when i is greater than j and once when j is greater than i. For example when i = 2 and j = 3, matrix[2][3] will be swapped with matrix[3][2], but then later when i = 3 and j = 2, they will be swapped back again.

You can fix the issue with a simple comparison test:

for i in 0..size-1
    for j in 0..size-1
      if i < j
        matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
    end
end
samgak
  • 23,944
  • 4
  • 60
  • 82
0

In my answer here the first step was to construct a helper to rotate (the matrix equivalent) of an array of equal-size arrays 90 degrees (anticlockwise). My solution was the following.

arr = [[ 1,  2,  3, 4,],
        [12, 13, 14, 5,],
        [11, 16, 15, 6,],
        [10,  9,  8, 7,]]

arr.map(&:reverse).transpose
  #=> [[4, 5, 6, 7],
  #    [3, 14, 15, 8],
  #    [2, 13, 16, 9],
  #    [1, 12, 11, 10]]
Community
  • 1
  • 1
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100