Finished day 11 aoc in rust

This commit is contained in:
2022-12-20 00:12:21 +01:00
parent 85ece60bbf
commit 662baa4fc4

View File

@@ -12,7 +12,7 @@ use nom::{
#[derive(Debug)]
enum Value {
Old,
Val(u32),
Val(u64),
} use Value::*;
#[derive(Debug)]
@@ -23,21 +23,21 @@ enum Operation {
#[derive(Debug)]
pub struct Test {
divisible_by: u32,
divisible_by: u64,
on_false: usize,
on_true: usize,
}
#[derive(Debug)]
pub struct Monkey {
items: VecDeque<u32>,
items: VecDeque<u64>,
operation: Operation,
test: Test,
number_of_inspections: u32,
number_of_inspections: u64,
}
impl Monkey {
pub fn handle_items(&mut self) -> Vec<(u32, usize)> {
pub fn handle_items(&mut self, magic_number: u64) -> Vec<(u64, usize)> {
let mut result = Vec::new();
while !self.items.is_empty() {
@@ -51,7 +51,8 @@ impl Monkey {
Add(Val(num)) => {item + num},
};
item /= 3;
// item /= 3;
item = item % magic_number;
let throw_to_monkey = match item % self.test.divisible_by == 0 {
true => self.test.on_true,
@@ -74,7 +75,7 @@ fn parse_operation(input: &str) -> IResult<&str, Operation> {
let (input, num) : (&str, Value) = preceded(
multispace1,
alt((
complete::u32.map(|num| Value::Val(num)),
complete::u64.map(|num| Value::Val(num)),
tag("old").map(|_| Value::Old),
)),
)(input)?;
@@ -91,7 +92,7 @@ fn parse_operation(input: &str) -> IResult<&str, Operation> {
fn parse_test(input: &str) -> IResult<&str, Test> {
let (input, divisible_by) = preceded(
tag("Test: divisible by "),
complete::u32,
complete::u64,
)(input)?;
let (input, _) = multispace1(input)?;
@@ -132,7 +133,7 @@ fn parse_input(input: &str) -> IResult<&str, Monkey> {
// Parse: Starting items: num1, num2
let (input, levels) = preceded(
tag("Starting items: "),
separated_list1(tag(", "), complete::u32),
separated_list1(tag(", "), complete::u64),
)(input)?;
let (input, _) = multispace1(input)?;
@@ -163,14 +164,19 @@ fn parse_input(input: &str) -> IResult<&str, Monkey> {
Ok((input, m))
}
fn part1() {
fn part1and2() {
let input_text = include_str!("../input.txt");
let (_, mut monkeys) = many1(parse_input)(input_text).unwrap();
for _i in 0..20 {
let magic_number = monkeys
.iter()
.map(|m| m.test.divisible_by)
.product();
for _i in 0..10000 {
for monkey_index in 0..monkeys.len() {
let monkey = monkeys.get_mut(monkey_index).unwrap();
let new_item_list = monkey.handle_items();
let new_item_list = monkey.handle_items(magic_number);
for (item, thrown_to_monkey) in new_item_list {
monkeys[thrown_to_monkey].items.push_back(item);
@@ -181,13 +187,13 @@ fn part1() {
let mut results = monkeys
.iter()
.map(|m| m.number_of_inspections)
.collect::<Vec<u32>>();
.collect::<Vec<u64>>();
results.sort_by(|a, b| b.cmp(a));
println!("{}", results[0] * results[1]);
println!("{} * {} = {}", results[0], results[1], results[0] * results[1]);
}
fn main() {
part1();
part1and2();
}