我想創建一個紅寶石三角陣列。三角形數組是一個多維數組,其中第一個數組有1個元素,第二個數組有2個元素,第三個數組有3個元素,依此類推。它看起來像這樣。紅寶石 - 創建三角陣列
[[1],[3,7],[2,4,6],[9,8,13,11],[10,21,17,24,35],[47,26,31,55,72,49]
=> Each next array has 1 more element than the previous array.
在三角形的格式,它會是這個樣子
[1]
[3,7]
[2,4,6]
[9,8,13,11]
[10,21,17,24,35]
[47,26,31,55,72,49]
正如你可以看到,我想在我的陣列中的所有值是隨機的。
1st array => I would like it to have 1 random element
2nd array => I would like it to have 2 random elements
3rd array => I would like it to have 3 random elements
等等。
好吧,我重構原始代碼,讓這個
def triangle_array(n)
@array = [[]] * n
index = 0
while index < n
@array[n] = (1..100).to_a.shuffle.first(n)
index += 1
end
return @array
end
這幸運的取得了一些進展,它甚至返回的最後一個數組元素。但它沒有返回前四名。
尼斯。我正在寫類似的東西,但幾乎沒有那麼優雅。 –
簡直太神奇了!很高興知道解決方案很簡單。 –