0

I'm going through problems at Project Euler to gain some experience with Ruby. The problem I'm working on now has me looking at a 1000-digit number and finding the sequence of five consecutive digits with the greatest product.

big_num = //1000-digit number
num_array = big_num.split('').map(&:to_i)
biggest = 0
prod = 1

(0..995).each do |x|
 (0..4).each do |y|
   prod *= num_array[x+y]
 end
 biggest = prod if prod > biggest
 prod = 0
end

puts biggest

This gives me 882, which is incorrect. To look for the problem, I had it print the values of x and y for each iteration. After the first iteration, it always prints out the five values of y as 7,3,1,6,7, which, when all multiplied together, equal 882. So, after the first iteration of the outer loop, it's not looking past the first five values of num_array, even though x seems to be incrementing properly. For the life of me, I can't figure out why it's behaving this way.

2 Answers 2

3

I would use the nice Enumerable method each_cons() to get all sequences of consecutive numbers, eliminating your outer loop. Secondly, I would use reduce(:*) to get each product, eliminating your inner loop. Finally I would call .max to get your answer.

num_array.each_cons(5).map{|seq| seq.reduce(:*)}.max

Voilà, one-liner.

Sign up to request clarification or add additional context in comments.

1 Comment

OP, accept this answer. This is the ruby way, this is the FP way, this is the nicely readable way.
1

You have to reinitialize prod with 1 instead of 0.

1 Comment

Thank you! I originally misread the problem as looking for sum, rather than product, so I just forgot to change that line to 1 instead of 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.