2012-06-06 83 views
0

所以這是在傷害我的頭,我對編程不太好。我有,在ruby中求解迭代算法

LetterArray = [a,b,c,d,e,f,g] 
NumArray = [1,2,3,4,5,6,7,8,9,10] 
ListOfLetters = [] 

,我想從NumArray採取元素,開始在LetterArray[0],上去VAR x量的次LetterArray,並添加元素(比如VAR y到數組,然後開始上y上的下一個數字在NumArray,等等。然後打印ListOfLetters到控制檯

我的目標是輸出是這樣的:。[a, c, f, c, a, f, e, e, f, a]

我一片空白如何到g o關於這個代碼。

+1

這不是很清楚你想要什麼,你能解釋一下嗎? – nikhil

+0

看起來像一份工作/面試問答。有趣的問題,但。請發佈所有細節。 – Anil

+0

你可能想用[Array#slice](http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-slice)做些什麼。 –

回答

0

要麼我不明白你的問題描述,要麼你顯示的示例輸出在某個點之後是錯誤的。不管怎樣,也許這可以讓你開始:

letter_array = [*?a..?g] 
number_array = *1..10 
list_of_letters = [] 

number_array.inject(0) do |s, n| 
    i = s + n 
    list_of_letters << letter_array[i % letter_array.size - 1] 
    i 
end 

這將產生輸出["a", "c", "f", "c", "a", "g", "g", "a", "c", "f"]

另外,您也可以先創建索引,然後使用它們(這並不需要預先初始化list_of_letters):

indices = number_array.inject([]) { |a, n| a << (a.last || 0) + n ; a}) 
list_of_letters = indices.map { |i| letter_array[i%letter_array.size-1] } 
+0

我想我的示例輸出是錯誤的。但是 letter_array = ['E','F#','G#','A','B','C#','D'] number_array = [1,1,2,3,5,8, 13,21,34,55,89,144,233,377,610,987,1597] list_of_letters = [] number_array.inject(0)do | s,n | I = S + N list_of_letters << letter_array [我%letter_array.size - 1] 我 結束 p list_of_letters 就是我要去的......雖然,輸出給了我[ 「E」,「 F#,A,D,B,C#,B,B,A,G#,E,B,D,C# ,「D」,「D」,「E」] – Dustin

+0

但是當我手算它時,我得到了E,F#,G#,B,E,B,B ....等等。 我想在E上開始,上去1到F#,然後上1到G#,然後上到2,到B ....我希望這能讓這個更清楚嗎? – Dustin

0
ar = ('a'..'g').to_a.cycle #keeps on cycling 
res = [] 
p 10.times.map do |n| 
    n.times{ar.next} #cycle one time too short (the first time n is 0) 
    res << ar.next #cycle once more and store 
end 
p res #=>["a", "c", "f", "c", "a", "g", "g", "a", "c", "f"] 
2

像這樣的東西(如果我得到你的要求權課程)?

letter_array = %w[a b c d e f g] 
number_array = [1,2,3,4,5,6,7,8,9,10] 
list_of_letters = [] 

number_array.inject(0) do |offset, delta| 
    list_of_letters << letter_array[offset] 
    (offset + delta) % letter_array.size 
end 

p list_of_letters #=> ["a", "b", "d", "g", "d", "b", "a", "a", "b", "d"] 
+0

這就是我一直在尋找的,謝謝! – Dustin