DEV Community

Caleb Weeks
Caleb Weeks

Posted on

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

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

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

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

part1 = do |game, subsets| do |subset| { |color, number| number <= bag[color] }.all?

puts part1

part2 = do |subsets|
  subsets.reduce do |set, cubes|
    set.merge(cubes) { |_, old, new| Math.max(old, new) }

puts part2
Enter fullscreen mode Exit fullscreen mode

Top comments (0)