#[aoc(day1, part1)] pub fn part1(input: &str) -> i32 { let mut dial_counter = DialCounter { position: 50, zero_count: 0, }; for line in input.lines() { dial_counter.rotate(line) } dial_counter.zero_count } #[derive(Debug)] struct DialCounter { position: i32, zero_count: i32, } impl DialCounter { fn rotate(&mut self, operation: &str) { self.position = match operation.chars().nth(0).unwrap() { 'L' => (self.position - operation[1..].parse::().unwrap()) % 100, 'R' => (self.position + operation[1..].parse::().unwrap()) % 100, _ => panic!("Unexpected input!"), }; if self.position == 0 { self.zero_count = self.zero_count + 1; } } fn rotate_2(&mut self, operation: &str) { let direction = operation.chars().nth(0).unwrap(); let magnitude = operation[1..].parse::().unwrap(); match direction { 'L' => { if self.position == 0 { self.position = 100 } self.position = self.position - magnitude; while self.position < 0 { self.position = self.position + 100; self.zero_count = self.zero_count + 1; } if self.position == 0 { self.zero_count = self.zero_count + 1; } } 'R' => { self.position = self.position + magnitude; while self.position > 99 { self.position = self.position - 100; self.zero_count = self.zero_count + 1; } } _ => panic!("Unexpected input!"), }; } } #[aoc(day1, part2)] pub fn part2(input: &str) -> i32 { let mut dial_counter = DialCounter { position: 50, zero_count: 0, }; for line in input.lines() { dial_counter.rotate_2(line) } dial_counter.zero_count } #[cfg(test)] mod tests { use super::*; struct Setup { test_string_1: String, test_string_2: String, } impl Setup { fn new() -> Self { Self { test_string_1: String::from("L68\nL30\nR48\nL5\nR60\nL55\nL1\nL99\nR14\nL82\n"), test_string_2: String::from("R27\nL477\n"), } } } #[test] fn test_part1() { let setup = Setup::new(); assert_eq!(part1(&setup.test_string_1), 3); println!(" "); assert_eq!(part1(&setup.test_string_2), 1); } #[test] fn test_part2() { let setup = Setup::new(); assert_eq!(part2(&setup.test_string_1), 6); println!(" "); assert_eq!(part2(&setup.test_string_2), 5); } }