Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
Code block support is not fully rolled out yet but likely will be in the middle of the event. Try to share solutions as both code blocks and using something such as https://topaz.github.io/paste/ or pastebin (code blocks to future proof it for when 0.19 comes out and since code blocks currently function in some apps and some instances as well if they are running a 0.19 beta)
Is there a leaderboard for the community?: We have a programming.dev leaderboard with the info on how to join in this post: https://programming.dev/post/6631465
🔒This post will be unlocked when there is a decent amount of submissions on the leaderboard to avoid cheating for top spots
Found a C per-char solution, that is, no lines, splitting, lookahead, etc. It wasn't even necessary to keep match lengths for the color names because they all have unique characters, e.g. 'b' only occurs in "blue" so then you can attribute the count to that color.
int main()
{
int p1=0,p2=0, id=1,num=0, r=0,g=0,b=0, c;
while ((c = getchar()) != EOF)
if (c==',' || c==';' || c==':') num = 0; else
if (c>='0' && c<='9') num = num*10 + c-'0'; else
if (c=='d') r = MAX(r, num); else
if (c=='g') g = MAX(g, num); else
if (c=='b') b = MAX(b, num); else
if (c=='\n') {
p1 += (r<=12 && g<=13 && b<=14) * id;
p2 += r*g*b;
r=g=b=0; id++;
}
printf("%d %d\n", p1, p2);
return 0;
}
Not too tricky today. Part 2 wasn't as big of a curveball as yesterday thankfully. I don't think it's the cleanest code I've ever written, but hey - the whole point of this is to get better at Rust, so I'll definitely be learning as I go, and coming back at the end to clean a lot of these up. I think for this one I'd like to look into a parsing crate like nom to clean up all the spliting and unwrapping in the two from() methods.
A solution in Nim language. Pretty straightforward code. Most logic is just parsing input + a bit of functional utils: allIt checks if all items in a list within limits to check if game is possible and mapIt collects red, green, blue cubes from each set of game.
import std/[strutils, strformat, sequtils]
type AOCSolution[T] = tuple[part1: T, part2: T]
type
GameSet = object
red, green, blue: int
Game = object
id: int
sets: seq[GameSet]
const MaxSet = GameSet(red: 12, green: 13, blue: 14)
func parseGame(input: string): Game =
result.id = input.split({':', ' '})[1].parseInt()
let sets = input.split(": ")[1].split("; ").mapIt(it.split(", "))
for gSet in sets:
var gs = GameSet()
for pair in gSet:
let
pair = pair.split()
cCount = pair[0].parseInt
cName = pair[1]
case cName:
of "red":
gs.red = cCount
of "green":
gs.green = cCount
of "blue":
gs.blue = cCount
result.sets.add gs
func isPossible(g: Game): bool =
g.sets.allIt(
it.red <= MaxSet.red and
it.green <= MaxSet.green and
it.blue <= MaxSet.blue
)
func solve(lines: seq[string]): AOCSolution[int]=
for line in lines:
let game = line.parseGame()
block p1:
if game.isPossible():
result.part1 += game.id
block p2:
let
minRed = game.sets.mapIt(it.red).max()
minGreen = game.sets.mapIt(it.green).max()
minBlue = game.sets.mapIt(it.blue).max()
result.part2 += minRed * minGreen * minBlue
when isMainModule:
let input = readFile("./input.txt").strip()
let (part1, part2) = solve(input.splitLines())
echo &"Part 1: The sum of valid game IDs equals {part1}."
echo &"Part 2: The sum of the sets' powers equals {part2}."
Hi there! Looks like you linked to a Lemmy community using a URL instead of its name, which doesn't work well for people on different instances. Try fixing it like this: [email protected]
Thanks! Your C solution includes main, whereas I do some stuff to parse the lines before hand. I think it would only be 1 extra character if I wrote it to parse the input manually, but I just care for ease of use with these AoC problems so I don't like counting that, makes it harder to read for me lol. Your solution is really inventive. I was looking for something like that, but didn't ever get to your conclusion. I wonder if that would be longer in my solution or shorter 🤔
Rust (Rank 7421/6311) (Time after start 00:32:27/00:35:35)
Extremely easy part 2 today, I would say easier than part 1 but they share the same sort of framework
Code Block
(Note lemmy removed some characters, code link shows them all)
use std::fs;
fn part1(input: String) -> i32 {
const RED: i32 = 12;
const GREEN: i32 = 13;
const BLUE: i32 = 14;
let mut sum = 0;
for line in input.lines() {
let [id, content] = line.split(": ").collect::>()[0..2] else { continue };
let id = id.split(" ").collect::>()[1].parse::().unwrap();
let marbles = content.split("; ").map(|x| { x.split(", ").collect::>() }).collect::>>();
let mut valid = true;
for selection in marbles {
for marble in selection {
let marble_split = marble.split(" ").collect::>();
let marble_amount = marble_split[0].parse::().unwrap();
let marble_color = marble_split[1];
if marble_color == "red" && marble_amount > RED {
valid = false;
break;
}
if marble_color == "green" && marble_amount > GREEN {
valid = false;
break;
}
if marble_color == "blue" && marble_amount > BLUE {
valid = false;
break;
}
}
}
if !valid {
continue;
}
sum += id;
}
return sum;
}
fn part2(input: String) -> i32 {
let mut sum = 0;
for line in input.lines() {
let [id, content] = line.split(": ").collect::>()[0..2] else { continue };
let id = id.split(" ").collect::>()[1].parse::().unwrap();
let marbles = content.split("; ").map(|x| { x.split(", ").collect::>() }).collect::>>();
let mut red = 0;
let mut green = 0;
let mut blue = 0;
for selection in marbles {
for marble in selection {
let marble_split = marble.split(" ").collect::>();
let marble_amount = marble_split[0].parse::().unwrap();
let marble_color = marble_split[1];
if marble_color == "red" && marble_amount > red {
red = marble_amount;
}
if marble_color == "green" && marble_amount > green {
green = marble_amount;
}
if marble_color == "blue" && marble_amount > blue {
blue = marble_amount;
}
}
}
sum += red * green * blue;
}
return sum;
}
fn main() {
let input = fs::read_to_string("data/input.txt").unwrap();
println!("{}", part1(input.clone()));
println!("{}", part2(input.clone()));
}
Oh, I misread the rules as each game having rounds of draws without replacement and the test data gave the same result for that reading, so when I confidently submitted my answer I got a bit of a surprise.
My (awful) Python solves. Much easier than day 1's, although I did run into an issue with trimming whitespace characters with my approach (Game 96 wouldn't flag properly).
Part 1
with open('02A_input.txt', 'r') as file:
data = file.readlines()
possibleGames=[]
for game in data:
# Find Game number
game = game.removeprefix("Game ")
gameNumber = int(game[0:game.find(":")])
# Break Game into rounds (split using semicolons)
game=game[game.find(":")+1:]
rounds=game.split(";")
# For each round, determine the maximum number of Red, Blue, Green items shown at a time
rgb=[0,0,0]
for round in rounds:
combos=round.split(",")
for combo in combos:
combo=combo.strip()
number=int(combo[0:combo.find(" ")])
if combo.endswith("red"):
if number>rgb[0]:
rgb[0]=number
elif combo.endswith("green"):
if number>rgb[1]:
rgb[1]=number
elif combo.endswith("blue"):
if number>rgb[2]:
rgb[2]=number
# If Red>12, Green>13, Blue>14, append Game number to possibleGames
if not (rgb[0]>12 or rgb[1]>13 or rgb[2]>14):
possibleGames.append(gameNumber)
print(sum(possibleGames))
Part 2
with open('02A_input.txt', 'r') as file:
data = file.readlines()
powers=[]
for game in data:
# Find Game number
game = game.removeprefix("Game ")
# Break Game into rounds (split using semicolons)
game=game[game.find(":")+1:]
rounds=game.split(";")
# For each round, determine the maximum number of Red, Blue, Green items shown at a time
# Note: This could be faster, since we don't need to worry about actual rounds
rgb=[0,0,0]
for round in rounds:
combos=round.split(",")
for combo in combos:
combo=combo.strip()
number=int(combo[0:combo.find(" ")])
if combo.endswith("red"):
if number>rgb[0]:
rgb[0]=number
elif combo.endswith("green"):
if number>rgb[1]:
rgb[1]=number
elif combo.endswith("blue"):
if number>rgb[2]:
rgb[2]=number
# Multiple R, G, B to find the "power" of the game
# Append Power to the list
powers.append(rgb[0]*rgb[1]*rgb[2])
print(sum(powers))
Done in C# Input parsing done with a mixture of splits and Regex (no idea why everyone hates it?) capture groups.
I have overbuilt for both days, but not tripped on any of the 'traps' in the input data - generally expecting the input to be worse than it is... too used to actual data from users
Input Parsing (common)
public class Day2RoundInput
{
private Regex gameNumRegex = new Regex("[a-z]* ([0-9]*)", RegexOptions.IgnoreCase);
public Day2RoundInput(string gameString)
{
var colonSplit = gameString.Trim().Split(':', StringSplitOptions.RemoveEmptyEntries);
var match = gameNumRegex.Match(colonSplit[0].Trim());
var gameNumberString = match.Groups[1].Value;
GameNumber = int.Parse(gameNumberString.Trim());
HandfulsOfCubes = new List();
var roundsSplit = colonSplit[1].Trim().Split(';', StringSplitOptions.RemoveEmptyEntries);
foreach (var round in roundsSplit)
{
HandfulsOfCubes.Add(new HandfulCubes(round));
}
}
public int GameNumber { get; set; }
public List HandfulsOfCubes { get; set; }
public class HandfulCubes
{
private Regex colourRegex = new Regex("([0-9]*) (red|green|blue)");
public HandfulCubes(string roundString)
{
var colourCounts = roundString.Split(',', StringSplitOptions.RemoveEmptyEntries);
foreach (var colour in colourCounts)
{
var matches = colourRegex.Matches(colour.Trim());
foreach (Match match in matches)
{
var captureOne = match.Groups[1];
var count = int.Parse(captureOne.Value.Trim());
var captureTwo = match.Groups[2];
switch (captureTwo.Value.Trim().ToLower())
{
case "red":
RedCount = count;
break;
case "green":
GreenCount = count;
break;
case "blue":
BlueCount = count;
break;
default: throw new Exception("uh oh");
}
}
}
}
public int RedCount { get; set; }
public int GreenCount { get; set; }
public int BlueCount { get; set; }
}
}
Task1
internal class Day2Task1:IRunnable
{
public void Run()
{
var inputs = GetInputs();
var maxAllowedRed = 12;
var maxAllowedGreen = 13;
var maxAllowedBlue = 14;
var allowedGameIdSum = 0;
foreach ( var game in inputs ) {
var maxRed = game.HandfulsOfCubes.Select(h => h.RedCount).Max();
var maxGreen = game.HandfulsOfCubes.Select(h => h.GreenCount).Max();
var maxBlue = game.HandfulsOfCubes.Select(h => h.BlueCount).Max();
if ( maxRed <= maxAllowedRed && maxGreen <= maxAllowedGreen && maxBlue <= maxAllowedBlue)
{
allowedGameIdSum += game.GameNumber;
Console.WriteLine("Game:" + game.GameNumber + " allowed");
}
else
{
Console.WriteLine("Game:" + game.GameNumber + "not allowed");
}
}
Console.WriteLine("Sum:" + allowedGameIdSum.ToString());
}
private List GetInputs()
{
List inputs = new List();
var textLines = File.ReadAllLines("Days/Two/Day2Input.txt");
foreach (var line in textLines)
{
inputs.Add(new Day2RoundInput(line));
}
return inputs;
}
}
Task2
internal class Day2Task2:IRunnable
{
public void Run()
{
var inputs = GetInputs();
var result = 0;
foreach ( var game in inputs ) {
var maxRed = game.HandfulsOfCubes.Select(h => h.RedCount).Max();
var maxGreen = game.HandfulsOfCubes.Select(h => h.GreenCount).Max();
var maxBlue = game.HandfulsOfCubes.Select(h => h.BlueCount).Max();
var power = maxRed*maxGreen*maxBlue;
Console.WriteLine("Game:" + game.GameNumber + " Result:" + power.ToString());
result += power;
}
Console.WriteLine("Day2 Task2 Result:" + result.ToString());
}
private List GetInputs()
{
List inputs = new List();
var textLines = File.ReadAllLines("Days/Two/Day2Input.txt");
//var textLines = File.ReadAllLines("Days/Two/Day2ExampleInput.txt");
foreach (var line in textLines)
{
inputs.Add(new Day2RoundInput(line));
}
return inputs;
}
}
Was pretty simple in Python with a regex to get the game number, and then the count of color. for part 2 instead of returning true/false whether the game is valid, you just max the count per color. No traps like in the first one, that I've seen, so it was surprisingly easy
def process_game(line: str):
game_id = int(re.findall(r'game (\d+)*', line)[0])
colon_idx = line.index(":")
draws = line[colon_idx+1:].split(";")
# print(draws)
if is_game_valid(draws):
# print("Game %d is possible"%game_id)
return game_id
return 0
def is_game_valid(draws: list):
for draw in draws:
red = get_nr_of_in_draw(draw, 'red')
if red > MAX_RED:
return False
green = get_nr_of_in_draw(draw, 'green')
if green > MAX_GREEN:
return False
blue = get_nr_of_in_draw(draw, 'blue')
if blue > MAX_BLUE:
return False
return True
def get_nr_of_in_draw(draw: str, color: str):
if color in draw:
nr = re.findall(r'(\d+) '+color, draw)
return int(nr[0])
return 0
# f = open("input.txt", "r")
f = open("input_real.txt", "r")
lines = f.readlines()
sum = 0
for line in lines:
sum += process_game(line.strip().lower())
print("Answer: %d"%sum)
Mostly an input parsing problem this time, but it was fun to use Hares tokenizer functions:
lua
-- SPDX-FileCopyrightText: 2023 Jummit
--
-- SPDX-License-Identifier: GPL-3.0-or-later
local colors = {"blue", "red", "green"}
local available = {red = 12, blue = 14, green = 13}
local possible = 0
local id = 0
local min = 0
for game in io.open("2.input"):lines() do
id = id + 1
game = game:gsub("Game %d+: ", "").."; "
local max = {red = 0, blue = 0, green = 0}
for show in game:gmatch(".-; ") do
for _, color in ipairs(colors) do
local num = tonumber(show:match("(%d+) "..color))
if num then
max[color] = math.max(max[color], num)
end
end
end
min = min + max.red * max.blue * max.green
local thisPossible = true
for _, color in ipairs(colors) do
if max[color] > available[color] then
thisPossible = false
break
end
end
if thisPossible then
possible = possible + id
end
end
print(possible)
print(min)
hare
// SPDX-FileCopyrightText: 2023 Jummit
//
// SPDX-License-Identifier: GPL-3.0-or-later
use strconv;
use types;
use strings;
use io;
use bufio;
use os;
use fmt;
const available: []uint = [12, 13, 14];
fn color_id(color: str) const uint = {
switch (color) {
case "red" => return 0;
case "green" => return 1;
case "blue" => return 2;
case => abort();
};
};
export fn main() void = {
const file = os::open("2.input")!;
defer io::close(file)!;
const scan = bufio::newscanner(file, types::SIZE_MAX);
let possible: uint = 0;
let min: uint = 0;
for (let id = 1u; true; id += 1) {
const line = match(bufio::scan_line(&scan)!) {
case io::EOF =>
break;
case let line: const str =>
yield strings::sub(
line,
strings::index(line, ": ") as size + 2,
strings::end);
};
let max: []uint = [0, 0, 0];
let tok = strings::rtokenize(line, "; ");
for (true) {
const show = match(strings::next_token(&tok)) {
case void =>
break;
case let show: str =>
yield show;
};
const pairs = strings::tokenize(show, ", ");
for (true) {
const pair: (str, str) = match(strings::next_token(&pairs)) {
case void =>
break;
case let pair: str =>
let tok = strings::tokenize(pair, " ");
yield (
strings::next_token(&tok) as str,
strings::next_token(&tok) as str
);
};
let color = color_id(pair.1);
let amount = strconv::stou(pair.0)!;
if (amount > max[color]) max[color] = amount;
};
};
if (max[0] <= available[0] && max[1] <= available[1] && max[2] <= available[2]) {
fmt::printfln("{}", id)!;
possible += id;
};
min += max[0] * max[1] * max[2];
};
fmt::printfln("{}", possible)!;
fmt::printfln("{}", min)!;
};
import collections
from .solver import Solver
class Day02(Solver):
def __init__(self):
super().__init__(2)
self.games = []
def presolve(self, input: str):
lines = input.rstrip().split('\n')
for line in lines:
draws = line.split(': ')[1].split('; ')
draws = [draw.split(', ') for draw in draws]
self.games.append(draws)
def solve_first_star(self):
game_id = 0
total = 0
for game in self.games:
game_id += 1
is_good = True
for draw in game:
for item in draw:
count, colour = item.split(' ')
if (colour == 'red' and int(count) > 12 or # pylint: disable=too-many-boolean-expressions
colour == 'blue' and int(count) > 14 or
colour == 'green' and int(count) > 13):
is_good = False
if is_good:
total += game_id
return total
def solve_second_star(self):
total = 0
for game in self.games:
minimums = collections.defaultdict(lambda: 0)
for draw in game:
for item in draw:
count, colour = item.split(' ')
minimums[colour] = max(minimums[colour], int(count))
power = minimums['red'] * minimums['blue'] * minimums['green']
total += power
return total
input = File.read("input.txt").lines
limits = {"red"=> 12, "green"=> 13, "blue"=> 14}
# possibles = [] of Int32
powers = [] of Int32
input.each do |line|
game = line.split(":")
id = game[0].split()[1].to_i
possible = true
min = {"red"=> 0, "green"=> 0, "blue"=> 0}
draws = game[1].split(";", &.split(",") do |cube|
cubeinfo = cube.split
num = cubeinfo[0].to_i
min[cubeinfo[1]] = num if num > min[cubeinfo[1]]
# unless num <= limits[cubeinfo[1]]
# possible = false
# break
# end
end )
powers.push(min.values.product)
# possibles.push(id) if possible
end
# puts possibles.sum
puts powers.sum
Yeah, it's still a very small language, not much community or tooling, but a pleasure to use. In practice it'll hit half the speeds of low level languages like rust and C, but with way less effort.
var list = new List((await File.ReadAllLinesAsync(@".\Day 2\PuzzleInput.txt")));
int conter = 0;
foreach (var line in list)
{
string[] split = line.Split(":");
int game = Int32.Parse( split[0].Split(" ")[1]);
string[] bagContents = split[1].Split(";");
var max = new Dictionary() { { "red", 0 }, { "green", 0 }, { "blue", 0 } };
foreach (var content in bagContents)
{
string pattern = @"(\d+) (\w+)";
MatchCollection matches = Regex.Matches(content, pattern);
foreach (Match match in matches)
{
int number = Int32.Parse(match.Groups[1].Value);
string color = match.Groups[2].Value;
max[color] = (max[color] >= number)? max[color] : number;
}
}
conter += (max["red"] <= 12 && max["green"] <= 13 && max["blue"] <= 14) ? game : 0;
}
Console.WriteLine(conter);
Part 2:
var list = new List((await File.ReadAllLinesAsync(@".\Day 2\PuzzleInput.txt")));
int conter = 0;
foreach (var line in list)
{
string[] split = line.Split(":");
int game = Int32.Parse(split[0].Split(" ")[1]);
string[] bagContents = split[1].Split(";");
var max = new Dictionary();
foreach (var content in bagContents)
{
string pattern = @"(\d+) (\w+)";
MatchCollection matches = Regex.Matches(content, pattern);
foreach (Match match in matches)
{
int number = Int32.Parse(match.Groups[1].Value);
string color = match.Groups[2].Value;
if (!max.ContainsKey(color))
max[color] = number;
else if(max[color] < number)
max[color] = number;
}
}
conter += max.Values.Aggregate(1, (total, value) => total * value );
}
Console.WriteLine(conter);
It was confusing. It took me 3 tries to write the parser. The first time I didn’t realize there were multiple observations per game and the second time for some reason I was convinced the color came first.
Just getting started with Rust, part 1 took a long time. Really amazed when I saw part 2, just needed to add 2 lines and was done due to the approach I had taken.
Feedback more than welcome!
use std::{
cmp, fs,
io::{BufRead, BufReader},
};
fn main() {
cube_conundrum_complete();
}
fn cube_conundrum_complete() {
// Load the data file
let filename = "./data/input_data/day_2_cubes.txt";
let file = match fs::File::open(filename) {
Ok(f) => f,
Err(e) => {
eprintln!("Error opening file: {}", e);
return;
}
};
let reader = BufReader::new(file);
// iniatiate final results
let mut total = 0;
let mut total_power = 0;
// loop over the games in the file
for _line in reader.lines() {
// Handle the data and extract game number and maximum number of cubes per color
let (game_number, max_green, max_red, max_blue) = cube_conundrum_data_input(_line.unwrap());
// Calculate the power for the day 2 result
total_power += max_green * max_red * max_blue;
//Calculate if the game was possible with the given number of cubes
let result = cube_conundrum_game_possible(game_number, max_green, max_red, max_blue);
total += result;
}
// print the final results
println!("total part 1: {}", total);
println!("total part 2: {}", total_power);
}
fn cube_conundrum_data_input(game_input: String) -> (i32, i32, i32, i32) {
// Split the game number from the draws
let (game_part, data_part) = game_input.split_once(":").unwrap();
// Select the number of the round and parse into an integer
let game_number: i32 = game_part
.split_once(" ")
.unwrap()
.1
.parse::()
.expect("could not parse gamenumber to integer");
// Split the data part into a vector both split on , and ; cause we only care about he maximum per color
let parts: Vec<&str> = data_part
.split(|c| c == ',' || c == ';')
.map(|part| part.trim())
.collect();
// Set the intial values for the maximum per color to 0
let (mut max_green, mut max_red, mut max_blue) = (0, 0, 0);
// Loop over the different draws split them into color and nubmer of cubes, update maximum number of cubes
for part in parts.iter() {
let (nr_cubes_text, color) = part.split_once(" ").unwrap();
let nr_cubes = nr_cubes_text
.parse::()
.expect("could not parse to integer");
match color {
"green" => max_green = cmp::max(max_green, nr_cubes),
"red" => max_red = cmp::max(max_red, nr_cubes),
"blue" => max_blue = cmp::max(max_blue, nr_cubes),
_ => println!("unknown color: {}", color),
};
}
return (game_number, max_green, max_red, max_blue);
}
fn cube_conundrum_game_possible(
game_number: i32,
max_green: i32,
max_red: i32,
max_blue: i32,
) -> i32 {
// Compare the number of seen cubes per game with the proposed number. Return the game number if it was possible, otherwise 0
let (comparison_red, comparison_green, comparison_blue) = (12, 13, 14);
if max_green > comparison_green || max_red > comparison_red || max_blue > comparison_blue {
return 0;
};
game_number
}
I'll only post the actual parsing and solution. I have written some helpers which are in other files, as is the main function. For the full code, please see my github repo.
Solution
structure Draw (α : Type) where
red : α
green : α
blue : α
deriving Repr
structure Game where
id : Nat
draw : List $ Draw Nat
deriving Repr
def parse (input : String) : Option $ List Game :=
let lines := input.splitTrim (. == '\n')
let lines := lines.filter (not ∘ String.isEmpty)
let parse_single_line : (String → Option Game):= λ (l : String) ↦ do
let parse_id := λ (s : String) ↦ do
let rest ← if s.startsWith "Game " then some (s.drop 5) else none
rest.toNat?
let parse_draw := λ (s : String) ↦ do
let s := s.splitTrim (· == ',')
let findAndRemoveTail := λ (s : String) (t : String) ↦
if s.endsWith t then
some $ String.dropRight s (t.length)
else
none
let update_draw_parse := λ (pd : Option (Draw (Option String))) (c : String) ↦ do
let old ← pd
let red := findAndRemoveTail c " red"
let green := findAndRemoveTail c " green"
let blue := findAndRemoveTail c " blue"
match red, green, blue with
| some red, none, none => match old.red with
| none => some $ {old with red := some red}
| some _ => none
| none, some green, none => match old.green with
| none => some $ {old with green := some green}
| some _ => none
| none, none, some blue => match old.blue with
| none => some $ {old with blue := some blue}
| some _ => none
| _, _, _ => none
let parsed_draw ← s.foldl update_draw_parse (some $ Draw.mk none none none)
let parsed_draw := {
red := String.toNat? <$> parsed_draw.red,
green := String.toNat? <$> parsed_draw.green,
blue := String.toNat? <$> parsed_draw.blue : Draw _}
let extractOrFail := λ (s : Option $ Option Nat) ↦ match s with
| none => some 0
| some none => none
| some $ some x => some x
let red ← extractOrFail parsed_draw.red
let green ← extractOrFail parsed_draw.green
let blue ← extractOrFail parsed_draw.blue
pure { red := red, blue := blue, green := green : Draw _}
let parse_draws := λ s ↦ List.mapM parse_draw $ s.splitTrim (· == ';')
let (id, draw) ← match l.splitTrim (· == ':') with
| [l, r] => Option.zip (parse_id l) (parse_draws r)
| _ => none
pure { id := id, draw := draw}
lines.mapM parse_single_line
def part1 (games : List Game) : Nat :=
let draw_possible := λ g ↦ g.red ≤ 12 && g.green ≤ 13 && g.blue ≤ 14
let possible := flip List.all draw_possible
let possible_games := games.filter (possible ∘ Game.draw)
possible_games.map Game.id |> List.foldl Nat.add 0
def part2 (games : List Game) : Nat :=
let powerOfGame := λ (g : Game) ↦
let minReq := λ (c : Draw Nat → Nat) ↦
g.draw.map c |> List.maximum? |> flip Option.getD 0
minReq Draw.red * minReq Draw.green * minReq Draw.blue
let powers := games.map powerOfGame
powers.foldl Nat.add 0