4 Commits

7 changed files with 289 additions and 23 deletions

View File

@@ -11,6 +11,7 @@ anyhow = "1.0.66"
clap = { version = "4.0.19", features = ["derive"] } clap = { version = "4.0.19", features = ["derive"] }
itertools = "0.10.5" itertools = "0.10.5"
nom = "7.1.1" nom = "7.1.1"
strength_reduce = "0.2.4"
[dev-dependencies] [dev-dependencies]
criterion = "0.4.0" criterion = "0.4.0"

55
2022/inputs/11.txt Normal file
View File

@@ -0,0 +1,55 @@
Monkey 0:
Starting items: 84, 66, 62, 69, 88, 91, 91
Operation: new = old * 11
Test: divisible by 2
If true: throw to monkey 4
If false: throw to monkey 7
Monkey 1:
Starting items: 98, 50, 76, 99
Operation: new = old * old
Test: divisible by 7
If true: throw to monkey 3
If false: throw to monkey 6
Monkey 2:
Starting items: 72, 56, 94
Operation: new = old + 1
Test: divisible by 13
If true: throw to monkey 4
If false: throw to monkey 0
Monkey 3:
Starting items: 55, 88, 90, 77, 60, 67
Operation: new = old + 2
Test: divisible by 3
If true: throw to monkey 6
If false: throw to monkey 5
Monkey 4:
Starting items: 69, 72, 63, 60, 72, 52, 63, 78
Operation: new = old * 13
Test: divisible by 19
If true: throw to monkey 1
If false: throw to monkey 7
Monkey 5:
Starting items: 89, 73
Operation: new = old + 5
Test: divisible by 17
If true: throw to monkey 2
If false: throw to monkey 0
Monkey 6:
Starting items: 78, 68, 98, 88, 66
Operation: new = old + 6
Test: divisible by 11
If true: throw to monkey 2
If false: throw to monkey 5
Monkey 7:
Starting items: 70
Operation: new = old + 7
Test: divisible by 5
If true: throw to monkey 1
If false: throw to monkey 3

View File

@@ -1,5 +1,7 @@
//! Common helper utilities to all days //! Common helper utilities to all days
use std::cmp::Ordering;
use anyhow::Result; use anyhow::Result;
use nom::combinator::map; use nom::combinator::map;
use nom::error::ErrorKind; use nom::error::ErrorKind;
@@ -116,3 +118,18 @@ where
(b, a) (b, a)
} }
} }
/// Some magic to get two mutable references into the same slice
pub fn get_both<T>(slice: &mut [T], first: usize, second: usize) -> (&mut T, &mut T) {
match first.cmp(&second) {
Ordering::Greater => {
let (begin, end) = slice.split_at_mut(first);
(&mut end[0], &mut begin[second])
}
Ordering::Less => {
let (begin, end) = slice.split_at_mut(second);
(&mut begin[first], &mut end[0])
}
Ordering::Equal => panic!("Tried to get the same index twice {first}"),
}
}

View File

