Ruby如何创建二维数组字母

时间:2021-09-01 21:34:41

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?

我正在尝试创建一个NxN的二维数组,并用字母填充它。我有一个创建二维数组的方法,但是如何遍历每一行和一列,为它分配一个随机字母?

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

3 个解决方案

#1


3  

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

如果我可以建议...... Matrix库非常有用:

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

#2


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

#3


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.

...或者您可以将2D数组展平为具有N * N个元素的简单数组,并使用两个索引上的简单算法来检索和设置矩阵元素,从而使初始化和迭代非常容易。虽然这可能会带来其他一些操作的问题,但这取决于您打算如何使用此结构。

#1


3  

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

如果我可以建议...... Matrix库非常有用:

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

#2


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

#3


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.

...或者您可以将2D数组展平为具有N * N个元素的简单数组,并使用两个索引上的简单算法来检索和设置矩阵元素,从而使初始化和迭代非常容易。虽然这可能会带来其他一些操作的问题,但这取决于您打算如何使用此结构。