|
| 1 | +advent_of_code::solution!(1); |
| 2 | + |
| 3 | +pub fn part_one(input: &str) -> Option<u64> { |
| 4 | + let mut position: i64 = 50; |
| 5 | + let mut result: u64 = 0; |
| 6 | + for turn in input.lines() { |
| 7 | + let (direction, distance) = parse_rotation(turn)?; |
| 8 | + |
| 9 | + position = apply_rotation(position, direction, distance); |
| 10 | + |
| 11 | + if position == 0 { |
| 12 | + result += 1; |
| 13 | + } |
| 14 | + } |
| 15 | + |
| 16 | + Some(result) |
| 17 | +} |
| 18 | + |
| 19 | +pub fn part_two(input: &str) -> Option<u64> { |
| 20 | + let mut position: i64 = 50; |
| 21 | + let mut result: u64 = 0; |
| 22 | + |
| 23 | + for turn in input.lines() { |
| 24 | + let (direction, distance) = parse_rotation(turn)?; |
| 25 | + |
| 26 | + // Count complete loops (each loop crosses 0 once) |
| 27 | + let complete_loops = distance / 100; |
| 28 | + result += complete_loops as u64; |
| 29 | + |
| 30 | + // Check if the partial rotation crosses 0 |
| 31 | + let remaining = distance % 100; |
| 32 | + let crosses_zero = match direction { |
| 33 | + 'R' => position + remaining >= 100, |
| 34 | + 'L' => position - remaining <= 0 && position > 0, |
| 35 | + _ => false, |
| 36 | + }; |
| 37 | + |
| 38 | + if crosses_zero { |
| 39 | + result += 1; |
| 40 | + } |
| 41 | + |
| 42 | + // Update position for next iteration |
| 43 | + position = apply_rotation(position, direction, distance); |
| 44 | + } |
| 45 | + |
| 46 | + Some(result) |
| 47 | +} |
| 48 | + |
| 49 | +fn apply_rotation(position: i64, direction: char, distance: i64) -> i64 { |
| 50 | + match direction { |
| 51 | + 'R' => (position + distance).rem_euclid(100), |
| 52 | + 'L' => (position - distance).rem_euclid(100), |
| 53 | + _ => position, |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +fn parse_rotation(line: &str) -> Option<(char, i64)> { |
| 58 | + let direction = line.chars().next()?; |
| 59 | + let distance: i64 = line[1..].parse().ok()?; |
| 60 | + Some((direction, distance)) |
| 61 | +} |
| 62 | + |
| 63 | +#[cfg(test)] |
| 64 | +mod tests { |
| 65 | + use super::*; |
| 66 | + |
| 67 | + #[test] |
| 68 | + fn test_part_one() { |
| 69 | + let result = part_one(&advent_of_code::template::read_file("examples", DAY)); |
| 70 | + assert_eq!(result, Some(3)); |
| 71 | + } |
| 72 | + |
| 73 | + #[test] |
| 74 | + fn test_part_two() { |
| 75 | + let result = part_two(&advent_of_code::template::read_file("examples", DAY)); |
| 76 | + assert_eq!(result, Some(6)); |
| 77 | + } |
| 78 | +} |
0 commit comments