开发者

Why does my Fibonacci series using Ruby's inject doesn't work?

This is embarrassing, I don't get why this line of code isn't returning to me the Fibonnacci series, but instead just a series of o开发者_运维问答nes.

(1..5).inject([1]) { |arr, x| x > 1 ? arr << arr.last + arr.last-1 : arr << 1; arr }

The code above is supposed to find the 1st six numbers in the series.

Could you please tell me what am I doing wrong?

Thank you as always.


arr.last-1 doesnt work, try arr[-2] instead:

p (1..5).inject([1]) { |arr, x| x > 1 ? arr << arr.last + arr[-2] : arr << 1 }
#=>[1, 1, 2, 3, 5, 8]

-edit- btw you don't need that ;arr at the end, << returns the array by default


arr.last-1 doesn't give you the second-to-last element of the array. It takes the last element and just subtracts one from it.

You want something like arr[arr.length - 2] or the fancy Ruby shortcut arr[-2].


I don't know Ruby, so this may be completely off, but it seems like this might be your culprit:

arr.last + arr.last-1

I don't think that this means "the last array element plus the element before it," but rather

arr.last + (arr.last)-1

Note that if you seed the array with 1, this would give you back 1 + 1 - 1 = 1, which means that your terms always evaluate to one, which probably isn't what you want.

Let me know if this is totally off, and hope this helps!


First off let's not forget the series actually starts with 0 and there is a far easier way to do this:

1.9.2-p290 :009 > 4.times.inject([0,1]) {|s| s + [s[-1] + s[-2]]}
 => [0, 1, 1, 2, 3, 5] 

Enjoy!


And yet another way in case you really like to use inject :)

(1..20).inject( [0, 1] ) { | fib | fib << fib.last(2).inject(:+) }
=> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946]


Shortest way:

(1..10).inject( [0, 1] ) { |sum| sum << sum.last(2).sum }
=> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