DEV Community

Caleb Weeks
Caleb Weeks

Posted on

2

Advent of Code #2 (in Crystal)

Nothing extraordinary about today's problem. Here's a few things I learned about Crystal while solving this one:

  • You can define type aliases using alias (shocker)
  • Somewhat unintuitively (to me, at least), you cannot call the map method with parentheses. Instead, you wrap the anonymous function in braces ({}) and then you can chain methods after that. I think it's idiomatic to leave a space between map and the braces, but that means you end up with code that looks like map {|x| x + 1}.sum.
  • Destructuring arrays works as expected (without the surrounding square brackets), but destructuing hashes isn't really a thing. You can destructure the key/value pair (which is basically an array), or you can destructure the keys or values separately after turning them into arrays.
input = File.read("input").strip

alias Games = Hash(Int32, Subsets)
alias Subsets = Array(Subset)
alias Subset = Hash(String, Int32)

games = input.split("\n").reduce(Games.new) do |games, line|
  game, subsets = line.split(":")
  game_number = game[5..].to_i
  subsets = subsets.split(';').map do |subset|
    subset.split(',').reduce(Subset.new) do |set, cubes|
      number, color = cubes.strip.split(' ')
      set.merge({color => number.to_i})
    end
  end
  games.merge({game_number => subsets})
end

bag = {
  "red" => 12,
  "green" => 13,
  "blue" => 14
}

part1 = games.select do |game, subsets|
  subsets.map do |subset|
    subset.map { |color, number| number <= bag[color] }.all?
  end.all?
end.keys.sum

puts part1

part2 = games.values.map do |subsets|
  subsets.reduce do |set, cubes|
    set.merge(cubes) { |_, old, new| Math.max(old, new) }
  end.values.product
end.sum

puts part2
Enter fullscreen mode Exit fullscreen mode

Image of AssemblyAI tool

Challenge Submission: SpeechCraft - AI-Powered Speech Analysis for Better Communication

SpeechCraft is an advanced real-time speech analytics platform that transforms spoken words into actionable insights. Using cutting-edge AI technology from AssemblyAI, it provides instant transcription while analyzing multiple dimensions of speech performance.

Read full post

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