[rs] Solve 2022_11 part 2

This commit is contained in:
Joscha 2022-12-11 11:20:58 +01:00
parent 7aa2bae399
commit c467daaa62
3 changed files with 32 additions and 17 deletions

View file

@ -1,14 +1,14 @@
use std::mem;
use std::str::Lines;
#[derive(Clone, Copy)]
#[derive(Debug, Clone, Copy)]
enum Operation {
Add,
Mul,
}
impl Operation {
fn eval(self, lhs: u32, rhs: u32) -> u32 {
fn eval(self, lhs: u64, rhs: u64) -> u64 {
match self {
Self::Add => lhs + rhs,
Self::Mul => lhs * rhs,
@ -16,14 +16,15 @@ impl Operation {
}
}
#[derive(Clone)]
struct Monkey {
holds: Vec<u32>,
holds: Vec<u64>,
// Left hand side is always "old"
op: Operation,
rhs: Option<u32>,
rhs: Option<u64>,
div_by: u32,
div_by: u64,
if_true: usize,
if_false: usize,
@ -41,7 +42,7 @@ impl Monkey {
let holds = prefixed(&mut lines, " Starting items: ")
.split(", ")
.map(|i| i.parse::<u32>().unwrap())
.map(|i| i.parse::<u64>().unwrap())
.collect::<Vec<_>>();
let (op, rhs) = prefixed(&mut lines, " Operation: new = old ")
@ -93,12 +94,14 @@ impl Monkey {
}
}
fn round(monkeys: &mut Vec<Monkey>) {
fn round(monkeys: &mut Vec<Monkey>, reduce_worry: bool, modulo: u64) {
for i in 0..monkeys.len() {
monkeys[i].inspections += monkeys[i].holds.len();
let monkey = monkeys[i].take();
for item in monkey.holds {
let item = monkey.op.eval(item, monkey.rhs.unwrap_or(item)) / 3;
let item = monkey.op.eval(item, monkey.rhs.unwrap_or(item));
let item = if reduce_worry { item / 3 } else { item };
let item = item % modulo;
let target = if item % monkey.div_by == 0 {
monkey.if_true
} else {
@ -109,18 +112,30 @@ fn round(monkeys: &mut Vec<Monkey>) {
}
}
fn monkey_business(monkeys: &[Monkey]) -> usize {
let mut inspections = monkeys.iter().map(|m| m.inspections).collect::<Vec<_>>();
inspections.sort_unstable();
inspections.into_iter().rev().take(2).product::<usize>()
}
pub fn solve(input: String) {
let mut monkeys = vec![];
for monkey in input.trim().split("\n\n") {
monkeys.push(Monkey::parse(monkey));
}
for _ in 0..20 {
round(&mut monkeys);
}
let common_multiple = monkeys.iter().map(|m| m.div_by).product::<u64>();
eprintln!("Common multiple: {common_multiple}");
let mut inspections = monkeys.iter().map(|m| m.inspections).collect::<Vec<_>>();
inspections.sort_unstable();
let part1 = inspections.into_iter().rev().take(2).product::<usize>();
println!("Part 1: {part1}");
let mut part1 = monkeys.clone();
for _ in 0..20 {
round(&mut part1, true, common_multiple);
}
println!("Part 1: {}", monkey_business(&part1));
let mut part2 = monkeys.clone();
for _ in 0..10000 {
round(&mut part2, false, common_multiple);
}
println!("Part 2: {}", monkey_business(&part2));
}