|
| 1 | +use std::str::FromStr; |
| 2 | + |
| 3 | +pub fn part1(contents: &str) -> i64 { |
| 4 | + let mut current: i64 = 50; |
| 5 | + let mut count = 0; |
| 6 | + for (dir, dist) in contents.lines().map(|line| parse_line(line)) { |
| 7 | + match dir { |
| 8 | + 'L' => current = (current - dist).rem_euclid(100), |
| 9 | + 'R' => current = (current + dist).rem_euclid(100), |
| 10 | + _ => panic!("Invalid direction"), |
| 11 | + } |
| 12 | + |
| 13 | + if current == 0 { |
| 14 | + count += 1; |
| 15 | + } |
| 16 | + } |
| 17 | + count |
| 18 | +} |
| 19 | + |
| 20 | +pub fn part2(contents: &str) -> i64 { |
| 21 | + let mut current = 50; |
| 22 | + let mut count = 0; |
| 23 | + for (dir, dist) in contents.lines().map(|line| parse_line(line)) { |
| 24 | + match dir { |
| 25 | + 'L' => { |
| 26 | + count += (current - dist).div_euclid(100).abs(); |
| 27 | + if current == 0 && dist > 0 { |
| 28 | + // Moving left again will wrap around and count as another zero |
| 29 | + // crossing. Remove one here to avoid double-counting. |
| 30 | + count -= 1; |
| 31 | + } |
| 32 | + |
| 33 | + current = (current - dist).rem_euclid(100); |
| 34 | + if current == 0 { |
| 35 | + // The division doesn't count landing on zero as a crossing, |
| 36 | + // so we need to increment the count here. |
| 37 | + count += 1; |
| 38 | + } |
| 39 | + } |
| 40 | + 'R' => { |
| 41 | + count += (current + dist).div_euclid(100); |
| 42 | + current = (current + dist).rem_euclid(100); |
| 43 | + } |
| 44 | + _ => panic!("Invalid direction"), |
| 45 | + } |
| 46 | + } |
| 47 | + count |
| 48 | +} |
| 49 | + |
| 50 | +fn parse_line(line: &str) -> (char, i64) { |
| 51 | + let (dir, dist) = line.split_at(1); |
| 52 | + (dir.chars().next().unwrap(), i64::from_str(dist).unwrap()) |
| 53 | +} |
| 54 | + |
| 55 | +#[cfg(test)] |
| 56 | +mod tests { |
| 57 | + use std::vec; |
| 58 | + |
| 59 | + use super::*; |
| 60 | + |
| 61 | + #[test] |
| 62 | + fn test_part1() { |
| 63 | + let lines = vec![ |
| 64 | + "L68", "L30", "R48", "L5", "R60", "L55", "L1", "L99", "R14", "L82", |
| 65 | + ]; |
| 66 | + |
| 67 | + assert_eq!(part1(&lines.join("\n")), 3); |
| 68 | + } |
| 69 | + |
| 70 | + #[test] |
| 71 | + fn test_part2() { |
| 72 | + let lines = vec![ |
| 73 | + "L68", "L30", "R48", "L5", "R60", "L55", "L1", "L99", "R14", "L82", |
| 74 | + ]; |
| 75 | + |
| 76 | + assert_eq!(part2(&lines.join("\n")), 6); |
| 77 | + } |
| 78 | +} |
0 commit comments