add day 11, part 2

This commit is contained in:
Christian Ulrich 2022-12-12 02:31:36 +01:00
parent d0c057572a
commit 2b7b34eb1f
No known key found for this signature in database
GPG Key ID: 8241BE099775A097
2 changed files with 40 additions and 1 deletions

View File

@ -34,6 +34,7 @@ pub struct Monkey {
pub struct Game { pub struct Game {
monkeys: Vec<Monkey>, monkeys: Vec<Monkey>,
modulus_lcm: u64,
divisor: u64, divisor: u64,
} }
@ -158,8 +159,10 @@ impl Game {
while let Some(monkey) = Monkey::from_stdin()? { while let Some(monkey) = Monkey::from_stdin()? {
monkeys.push(monkey); monkeys.push(monkey);
} }
let modulus_lcm = monkeys.iter().map(|m| m.modulus).product();
Ok(Self { Ok(Self {
monkeys: monkeys, monkeys: monkeys,
modulus_lcm: modulus_lcm,
divisor: divisor, divisor: divisor,
}) })
} }
@ -178,7 +181,7 @@ impl Iterator for Game {
match self.monkeys[i].throw_item(self.divisor) { match self.monkeys[i].throw_item(self.divisor) {
Ok(None) => break, Ok(None) => break,
Ok(Some((item, target))) => { Ok(Some((item, target))) => {
self.monkeys[target].add_item(item); self.monkeys[target].add_item(item % self.modulus_lcm);
} }
Err(e) => return Some(Err(e)), Err(e) => return Some(Err(e)),
} }

36
day11/part2.rs Normal file
View File

@ -0,0 +1,36 @@
// Copyright 2022 Christian Ulrich
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// usage: ./part1 < input
pub mod common;
use common::{Game, Monkey};
fn main() -> Result<(), &'static str> {
let game = Game::from_stdin(1)?;
let last_round = game.take(10000).last().unwrap();
let mut item_counts: Vec<_> = last_round?
.monkeys()
.iter()
.map(Monkey::item_count)
.collect();
item_counts.sort();
println!(
"{}",
item_counts[item_counts.len() - 1] * item_counts[item_counts.len() - 2]
);
Ok(())
}