Skip to content

Commit

Permalink
2nd day
Browse files Browse the repository at this point in the history
  • Loading branch information
majcn committed Dec 2, 2023
1 parent 2e888b5 commit 00981d6
Show file tree
Hide file tree
Showing 2 changed files with 110 additions and 0 deletions.
5 changes: 5 additions & 0 deletions data/examples/02.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red
Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red
Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green
105 changes: 105 additions & 0 deletions src/bin/02.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
advent_of_code::solution!(2);

#[derive(Debug)]
struct Game {
id: u32,
sets: Vec<Set>,
}

#[derive(Debug)]
struct Set {
red: u32,
green: u32,
blue: u32,
}

impl From<&str> for Set {
fn from(item: &str) -> Self {
let mut result = Set {
red: 0,
green: 0,
blue: 0,
};

item.split(", ")
.filter_map(|x| x.split_once(' '))
.for_each(|(n, color)| match color {
"red" => result.red = n.parse().unwrap(),
"green" => result.green = n.parse().unwrap(),
"blue" => result.blue = n.parse().unwrap(),
_ => unreachable!(),
});

result
}
}

impl From<&str> for Game {
fn from(item: &str) -> Self {
let (game_id, game_data) = item.split_once(": ").unwrap();

let id = game_id[5..].parse().unwrap();
let sets = game_data.split("; ").map(Set::from).collect();

Game { id, sets }
}
}

fn parse_data(input: &str) -> Vec<Game> {
input.lines().map(Game::from).collect()
}

pub fn part_one(input: &str) -> Option<u32> {
let data = parse_data(input);

let limit = Set {
red: 12,
green: 13,
blue: 14,
};

let result =
data.into_iter()
.filter(|game| {
!game.sets.iter().any(|set| {
set.red > limit.red || set.green > limit.green || set.blue > limit.blue
})
})
.map(|game| game.id)
.sum();

Some(result)
}

pub fn part_two(input: &str) -> Option<u32> {
let data = parse_data(input);

let result = data
.into_iter()
.map(|game| Set {
red: game.sets.iter().map(|x| x.red).max().unwrap(),
green: game.sets.iter().map(|x| x.green).max().unwrap(),
blue: game.sets.iter().map(|x| x.blue).max().unwrap(),
})
.map(|set| set.red * set.green * set.blue)
.sum();

Some(result)
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_part_one() {
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(8));
}

#[test]
fn test_part_two() {
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(2286));
}
}

0 comments on commit 00981d6

Please sign in to comment.