1
0
Fork 0

day(11): refactor simulation

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2022-12-11 14:27:03 +01:00
parent d56154f5c2
commit 837a579827
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -119,7 +119,7 @@ impl FromStr for Monkey {
}
}
fn round(monkeys: &mut Input, lcm: usize, div: bool) {
fn round(monkeys: &mut Input, lcm: usize, modular: bool) {
let mut q: VecDeque<(usize, usize)> = VecDeque::new();
for i in 0..monkeys.len() {
@ -127,10 +127,11 @@ fn round(monkeys: &mut Input, lcm: usize, div: bool) {
for j in 0..m.items.len() {
let mut worry = m.operation.apply(m.items[j]);
if div {
if modular {
worry %= lcm;
} else {
worry /= 3;
}
worry %= lcm;
q.push_back((m.test.get(worry), worry));
m.inspections += 1;
@ -156,6 +157,38 @@ fn euclid(a: usize, b: usize) -> usize {
a
}
fn simulate_rounds(input: &Input, rounds: usize, modular: bool) -> Output {
let mut monkeys = input.clone();
let lcm = monkeys
.iter()
.map(|m| m.test.0)
.fold(1, |x, y| (x * y) / euclid(x, y));
let inspect = vec![
1, 20, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 1000,
];
for r in 0..rounds {
round(&mut monkeys, lcm, modular);
if inspect.contains(&(r + 1)) {
debug!(
"Monkeys: {:?}",
monkeys.iter().map(|m| m.inspections).collect_vec()
);
}
}
monkeys
.iter()
.map(|m| m.inspections)
// .inspect(|x| debug!("inspections of monkey: {x}"))
.sorted_by_key(|&i| Reverse(i))
.take(2)
.product()
}
struct Day11;
impl Solution<Input, Output> for Day11 {
fn parse_input<P: AsRef<Path>>(pathname: P) -> Input {
@ -166,55 +199,11 @@ impl Solution<Input, Output> for Day11 {
}
fn part_1(input: &Input) -> Output {
let mut monkeys = input.clone();
let lcm = monkeys
.iter()
.map(|m| m.test.0)
.fold(1, |x, y| x * y / euclid(x, y));
for _ in 0..20 {
round(&mut monkeys, lcm, true);
}
monkeys
.iter()
.map(|m| m.inspections)
.sorted_by_key(|&i| Reverse(i))
.take(2)
.product()
simulate_rounds(input, 20, false)
}
fn part_2(input: &Input) -> Output {
let mut monkeys = input.clone();
let lcm = monkeys
.iter()
.map(|m| m.test.0)
.fold(1, |x, y| (x * y) / euclid(x, y));
let inspect = vec![
1, 20, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 1000,
];
for r in 0..10000 {
round(&mut monkeys, lcm, false);
if inspect.contains(&(r + 1)) {
debug!(
"Monkeys: {:?}",
monkeys.iter().map(|m| m.inspections).collect_vec()
);
}
}
monkeys
.iter()
.map(|m| m.inspections)
// .inspect(|x| debug!("inspections of monkey: {x}"))
.sorted_by_key(|&i| Reverse(i))
.take(2)
.product()
simulate_rounds(input, 10000, true)
}
}