0

Estoy tratando de rotar matrices rectangulares (cuadradas incluidas) en Ruby, pero me hallo con el problema de que no sé como declarar (sin inicializar de preferencia) una matriz de este tipo.

Investigando en internet encontré una clase aparentemente mágica llamada Matrix y estoy tratando de usarla con precarios resultados.

Mi mayor problema con esta librería es que no puedo usar algo como

rows = array.length
cols = array[0].length
returnedArray=Matrix.empty(cols, rows)

ya que uno de los parámetros para matrices rectangulares es que un parámetro sea cero.

Este es mi código hasta ahora:

require 'matrix'

def rotate(matrix, direction)
  if matrix.length == 0
    return matrix
  end
  if direction == "clockwise"
    return rotateRight(matrix)
  else
    return rotateLeft(matrix)
  end
end

def rotateRight(array)
    rows = array.length
    cols = array[0].length

    returnedArray=Matrix.empty(cols, 0)

    array.each_with_index do |e, row, col|
      returnedArray[col][(rows-1) - row] = e
    end
    return returnedArray
end

def rotateLeft(array)
  rows = array.length
  cols = array[0].length
  returnedArray=Matrix.empty(cols, 0)

  array.each_with_index do |e, row, col|
    returnedArray[(cols - 1) - col][row] = e
  end
  return returnedArray
end

matrix = [[1,2,3],
         [4,5,6],
         [7,8,9]]

rotate(matrix, 'counter-clockwise')

Lo que me produce un error:

main.rb:32:in -': nil can't be coerced into Integer (TypeError) from main.rb:32:inblock in rotateLeft' from main.rb:31:in each' from main.rb:31:ineach_with_index' from main.rb:31:in rotateLeft' from main.rb:10:inrotate' from main.rb:41:in `'

Actualización, he hecho la conversión de Matrix a Array usando el operador splat, pero aún así, se observa que la inserción en el arreglo no es la correcta, aquí un fragmento:

def rotateLeft(array)
  rows = array.length
  cols = array[0].length
  #returnedArray=Matrix.empty(cols, 0)
  returnedArray = Array.new(cols, Array.new(rows))

  matrixArray = Matrix[*array]

  puts matrixArray
  puts Matrix[*returnedArray]

  matrixArray.each_with_index do |e, row, col|
    puts "[#{row},#{col}]=#{e}"
    puts "returnedArray[#{cols - 1} - #{col} =>#{(cols - 1) - col}][#{row}] = #{e}"
    returnedArray[(cols - 1) - col][row] = e
    puts Matrix[*returnedArray]
  end
  puts Matrix[*returnedArray]
  return returnedArray
end

Salida:

