I've some questions for an exam and wondered if somebody could take a look at my Fibonacci sequence that is supposed to answer this question:
"select the element out of the array if its index is a Fibonacci number"
def fibonacci_sequence(max_num)
sequence = [1, 2]
loop do
fibonacci = sequence[-2] + sequence[-1]
break if fibonacci >= max_num
sequence << fibonacci
end
sequence
end
# array size
max_num = 100
numbers = []
1.upto(max_num) { |num| numbers << num }
fibonacci = fibonacci_sequence(max_num)
# select fibonacci numbers and assign array to variable
fibonacci_numbers = numbers.select { |num| fibonacci.include?(num) }
My thoughts were that I had to work out what the Fibonacci sequence was before I could select numbers out of the array that were Fibonacci. The thing is I already answer the question by assigning these numbers to the Fibonacci variable. I've then used a select method on the original numbers array even though I already know what the output is going to be.
Have I gone about this the right way? I'm thinking no!
numbers.select.with_index { |num, idx| fibonacci.include?(idx) }
\$\endgroup\$