aoc

My solutions for the Advent of Code
git clone https://git.tronto.net/aoc
Download | Log | Files | Refs | README

common.rs (1280B)


      1 #[derive(Debug)]
      2 pub struct Operation {
      3     pub m1: String,
      4     pub m2: String,
      5     pub op: char
      6 }
      7 
      8 #[derive(Debug)]
      9 pub enum MonkeyType {
     10     Num(i64),
     11     Op(Operation)
     12 }
     13 
     14 #[derive(Debug)]
     15 pub struct Monkey {
     16     pub name: String,
     17     pub kind: MonkeyType
     18 }
     19 
     20 pub fn read_monkeys_from_stdin() -> Vec<Monkey> {
     21     let mut v = vec![];
     22     let mut line = String::new();
     23     while std::io::stdin().read_line(&mut line).unwrap() > 0 {
     24         let name = String::from(&line[0..4]);
     25         let monkey = match line.chars().nth(6).unwrap() {
     26             '0'..='9' => {
     27                 let n = line[6..line.len()-1].parse::<i64>().unwrap();
     28                 Monkey { name, kind: MonkeyType::Num(n) }
     29             },
     30             _ => {
     31                 let m1 = String::from(&line[6..10]);
     32                 let m2 = String::from(&line[13..17]);
     33                 let op = Operation { m1, m2, op: line.chars().nth(11).unwrap() };
     34                 Monkey { name, kind: MonkeyType::Op(op) }
     35             }
     36         };
     37         v.push(monkey);
     38         line.clear();
     39     }
     40     v
     41 }
     42 
     43 pub fn apply_op(n1: i64, n2: i64, op: &Operation) -> i64 {
     44     match op.op {
     45         '+' => n1 + n2,
     46         '-' => n1 - n2,
     47         '*' => n1 * n2,
     48         '/' => n1 / n2,
     49         _ => panic!("invalid operator")
     50     }
     51 }