2011-03-23 84 views
5

我試圖按0-9和a-z的順序創建一個數字和字母列表。我有一個數組數組 value_array = ['0','1','2','3','4','5','6','7','8', ''','a','b','c','d', 'e','f','g','h','i','j','k',' l','m','n','o','p','q','r','s','t','u','v','w', 'x 」,‘Y’,‘Z’]使用多個陣列創建計數

和陣列用於組合的列表中,爲了是,這些數字可以產生用於字符的x個,讓我們說三

list_array = []

和一個用於當前字母和數字組合的數組(我將把i n要它推到列表陣列之前的字符串]

current_combo [「0」,「0」,「0」]

如何獲取值數組數爲當前的組合陣列,我可以創建像「 ['0','0','1'] ['0','0','2'] ['0','0','3'] ['0','0','4'] ['0','0','5'] ['0','0','6'] .. .. .. ['a','z','1'] .. .. 並最後到['z','z','z']?

這是我的代碼到目前爲止。對不起,如果它真的很瘋狂。我是一個菜鳥在此:

exponent = test.count('?') 


puts 36 ** exponent 

possible_characters = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d', 
'e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w', 
'x','y','z'] 

list = [] 

combo = [] 
end_combo = [] 

exponent.times do |e| 
    combo << '0' 
    end_combo << 'z' 
end 

puts combo.to_s 

while combo != end_combo 



end 
+2

參見http://stackoverflow.com/questions/ 5212884/ruby​​-generate-all-two-letter-words – 2011-03-23 21:16:28

回答

7
xs = ("0".."9").to_a + ("a".."z").to_a 
xs.product(xs, xs) 
# [["0", "0", "0"], ["0", "0", "1"], ..., ["z", "z", "y"], ["z", "z", "z"]] 

至於姆拉登指出,使用Ruby 1.9那就更簡單了:

(("0".."9").to_a + ("a".."z").to_a).repeated_permutation(3) 
+2

ohh。我喜歡Ruby – fl00r 2011-03-23 20:56:32

+1

其實在1.9.2中創建'xs'數組更容易:'[*?0..?9,*?a ..?z]'。 – 2011-03-24 10:53:10

2
value_array.repeated_permutation(n).to_a 
+2

我認爲OP想要一個笛卡爾產品,而不是一個置換。 – tokland 2011-03-23 19:42:38

+2

1.9.2有'repeated_permutation'這應該做的伎倆:http://www.ruby-doc.org/core/classes/Array.html#M000289 – 2011-03-23 21:06:37

+0

@tokland @Mladen你說得對。固定。 – sawa 2011-03-24 00:01:44