main.rs (1418B)
1 enum Command { 2 Up(i32), 3 Down(i32), 4 Forward(i32), 5 } 6 7 fn parse_command(s: &str) -> Option<Command> { 8 let mut it = s.split(' '); 9 let dir = it.next().unwrap(); 10 let dist = it.next().unwrap().parse::<i32>().unwrap(); 11 match dir { 12 "up" => Some(Command::Up(dist)), 13 "down" => Some(Command::Down(dist)), 14 "forward" => Some(Command::Forward(dist)), 15 _ => None, 16 } 17 } 18 19 fn main() { 20 let input = std::fs::read_to_string("input.txt") 21 .unwrap() 22 .trim() 23 .split('\n') 24 .map(|cmd| parse_command(cmd).unwrap()) 25 .collect::<Vec<Command>>(); 26 // 1714950 27 println!("Part 1: {}", part_1(&input)); 28 // 1281977850 29 println!("Part 2: {}", part_2(&input)); 30 } 31 32 fn part_1(input: &Vec<Command>) -> i32 { 33 let mut depth = 0; 34 let mut pos = 0; 35 36 for cmd in input { 37 match cmd { 38 Command::Up(x) => depth -= x, 39 Command::Down(x) => depth += x, 40 Command::Forward(x) => pos += x, 41 } 42 } 43 44 depth * pos 45 } 46 47 fn part_2(input: &Vec<Command>) -> i32 { 48 let mut depth = 0; 49 let mut pos = 0; 50 let mut aim = 0; 51 52 for cmd in input { 53 match cmd { 54 Command::Up(x) => aim -= x, 55 Command::Down(x) => aim += x, 56 Command::Forward(x) => { 57 pos += x; 58 depth += aim * x; 59 } 60 } 61 } 62 63 depth * pos 64 }