Matrix[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Matrix[[, , ], [, , ], [, , ]]
[0,0]=1
returnedArray[2 - 0 =>2][0] = 1
Matrix[[1, , ], [1, , ], [1, , ]]
[0,1]=2
returnedArray[2 - 1 =>1][0] = 2
Matrix[[2, , ], [2, , ], [2, , ]]
[0,2]=3
returnedArray[2 - 2 =>0][0] = 3
Matrix[[3, , ], [3, , ], [3, , ]]
[1,0]=4
returnedArray[2 - 0 =>2][1] = 4
Matrix[[3, 4, ], [3, 4, ], [3, 4, ]]
[1,1]=5
returnedArray[2 - 1 =>1][1] = 5
Matrix[[3, 5, ], [3, 5, ], [3, 5, ]]
[1,2]=6
returnedArray[2 - 2 =>0][1] = 6
Matrix[[3, 6, ], [3, 6, ], [3, 6, ]]
[2,0]=7
returnedArray[2 - 0 =>2][2] = 7
Matrix[[3, 6, 7], [3, 6, 7], [3, 6, 7]]
[2,1]=8
returnedArray[2 - 1 =>1][2] = 8
Matrix[[3, 6, 8], [3, 6, 8], [3, 6, 8]]
[2,2]=9
returnedArray[2 - 2 =>0][2] = 9
Matrix[[3, 6, 9], [3, 6, 9], [3, 6, 9]]
Matrix[[3, 6, 9], [3, 6, 9], [3, 6, 9]]

¿Qué necesito modificar para que funcione mi programa que rota matrices?

4
  • El error está aquí: array.each_with_index do |e, row, col|, dado que each_with_index te regresa solo dos variables, así que e tiene el valor del arreglo, row el índice y col tiene nil. ¿Exactamente qué buscas hacer en ese fragmento de código?
    – Gerry
    el 3 may. 2018 a las 21:07
  • @Gerry ese código lo copié mira ruby-doc.org/stdlib-2.2.3/libdoc/matrix/rdoc/… el 3 may. 2018 a las 22:10
  • El error está aquí: Array.new(cols, Array.new(rows)) pues debería ser Array.new(cols) { Array.new(rows) }. La diferencia es que en el primer fragmento se crea un arreglo con rows y lo asigna a cada elemento de cols, pero es el mismo arreglo; en cambio, en el segundo se crea un arreglo distinto para cada elemento de cols.
    – Gerry
    el 4 may. 2018 a las 16:44
  • 1
    Gracias! no me dí cuenta de ese detalle el 4 may. 2018 a las 17:04

1 respuesta 1

3

Actualización

Para aprovechar la clase Matrix te recomiendo iniciar creando el objeto Matrix y pasarlo como argumento al método rotate; luego, en los métodos específicos para rotar (i.e. rotate_left y rotate_right), utiliza arreglos vacíos en lugar de objetos Matrix vacíos:

require 'matrix'

def rotate(matrix, direction)
  return matrix if matrix.empty?

  if direction == "clockwise"
    rotate_right(matrix)
  else
    rotate_left(matrix)
  end
end

def rotate_right(matrix)
  rows = matrix.row_size
  cols = matrix.column_size

  result_matrix = Array.new(rows) { Array.new(cols) }

  matrix.each_with_index do |e, row, col|
    result_matrix[col][(rows-1) - row] = e
  end

  result_matrix
end

def rotate_left(matrix)
  rows = matrix.row_size
  cols = matrix.column_size

  result_matrix = Array.new { rows, Array.new(cols) }

  matrix.each_with_index do |e, row, col|
    result_matrix[(cols - 1) - col][row] = e
  end

  result_matrix
end

matrix = Matrix[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

rotate(matrix, 'counter-clockwise')
#=> [[3, 6, 9], [2, 5, 8], [1, 4, 7]]

rotate(matrix, 'clockwise')
#=> [[7, 4, 1], [8, 5, 2], [9, 6, 3]]

Además, podrías limpiar un poco tu código (evitar la repetición) utilizando sólo una función y logrando el mismo resultado:

require 'matrix'

def rotate(matrix, direction)
  return matrix if matrix.empty?

  rows = matrix.row_size
  cols = matrix.column_size

  result_matrix = Array.new(rows) { Array.new(cols) }

  matrix.each_with_index do |e, row, col|
    if direction == "clockwise"
      result_matrix[col][(rows - 1) - row] = e
    else
      result_matrix[(cols - 1) - col][row] = e
    end
  end

  result_matrix
end

matrix = Matrix[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

rotate(matrix, 'counter-clockwise')
#=> [[3, 6, 9], [2, 5, 8], [1, 4, 7]]

rotate(matrix, 'clockwise')
#=> [[7, 4, 1], [8, 5, 2], [9, 6, 3]]

Como opción alterna, podrías utilizar los métodos Array#transpose y Array#reverse, a través de los cuales podrías lograr la rotación que buscas; por ejemplo:

matrix = [[1,2,3], [4,5,6], [7,8,9]]

# Rotación a la izquierda:
matrix.map(&:reverse).transpose
#=> [[3, 6, 9], [2, 5, 8], [1, 4, 7]]

# Rotación a la derecha:
matrix.transpose.map(&:reverse)
#=> [[7, 4, 1], [8, 5, 2], [9, 6, 3]]

Sin embargo (tal como se resalta en los comentarios) esta solución tiene un desempeño pobre y no se recomienda para matrices grandes.

7
  • definitivamente esa debe de ser una muy mala práctica debido a su desempeño el 3 may. 2018 a las 22:13
  • @RuslanLópezCarro En efecto, el desempeño puede ser pobre para matrices grandes, pero para matrices pequeñas no es problema.
    – Gerry
    el 3 may. 2018 a las 22:30
  • @RuslanLópezCarro He actualizado la respuesta modificando tu código para que, utilizando tu lógica y aprovechando la clase Matrix, se muestre el resultado esperado.
    – Gerry
    el 4 may. 2018 a las 2:58
  • A simple vista se puede decir que tu código unicamente funciona para matrices de 3x3 el 4 may. 2018 a las 15:46
  • @RuslanLópezCarro Cierto, olvidé actualizar esos valores, pero ya he actualizado la respuesta.
    – Gerry
    el 4 may. 2018 a las 15:49

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.