main.rs (2548B)
1 use std::collections::HashMap; 2 3 #[derive(Debug, Copy, Clone)] 4 enum SeaCucumber { 5 East, 6 South, 7 } 8 9 fn main() { 10 let input = std::fs::read_to_string("input.txt") 11 .unwrap() 12 .trim() 13 .split('\n') 14 .map(|s| { 15 s.chars() 16 .map(|c| match c { 17 '.' => None, 18 '>' => Some(SeaCucumber::East), 19 'v' => Some(SeaCucumber::South), 20 _ => unreachable!(), 21 }) 22 .collect::<Vec<_>>() 23 }) 24 .collect::<Vec<Vec<_>>>(); 25 println!("Part 1: {}", part_1(&input)); 26 } 27 28 fn part_1(input: &Vec<Vec<Option<SeaCucumber>>>) -> usize { 29 let mut map = HashMap::new(); 30 let x_max = input[0].len(); 31 let y_max = input.len(); 32 for y in 0..y_max { 33 for x in 0..x_max { 34 if let Some(sc) = input[y][x] { 35 map.insert((x, y), sc); 36 } 37 } 38 } 39 let mut step = 0; 40 loop { 41 let mut updated = false; 42 let mut next_map = HashMap::new(); 43 // move the east facing herd 44 for (&(x, y), sc) in map.iter() { 45 match sc { 46 SeaCucumber::East => { 47 let x_next = (x + 1) % x_max; 48 if x_next != x && !map.contains_key(&(x_next, y)) { 49 updated = true; 50 next_map.insert((x_next, y), SeaCucumber::East); 51 } else { 52 next_map.insert((x, y), SeaCucumber::East); 53 } 54 } 55 SeaCucumber::South => { 56 next_map.insert((x, y), SeaCucumber::South); 57 } 58 } 59 } 60 map = next_map; 61 next_map = HashMap::new(); 62 // move the south facing herd 63 for (&(x, y), sc) in map.iter() { 64 match sc { 65 SeaCucumber::East => { 66 next_map.insert((x, y), SeaCucumber::East); 67 } 68 SeaCucumber::South => { 69 let y_next = (y + 1) % y_max; 70 if y_next != y && !map.contains_key(&(x, y_next)) { 71 updated = true; 72 next_map.insert((x, y_next), SeaCucumber::South); 73 } else { 74 next_map.insert((x, y), SeaCucumber::South); 75 } 76 } 77 } 78 } 79 map = next_map; 80 step += 1; 81 if !updated { 82 return step; 83 } 84 } 85 }