2014-07-11 55 views
2

我想創建一個紅寶石三角陣列。三角形數組是一個多維數組,其中第一個數組有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 

這幸運的取得了一些進展,它甚至返回的最後一個數組元素。但它沒有返回前四名。

回答

4

使用Enumerable#map

(1..6).map { |i| 
    (1..i).map { rand(100) } 
} 
# => [[24], [54, 57], [77, 86, 71], [94, 92, 0, 89], 
#  [86, 16, 0, 44, 91], [95, 26, 43, 35, 53, 54]] 
+0

尼斯。我正在寫類似的東西,但幾乎沒有那麼優雅。 –

+0

簡直太神奇了!很高興知道解決方案很簡單。 –

0

請問你的代碼,即使沒有拋出異常運行?我認爲array將是未定義的,因爲您只定義了@array

我認爲解決這將是這個最簡單的方法:但是在falsetru的回答中找到

def triangle_array 
    array = [[], [], [], [], [], []] 
    array[0] = [rand(100)] 
    2.times {array[1] << rand(100)} 
    3.times {array[2] << rand(100)} 
    4.times {array[3] << rand(100)} 
    5.times {array[4] << rand(100)} 
    6.times {array[4] << rand(100)} 
end 

一個很好的方式重寫方法。

+0

我剛纔重構了我的代碼。我的意思是說[[]] * 6 –

+0

'[[]] * 6'是一段非常有趣的代碼。它總共只有兩個陣列。 –

2

我想類似下面: -

Array.new(6) { |i| Array.new(i+1) { rand(100) } } 
# => => [[95], [7, 33], [77, 81, 32], [87, 1, 51, 70], 
# [49, 18, 87, 55, 21], [99, 43, 8, 23, 53, 35]] 

檢查這真棒Array::new方法。

0

的東西有點不同:

require 'matrix' 

n = 5 
m = 100 

Matrix.build(n) { |i,j| i<=j ? rand(m) : nil } 
     .column_vectors 
     .map { |e| e.to_a.compact } 
    #=> [[25], [56, 77], [34, 7, 86], [81, 78, 67, 85], [81, 28, 56, 2, 8]] 

我們:

x = Matrix.build(n) { |i,j| i<=j ? rand(m) : nil } 
    #=> Matrix[[25, 56, 34, 81, 81], [nil, 77, 7, 78, 28], 
    #   [nil, nil, 86, 67, 56], [nil, nil, nil, 85, 2], 
    #   [nil, nil, nil, nil, 8]] 

v = x.column_vectors 
    #=> [Vector[25, nil, nil, nil, nil], Vector[56, 77, nil, nil, nil], 
    # Vector[34, 7, 86, nil, nil], Vector[81, 78, 67, 85, nil], 
    # Vector[81, 28, 56, 2, 8]] 

v.map { |e| e.to_a.compact } 
    #=> [[25], [56, 77], [34, 7, 86], [81, 78, 67, 85], [81, 28, 56, 2, 8]]