Skip to content

Instantly share code, notes, and snippets.

@faried
Created December 2, 2023 22:10
Show Gist options
  • Save faried/272fd9e16170885e124993a42b512d01 to your computer and use it in GitHub Desktop.
Save faried/272fd9e16170885e124993a42b512d01 to your computer and use it in GitHub Desktop.
defmodule Day02.Parser do
import NimbleParsec
# Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
game_id = ignore(string("Game ")) |> integer(min: 1, max: 4) |> unwrap_and_tag(:game_id)
red = replace(string("red"), :red)
green = replace(string("green"), :green)
blue = replace(string("blue"), :blue)
color = choice([red, green, blue])
cube_separator = optional(string(", "))
cube = integer(min: 1, max: 4) |> ignore(string(" ")) |> concat(color) |> ignore(optional(cube_separator))
round_separator = optional(string("; "))
round = times(cube, min: 1) |> ignore(round_separator) |> tag(:round)
rounds = times(round, min: 1) |> tag(:rounds)
defparsec :game, game_id |> ignore(string(": ")) |> concat(rounds) |> eos(), debug: true
end
iex(1)> line = "Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue"
iex(2)> Day02.Parser.game(line)
{:ok,
[
game_id: 2,
rounds: [
round: [1, :blue, 2, :green],
round: [3, :green, 4, :blue, 1, :red],
round: [1, :green, 1, :blue]
]
], "", %{}, {1, 0}, 64}
iex(3)>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment