Compare commits
2 Commits
331755f1cf
...
b165cfce48
| Author | SHA1 | Date | |
|---|---|---|---|
| b165cfce48 | |||
| 42d13d41b1 |
171
src/day2.rs
Normal file
171
src/day2.rs
Normal file
@@ -0,0 +1,171 @@
|
||||
use std::{io::BufRead, str::FromStr};
|
||||
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
|
||||
#[derive(Eq, PartialEq, Clone, Copy)]
|
||||
pub enum Shape {
|
||||
Rock,
|
||||
Paper,
|
||||
Scissors,
|
||||
}
|
||||
|
||||
impl FromStr for Shape {
|
||||
type Err = Box<dyn std::error::Error>;
|
||||
fn from_str(value: &str) -> Result<Self, Self::Err> {
|
||||
match value {
|
||||
"A" | "X" => Ok(Self::Rock),
|
||||
"B" | "Y" => Ok(Self::Paper),
|
||||
"C" | "Z" => Ok(Self::Scissors),
|
||||
c => Err(format!("Invalid shape `{c:?}`").into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Shape {
|
||||
fn fight(&self, opponent: &Shape) -> Outcome {
|
||||
match (self, opponent) {
|
||||
(Self::Rock, Self::Scissors) | (Self::Scissors, Self::Paper) | (Self::Paper, Self::Rock) => Outcome::Win,
|
||||
_ if self == opponent => Outcome::Tie,
|
||||
_ => Outcome::Lose,
|
||||
}
|
||||
}
|
||||
fn score(&self, opponent: &Shape) -> u64 {
|
||||
self.points() + self.fight(opponent).points()
|
||||
}
|
||||
fn points(&self) -> u64 {
|
||||
match self {
|
||||
Shape::Rock => 1,
|
||||
Shape::Paper => 2,
|
||||
Shape::Scissors => 3,
|
||||
}
|
||||
}
|
||||
// Return the Shape that will produce the desired outcome against us for the opponent
|
||||
fn fix_round(&self, goal: &Outcome) -> Shape {
|
||||
match goal {
|
||||
Outcome::Tie => *self,
|
||||
Outcome::Win => match self {
|
||||
Shape::Rock => Shape::Paper,
|
||||
Shape::Paper => Shape::Scissors,
|
||||
Shape::Scissors => Shape::Rock,
|
||||
},
|
||||
Outcome::Lose => match self {
|
||||
Shape::Rock => Shape::Scissors,
|
||||
Shape::Paper => Shape::Rock,
|
||||
Shape::Scissors => Shape::Paper,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub enum Outcome {
|
||||
Win,
|
||||
Lose,
|
||||
Tie,
|
||||
}
|
||||
|
||||
impl Outcome {
|
||||
fn points(&self) -> u64 {
|
||||
match self {
|
||||
Self::Win => 6,
|
||||
Self::Tie => 3,
|
||||
Self::Lose => 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for Outcome {
|
||||
type Err = Box<dyn std::error::Error>;
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s {
|
||||
"X" => Ok(Self::Lose),
|
||||
"Y" => Ok(Self::Tie),
|
||||
"Z" => Ok(Self::Win),
|
||||
_ => Err(format!("Invalid outcome : `{s}").into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Move {
|
||||
ours: Shape,
|
||||
theirs: Shape,
|
||||
}
|
||||
|
||||
impl FromStr for Move {
|
||||
type Err = Box<dyn std::error::Error>;
|
||||
fn from_str(value: &str) -> Result<Self, Self::Err> {
|
||||
let (theirs, ours) = value.split_once(&" ").ok_or("Unable to split")?;
|
||||
Ok(Move {
|
||||
ours: ours.parse()?,
|
||||
theirs: theirs.parse()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Move {
|
||||
fn score(&self) -> u64 {
|
||||
self.ours.score(&self.theirs)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MoveGoal {
|
||||
theirs: Shape,
|
||||
goal: Outcome,
|
||||
}
|
||||
|
||||
impl FromStr for MoveGoal {
|
||||
type Err = Box<dyn std::error::Error>;
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let (theirs, goal) = s.split_once(&" ").ok_or("Unable to split")?;
|
||||
Ok(MoveGoal {
|
||||
theirs: theirs.parse()?,
|
||||
goal: goal.parse()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl MoveGoal {
|
||||
fn get_move(&self) -> Move {
|
||||
Move {
|
||||
theirs: self.theirs,
|
||||
ours: self.theirs.fix_round(&self.goal),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[aoc_generator(day2, part1)]
|
||||
fn parse_part1(input: &[u8]) -> Vec<Move> {
|
||||
input.lines().map(|l| l.unwrap().parse().unwrap()).collect()
|
||||
}
|
||||
#[aoc_generator(day2, part2)]
|
||||
fn parse_part2(input: &[u8]) -> Vec<MoveGoal> {
|
||||
input.lines().map(|l| l.unwrap().parse().unwrap()).collect()
|
||||
}
|
||||
|
||||
#[aoc(day2, part1)]
|
||||
fn part1(input: &Vec<Move>) -> u64 {
|
||||
input.iter().map(|m| m.score()).sum()
|
||||
}
|
||||
|
||||
#[aoc(day2, part2)]
|
||||
fn part2(input: &Vec<MoveGoal>) -> u64 {
|
||||
input.iter().map(|mg| mg.get_move().score()).sum()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &[u8] = b"A Y
|
||||
B X
|
||||
C Z";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(&parse_part1(EXAMPLE)), 15);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(&parse_part2(EXAMPLE)), 12);
|
||||
}
|
||||
}
|
||||
113
src/day3.rs
Normal file
113
src/day3.rs
Normal file
@@ -0,0 +1,113 @@
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
use itertools::Itertools;
|
||||
use std::fmt::Display;
|
||||
|
||||
struct Rucksack {
|
||||
items: Vec<u8>,
|
||||
}
|
||||
|
||||
impl From<&[u8]> for Rucksack {
|
||||
fn from(s: &[u8]) -> Self {
|
||||
Self {
|
||||
items: s.iter().cloned().collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Rucksack {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_fmt(format_args!(
|
||||
"{}{}",
|
||||
String::from_utf8_lossy(&self.compartments()[0]),
|
||||
String::from_utf8_lossy(&self.compartments()[1])
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl Rucksack {
|
||||
fn compartments(&self) -> [&[u8]; 2] {
|
||||
let tup = self.items.split_at(self.items.len() / 2);
|
||||
[tup.0, tup.1]
|
||||
}
|
||||
fn common(&self) -> u8 {
|
||||
for item in self.compartments()[0] {
|
||||
if self.compartments()[1].contains(&item) {
|
||||
return *item;
|
||||
}
|
||||
}
|
||||
panic!("Common item not found");
|
||||
}
|
||||
fn contains(&self, item: &u8) -> bool {
|
||||
self.compartments().into_iter().flatten().contains(item)
|
||||
}
|
||||
fn common_with<'a>(&self, other: &[u8]) -> impl Iterator<Item = u8> {
|
||||
self.compartments()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|c| other.contains(c))
|
||||
.cloned()
|
||||
}
|
||||
}
|
||||
|
||||
fn priority(c: u8) -> u8 {
|
||||
if c >= b'A' && c <= b'Z' {
|
||||
c - b'A' + 27
|
||||
} else if c >= b'a' && c <= b'z' {
|
||||
c - b'a' + 1
|
||||
} else {
|
||||
panic!("Invalid item {c}")
|
||||
}
|
||||
}
|
||||
|
||||
#[aoc_generator(day3)]
|
||||
fn parse(input: &[u8]) -> Vec<Rucksack> {
|
||||
input.split(|i| *i == b'\n').map(|x| x.into()).collect()
|
||||
}
|
||||
|
||||
#[aoc(day3, part1)]
|
||||
fn part1(input: &Vec<Rucksack>) -> u64 {
|
||||
input.iter().map(|sack| priority(sack.common()) as u64).sum()
|
||||
}
|
||||
|
||||
#[aoc(day3, part2)]
|
||||
fn part2(input: &Vec<Rucksack>) -> u64 {
|
||||
let mut total = 0u64;
|
||||
for sacks in input.chunks(3) {
|
||||
let commons_1 = sacks[0].common_with(&sacks[1].items).unique().collect_vec();
|
||||
let commons = sacks[2].common_with(&commons_1).unique().collect_vec();
|
||||
|
||||
if commons.len() != 1 {
|
||||
panic!(
|
||||
"Wrong number ({}) of commons for sacks {} {} {}",
|
||||
commons.len(),
|
||||
sacks[0],
|
||||
sacks[1],
|
||||
sacks[2]
|
||||
);
|
||||
}
|
||||
total += priority(commons[0]) as u64
|
||||
}
|
||||
total
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &[u8] = b"vJrwpWtwJgWrhcsFMMfFFhFp
|
||||
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
|
||||
PmmdzqPrVvPwwTWBwg
|
||||
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
|
||||
ttgJtRGJQctTZtZT
|
||||
CrZsJsPPZsGzwwsLwLmpwMDw";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(&parse(EXAMPLE)), 157);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(&parse(EXAMPLE)), 70);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
mod day1;
|
||||
mod day2;
|
||||
mod day3;
|
||||
use aoc_runner_derive::aoc_lib;
|
||||
|
||||
pub mod day6;
|
||||
mod day6;
|
||||
|
||||
aoc_lib! { year = 2022 }
|
||||
|
||||
Reference in New Issue
Block a user