Here is my code, can anyone tell me where/why my algorithm is not accounting for the extra 10.
I do know that this code can be greatly shortened, but I'd rather keep it like this because I don't understand the other(much shorter) ways.
def solve18
current_line = 0
current_index = 0
numbers_below(current_line, current_index)
end
def numbers_below(current_line, current_index)
total = 0
numsUsed = Array.new
new_index = current_index
while current_line < 15
next_line = current_line + 1
next_numbers = get_next_numbers(next_line, new_index)
a = next_numbers[0]
b = next_numbers[1]
# B will be nil when on the first line
# I put this here to make sure that A is greater than B
if a == nil
a = -1
elsif b == nil
b = -1
end
if a.to_i > b.to_i
total += a.to_i
numsUsed << a.to_i
new_index = next_numbers[2]
elsif b.to_i > a.to_i
total += b.to_i
numsUsed << b.to_i
new_index = next_numbers[3]
end
current_line = next_line
end
total
end
def get_next_numbers(next_line, current_index)
numbersArray = Array.new
# This file exists and contains all lines/numbers
triangle = File.open("triangle_problem18.txt", "r")
lines = triangle.gets.to_s.split('\n')
line = lines[next_line - 1]
numbers = line.to_s.split(' ')
for i in 0..numbers.length
if i == current_index
numbersArray << numbers[current_index]
numbersArray << numbers[current_index + 1]
numbersArray << current_index
numbersArray << (current_index + 1)
end
end
numbersArray
end
Any help would be greatly appreciated.
This post has been edited by gbertoli3: 25 November 2011 - 01:04 AM

New Topic/Question
Reply




MultiQuote







|