use std::fs::File; use std::io::{self, BufRead}; use std::path::Path; use std::iter::Zip; #[derive(Debug)] enum Operand { Add, Multiply, } #[derive(Debug)] struct Test { value: u32, if_true: usize, if_false: usize, } impl Test { fn new(value: u32, if_true: usize, if_false: usize) -> Self { Self { value, if_true, if_false, } } fn compute(&self, item: u32) -> usize { match item % self.value { 0 => self.if_true, _ => self.if_false, } } } #[derive(Debug)] struct Operation { lhs: Option, rhs: Option, operand: Operand, } impl Operation { fn new(lhs: Option, rhs: Option, operand: Operand) -> Self { Self { lhs, rhs, operand, } } fn compute(&self, item: u32) -> u32 { let lhs = self.lhs.unwrap_or(item); let rhs = self.rhs.unwrap_or(item); match self.operand { Operand::Multiply => lhs * rhs, Operand::Add => lhs + rhs, } } } #[derive(Debug)] struct Monkey { items: Vec, operation: Operation, test: Test, business: usize, } impl Monkey { fn new(items: Vec, operation: Operation, test: Test) -> Self { Self { items, operation, test, business: 0, } } fn compute(&mut self) -> Vec { self.business += self.items.len(); self.items = self.items.iter().map(|x| self.operation.compute(*x)).collect(); self.items = self.items.iter().map(|x| x / 3).collect(); self.items.iter().map(|x| self.test.compute(*x)).collect() } } fn main() { let file_path = String::from("input"); let mut monkeys = Vec::::new(); monkeys.push(Monkey::new(vec![72, 97], Operation::new(None, Some(13), Operand::Multiply), Test::new(19, 5, 6))); monkeys.push(Monkey::new(vec![55, 70, 90, 74, 95], Operation::new(None, None, Operand::Multiply), Test::new(7, 5, 0))); monkeys.push(Monkey::new(vec![74, 97, 66, 57], Operation::new(None, Some(6), Operand::Add), Test::new(17, 1, 0))); monkeys.push(Monkey::new(vec![86, 54, 53], Operation::new(None, Some(2), Operand::Add), Test::new(13, 1, 2))); monkeys.push(Monkey::new(vec![50, 65, 78, 50, 62, 99], Operation::new(None, Some(3), Operand::Add), Test::new(11, 3, 7))); monkeys.push(Monkey::new(vec![90], Operation::new(None, Some(4), Operand::Add), Test::new(2, 4, 6))); monkeys.push(Monkey::new(vec![88, 92, 63, 94, 96, 82, 53, 53], Operation::new(None, Some(8), Operand::Add), Test::new(5, 4, 7))); monkeys.push(Monkey::new(vec![70, 60, 71, 69, 77, 70, 98], Operation::new(None, Some(7), Operand::Multiply), Test::new(3, 2, 3))); for _ in 0..20 { for i in 0..8 { let pass_to_i_vec = monkeys[i].compute(); let test: Vec = monkeys[i].items.drain(..).collect(); let my_zip = test.iter().zip(pass_to_i_vec.iter()); for (v, i) in my_zip { monkeys[*i].items.push(*v); } } } println!("{:#?}", monkeys); let mut monkey_business = Vec::::new(); for i in 0..8 { monkey_business.push(monkeys[i].business); } monkey_business.sort(); println!("{}", monkey_business[6] * monkey_business[7]); } fn read_lines

(filename: P) -> io::Result>> where P: AsRef, { let file = File::open(filename)?; Ok(io::BufReader::new(file).lines()) }