Pattern matching with Ranges - Day 02 - Advent of Code 2023
Вставка
- Опубліковано 26 сер 2024
- In this video, you'll see a Ruby solution to parse the input data, model Game and Round classes, and determine which games meet the validity criteria for the Day 02, 2023 advent of code challenge.
We'll start by parsing the input to extract the game ID and rounds. Then build out Game and Round classes to represent the data. Next we'll create a #possible? method to check if a game meets the criteria of only having 12 red, 13 green, and 14 blue cubes.
For part 2, we'll find the minimum possible cubes needed to make each game valid. I refactor my solution to leverage Ruby iterator methods like #each_with_object and #all?. Finally, I use Ruby 3.1's new pattern matching on ranges for a clean validation check.
Advent of Code: adventofcode.com/
My Solutions: gist.github.co...
Playlist • Advent of Code
#adventofcode #ruby
In 1st puzzle I used:
start_cubes = {red: 12, green: 13, blue: 14}
start_cubes.default = 0
def possible_play? start_cubes, taken_cubes
taken_cubes.each{|color,number|
return false if start_cubes[color] < number
}
true
end
...
I set default of hash because I was thinking: is it possible that in some games (or in 2nd puzzle) they will try to pick up a cube of some other color.
Nice move with default