Advent of Code #6 (in Crystal)

sethcalebweeks

Caleb Weeks

Posted on December 6, 2023

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 = 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
💖 💪 🙅 🚩
sethcalebweeks
Caleb Weeks

Posted on December 6, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Advent of Code #14 (in Crystal)
crystal Advent of Code #14 (in Crystal)

December 17, 2023

Advent of Code #12 (in Crystal)
crystal Advent of Code #12 (in Crystal)

December 17, 2023

Advent of Code #13 (in Crystal)
crystal Advent of Code #13 (in Crystal)

December 17, 2023

Advent of Code #11 (in Crystal)
crystal Advent of Code #11 (in Crystal)

December 12, 2023

Advent of Code #7 (in Crystal)
crystal Advent of Code #7 (in Crystal)

December 7, 2023