Advent of Code #6 (in Crystal)
Caleb Weeks

Caleb Weeks @sethcalebweeks

About: Christian, husband, father, functional programming enthusiast, software architect, mechanical engineer (in that order)

Location:
Syracuse, NY
Joined:
Mar 24, 2020

Advent of Code #6 (in Crystal)

Publish Date: Dec 6 '23
0 0

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 = File.read("input").strip

time, distance = input.split("\n").map do |line|
  line.scan(/\d+/).map(&.[0].to_i)
end

pairs = time.zip(distance)

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

puts part1

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

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

Comments 0 total

    Add comment