0

所以这让我很头疼,我显然不太擅长编程。我有,

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

我想从NumArrayand 中获取一个元素,从 开始,在 LetterArray 中LetterArray[0]增加 var的次数,然后添加该元素(比如 var到数组中。然后开始在 中增加下一个数字,依此类推。然后打印去安慰。xyyNumArrayListOfLetters

我的目标是输出是这样的:[a, c, f, c, a, f, e, e, f, a].

我在如何在代码中解决这个问题上画了一个空白。

4

3 回答 3

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"]
于 2012-06-06T16:23:46.377 回答
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"]
于 2012-06-06T16:00:41.543 回答
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] }
于 2012-06-06T15:46:00.180 回答