This is the first day I did not OOP it up, because I felt lazy. Part 2 is still nicely linear, but didn't bother to optimise Part 1. Here's Ruby:
require 'benchmark' def find_sum_of_uniques(candidates, check) skip = check / 2.to_f candidates.each do |x| next if x == skip candidates.each do |y| next if y == skip return true if x + y == check end end false end def find_invalid(numbers, preamble: 25) pointer = preamble candidates = numbers[0...preamble] while pointer < numbers.length check = numbers[pointer] unless find_sum_of_uniques(candidates, check) return check end candidates.shift candidates.push(numbers[pointer]) pointer += 1 end end def find_sum_set(numbers, match) pointer_left = 0 pointer_right = 1 sum = numbers[pointer_left..pointer_right].sum checks = 0 while sum != match checks += 1 # puts "#{match} != #{numbers[pointer_left]} + (...#{[pointer_right - pointer_left - 2, 0].max} numbers) + #{numbers[pointer_right]}" if sum < match pointer_right += 1 sum += numbers[pointer_right] elsif sum > match sum -= numbers[pointer_left] pointer_left += 1 end end numbers[pointer_left...pointer_right].tap do |x| # puts "#{match} == #{numbers[pointer_left..pointer_right].sort.join(" + ")}" puts "\nChecked #{checks} sets to find the sum set" end end numbers = File.readlines('input.txt').map(&:to_i) Benchmark.bmbm do |b| b.report do invalid = find_invalid(numbers, preamble: 25) set = find_sum_set(numbers, invalid) puts "xmas: #{set.minmax.sum}" end end
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
This is the first day I did not OOP it up, because I felt lazy. Part 2 is still nicely linear, but didn't bother to optimise Part 1. Here's Ruby: