Ben C.
Ben C.

Reputation: 1861

Nested each loop not working

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.

Upvotes: 0

Views: 112

Answers (2)

Mark Thomas
Mark Thomas

Reputation: 37507

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.

Upvotes: 3

Ashalynd
Ashalynd

Reputation: 12563

You have to reinitialize prod with 1 instead of 0.

Upvotes: 1

Related Questions