DEV Community

Caleb Weeks
Caleb Weeks

Posted on

Advent of Code #6 (in Crystal)

Yesterday, I got by without optimizing my program for part 2. Although it took hours to compute, I got the right answer in the end.

Today, that was not an option. The numbers grow so large, that calculating all of them is impractical if not impossible. Thankfully, it was fairly straightforward to come up with a shortcut.

Just like this post, the code is short:

input ="input").strip

time, distance = input.split("\n").map do |line|

pairs =

part1 = do |time, distance|
  (1..(time - 1)).map { |x| x * (time - x) }.count { |x| x > distance }

puts part1

time, distance = input.split("\n").map do |line|
  line.gsub(' ', "").scan(/\d+/)[0][0].to_i64

part2 = time - (1..(time - 1)).take_while do |x|
  x.to_i64 * (time - x.to_i64) <= distance
end.size * 2 - (time % 2 == 0 ? 1 : 0)

puts part2
Enter fullscreen mode Exit fullscreen mode

Top comments (0)