@@ -1,5 +1,3 @@
use std::cmp::Ordering;
use anyhow::Result; use anyhow::Result;
use nom::branch::alt; use nom::branch::alt;
use nom::bytes::complete::tag; use nom::bytes::complete::tag;
@@ -8,6 +6,7 @@ use nom::bytes::complete::take_until;
use nom::character::complete::newline; use nom::character::complete::newline;
use nom::combinator::map; use nom::combinator::map;
use nom::combinator::opt; use nom::combinator::opt;
use nom::combinator::value;
use nom::multi::fold_many1; use nom::multi::fold_many1;
use nom::multi::many1; use nom::multi::many1;
use nom::sequence::delimited; use nom::sequence::delimited;
@@ -17,6 +16,7 @@ use nom::sequence::tuple;
use nom::IResult; use nom::IResult;
use crate::common::enumerate; use crate::common::enumerate;
use crate::common::get_both;
use crate::common::parse_input; use crate::common::parse_input;
type Move = (usize, usize, usize); type Move = (usize, usize, usize);
@@ -32,7 +32,7 @@ fn parse_row<'a>(input: &'a [u8], stacks: &mut OwnedStacks) -> IResult<&'a [u8],
Some(v[0]) Some(v[0])
}), }),
// Or an empty stack into a None // Or an empty stack into a None
map(tag(" "), |_| None), value(None, tag(" ")),
)), )),
opt(tag(" ")), opt(tag(" ")),
)), )),
@@ -91,21 +91,6 @@ fn parse_task(input: &[u8]) -> IResult<&[u8], (OwnedStacks, Vec<Move>)> {
Ok((input, (stacks, moves))) Ok((input, (stacks, moves)))
} }
/// Some magic to get two mutable references into the same slice
fn get_both(stacks: &mut [Vec<u8>], from: usize, to: usize) -> (&mut Vec<u8>, &mut Vec<u8>) {
match from.cmp(&to) {
Ordering::Greater => {
let (begin, end) = stacks.split_at_mut(from);
(&mut end[0], &mut begin[to])
}
Ordering::Less => {
let (begin, end) = stacks.split_at_mut(to);
(&mut begin[from], &mut end[0])
}
Ordering::Equal => panic!("Tried to stack from and to {from}"),
}
}
fn compute_answer(stacks: &mut [Vec<u8>]) -> Result<String> { fn compute_answer(stacks: &mut [Vec<u8>]) -> Result<String> {
let mut result = String::with_capacity(stacks.len()); let mut result = String::with_capacity(stacks.len());

View File

@@ -4,6 +4,7 @@ use nom::bytes::complete::tag;
use nom::character::complete::newline; use nom::character::complete::newline;
use nom::combinator::iterator; use nom::combinator::iterator;
use nom::combinator::map; use nom::combinator::map;
use nom::combinator::value;
use nom::sequence::preceded; use nom::sequence::preceded;
use nom::sequence::terminated; use nom::sequence::terminated;
use nom::IResult; use nom::IResult;
@@ -36,7 +37,7 @@ impl Instruction {
fn parse_instruction(input: &[u8]) -> IResult<&[u8], Instruction> { fn parse_instruction(input: &[u8]) -> IResult<&[u8], Instruction> {
terminated( terminated(
alt(( alt((
map(tag("noop"), |_| Instruction::Noop), value(Instruction::Noop, tag("noop")),
map(preceded(tag("addx "), nom::character::complete::i32), |v| { map(preceded(tag("addx "), nom::character::complete::i32), |v| {
Instruction::AddX(v) Instruction::AddX(v)
}), }),

View File

@@ -1,9 +1,189 @@
use anyhow::Result; use anyhow::Result;
use nom::branch::alt;
use nom::bytes::complete::tag;
use nom::bytes::complete::take;
use nom::character::complete::digit1;
use nom::character::complete::newline;
use nom::combinator::map;
use nom::combinator::map_res;
use nom::combinator::value;
use nom::multi::separated_list0;
use nom::multi::separated_list1;
use nom::sequence::delimited;
use nom::sequence::preceded;
use nom::sequence::separated_pair;
use nom::sequence::tuple;
use nom::IResult;
use strength_reduce::StrengthReducedU64;
pub fn part1(_input: &[u8]) -> Result<String> { use crate::common::parse_input;
anyhow::bail!("not implemented")
#[derive(Debug, Copy, Clone)]
enum Operation {
Mul(u64),
Add(u64),
Square,
} }
pub fn part2(_input: &[u8]) -> Result<String> { impl Operation {
anyhow::bail!("not implemented") fn transform(self, worry: u64) -> u64 {
match self {
Operation::Mul(val) => worry * val,
Operation::Add(val) => worry + val,
Operation::Square => worry * worry,
}
}
}
#[derive(Debug)]
struct Monkey {
items: Vec<u64>,
operation: Operation,
test_mod: StrengthReducedU64,
targets: [usize; 2],
inspected: usize,
}
impl Monkey {
fn handle_items(&mut self, drains: &mut [Vec<u64>; 2]) {
self.inspected += self.items.len();
for item in self.items.drain(..) {
let mut new_val = self.operation.transform(item);
// Miraculously get less worried
new_val /= 3;
drains[(new_val % self.test_mod == 0) as usize].push(new_val);
}
}
fn handle_items2(&mut self, drains: &mut [Vec<u64>], mod_base: StrengthReducedU64) {
self.inspected += self.items.len();
for item in self.items.drain(..) {
let mut new_val = self.operation.transform(item);
// Modular arithmetic is a good way to get less worried
new_val = new_val % mod_base;
drains[(new_val % self.test_mod == 0) as usize].push(new_val);
}
}
}
fn parse_operation(input: &[u8]) -> IResult<&[u8], Operation> {
preceded(
tag("new = old "),
alt((
map_res(
separated_pair(take(1usize), tag(" "), nom::character::complete::u64),
|(op, val): (&[u8], u64)| match op[0] {
b'*' => Ok(Operation::Mul(val)),
b'+' => Ok(Operation::Add(val)),
_ => Err(anyhow::anyhow!("Invalid operation {op:?}")),
},
),
value(Operation::Square, tag("* old")),
)),
)(input)
}
fn parse_monkey(input: &[u8]) -> IResult<&[u8], Monkey> {
use nom::character::complete::u64;
map(
preceded(
// Skip the useless header line
tuple((tag("Monkey "), digit1, tag(":\n"))),
// Parse the actual interesting bits of the monkey
tuple((
// Parse the starting items
delimited(
tag(" Starting items: "),
separated_list1(tag(", "), u64),
newline,
),
// Parse operation
delimited(tag(" Operation: "), parse_operation, newline),
// Parse the test
delimited(tag(" Test: divisible by "), u64, newline),
// Parse both cases
delimited(tag(" If true: throw to monkey "), u64, newline),
delimited(tag(" If false: throw to monkey "), u64, newline),
)),
),
|(items, operation, test_mod, if_true, if_false)| Monkey {
items,
operation,
test_mod: StrengthReducedU64::new(test_mod),
targets: [if_false as usize, if_true as usize],
inspected: 0,
},
)(input)
}
fn parse_monkeys(input: &[u8]) -> IResult<&[u8], Vec<Monkey>> {
separated_list0(newline, parse_monkey)(input)
}
fn format_result(mut monkeys: Vec<Monkey>) -> Result<String> {
monkeys.sort_by(|a, b| b.inspected.cmp(&a.inspected));
let result: usize = monkeys[0].inspected * monkeys[1].inspected;
Ok(result.to_string())
}
pub fn part1(input: &[u8]) -> Result<String> {
let mut monkeys = parse_input(input, parse_monkeys)?;
let mut drains = [Vec::new(), Vec::new()];
for _ in 0..20 {
for i in 0..monkeys.len() {
monkeys[i].handle_items(&mut drains);
for (j, drain) in drains.iter_mut().enumerate() {
let target = monkeys[i].targets[j];
monkeys[target].items.append(drain);
}
}
}
format_result(monkeys)
}
pub fn part2(input: &[u8]) -> Result<String> {
let mut monkeys = parse_input(input, parse_monkeys)?;
let mut drains = [Vec::new(), Vec::new()];
let mod_base = StrengthReducedU64::new(monkeys.iter().map(|m| m.test_mod.get()).product());
for _ in 0..10000 {
for i in 0..monkeys.len() {
monkeys[i].handle_items2(&mut drains, mod_base);
for (j, drain) in drains.iter_mut().enumerate() {
let target = monkeys[i].targets[j];
monkeys[target].items.append(drain);
}
}
}
format_result(monkeys)
}
#[cfg(test)]
mod tests {
use super::*;
const SAMPLE: &[u8] = include_bytes!("samples/11.txt");
#[test]
fn sample_part1() {
assert_eq!(part1(SAMPLE).unwrap(), "10605");
}
#[test]
fn sample_part2() {
assert_eq!(part2(SAMPLE).unwrap(), "2713310158");
}
} }

27
2022/src/samples/11.txt Normal file
View File

@@ -0,0 +1,27 @@
Monkey 0:
Starting items: 79, 98
Operation: new = old * 19
Test: divisible by 23
If true: throw to monkey 2
If false: throw to monkey 3
Monkey 1:
Starting items: 54, 65, 75, 74
Operation: new = old + 6
Test: divisible by 19
If true: throw to monkey 2
If false: throw to monkey 0
Monkey 2:
Starting items: 79, 60, 97
Operation: new = old * old
Test: divisible by 13
If true: throw to monkey 1
If false: throw to monkey 3
Monkey 3:
Starting items: 74
Operation: new = old + 3
Test: divisible by 17
If true: throw to monkey 0
If false: throw to monkey 1