DEV Community

Caleb Weeks
Caleb Weeks

Posted on

Advent of Code #11 (in Crystal)

I've been trying to add some meaningful commentary or thoughts along with each of these posts about Crystal, the puzzle, my solution, or coding in general. But today, I've got nothing. The puzzle wasn't all that complicated, and my code isn't all that great.

I gave up after day 11 last year, so hopefully I'll be able to get a little further this year!

Here's my code:

input = File.read("input").strip

lines = input.split("\n")

galaxies = lines.map_with_index do |line, row|
  line.scan(/#/).map { |match| {row, match.begin} }
end.flatten

empty_rows = (0..(lines.size - 1)).select do |row|
  !galaxies.find { |(x, _)| x == row }
end

empty_cols = (0..(lines[0].size - 1)).select do |col|
  !galaxies.find { |(_, y)| y == col }
end

expanded_universe = galaxies.map do |x, y|
  {
    x + empty_rows.select { |row| row < x }.size,
    y + empty_cols.select { |col| col < y }.size
  }
end

part1 = begin
  lengths = 0
  expanded_universe.each_cartesian(expanded_universe) do |(x1, y1), (x2, y2)|
    if {x1, y1} < {x2, y2}
      lengths += (x2 - x1).abs + (y2 - y1).abs
    end
  end
  lengths
end

puts part1

older_universe = galaxies.map do |x, y|
  {
    x.to_i64 + (empty_rows.select { |row| row < x }.size.to_i64 * 999_999_i64),
    y.to_i64 + (empty_cols.select { |col| col < y }.size.to_i64 * 999_999_i64)
  }
end

part2 = begin
  lengths = 0_i64
  older_universe.each_cartesian(older_universe) do |(x1, y1), (x2, y2)|
    if {x1, y1} < {x2, y2}
      lengths += (x2 - x1).abs + (y2 - y1).abs
    end
  end
  lengths
end

puts part2
Enter fullscreen mode Exit fullscreen mode

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay