2012-06-06 43 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