0

I am trying to create a 2d array of NxN, and populate it with letters. I have a method to create the 2d array, but how can I iterate through each row and column an assign a random letter to it?

class Array2D
    def initialize(width, height)
        @data = Array.new(width) { Array.new(height) }
    end
    def [](x, y)
        @data[x][y]
    end
    def []=(x, y, value)
        @data[x][y] = value
    end
end
4
  • If it is NxN, then why does initialize take width and height separately?
    – sawa
    Nov 18, 2013 at 13:02
  • If it is NxN, then why does initialize take width and height separately?
    – sawa
    Nov 18, 2013 at 13:14
  • @sawa You can say that again!
    – vgoff
    Nov 20, 2013 at 7:32
  • If it is NxN, then why does initialize take width and height separately?
    – sawa
    Nov 20, 2013 at 8:48

3 Answers 3

3

If I may suggest... the Matrix library is pretty useful:

require 'matrix'
m = Matrix.build(5, 5) {|row, col| ('a'..'z').to_a[rand(26)] }

# => Matrix[["u", "f", "p", "o", "z"], ["h", "y", "e", "e", "l"], ["p", "q", "j", "i", "w"], ["r", "i", "d", "g", "w"], ["f", "a", "m", "u", "f"]]
0

You could use map!:

def initialize(width, height)
    @data = Array.new(width) { Array.new(height) }
    letters = ('a'..'z').to_a
    @data.map!{|row| row.map!{letters.sample}}
end

p Array2D.new(2,2) #=> <Array2D:0x1d43a50 @data=[["k", "x"], ["h", "f"]]>
0

... or you can just flatten the 2D array into a simple array with N*N elements and use simple arithmetic on two indexes for retrieving and setting matrix elements, making initialisations and iterations extremely easy. Although this might bring problems with some other operations, it depends on how you intend to use this structure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.