Reputation: 183
I have an algorithm that stores the coordinates of an n by m matrix of characters in python. For example
a b
c d
would be stored as a list of coordinate-character pairs:
(0, 0) a (0, 1) b
(1, 0) c (1, 1) d
My python code is as below
def init_coordination(self):
list_copy = self.list[:]
row = 0
column = 0
coordination = {}
for char in list copy
if column >= self.column:
row += 1
column = 0
coordination[char] = (row, column)
column += 1
return coordination
I am trying to implement this algorithm in ruby, and I am guessing that the closest data structure to dictionary in ruby is hash. I need some suggestion with the following ruby code:
def self.init_coordination
position = Hash.new("Coordination of char")
row = 0
column = 0
@list.each do |char|
if column < @column
position[row, column] = char
column = column + 1
elsif column == @column
column = 0
row = row + 1
elsif row == @row
puts position
end
end
Also, how would I represent a list in ruby?
Upvotes: 0
Views: 617
Reputation: 156444
Lists in Ruby are called Arrays.
arr = []
arr.push(0) # => [0]
arr.concat([1,2,3]) # => [0, 1, 2, 3]
arr2d = [[0,0],[0,1],[1,0],[1,1]]
There is also a Matrix type which is probably more efficient and likely has more operations of interest.
require 'matrix'
matrix = Matrix[[0,0],[0,1],[1,0],[1,1]]
matrix[0,0] # => 0
Upvotes: 2