From bf5747e9925988c8cf053f974fdcc35ca76df361 Mon Sep 17 00:00:00 2001 From: Gard Spreemann Date: Sun, 11 Dec 2022 16:14:28 +0100 Subject: Days 8 and 9 --- 09/src/part-2.rs | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 09/src/part-2.rs (limited to '09/src/part-2.rs') diff --git a/09/src/part-2.rs b/09/src/part-2.rs new file mode 100644 index 0000000..1773d2e --- /dev/null +++ b/09/src/part-2.rs @@ -0,0 +1,65 @@ +// Ugh, weird motion in this grid world! + +use std::collections::{HashSet}; +use std::io::{BufRead}; + +const NUM_SEGMENTS: usize = 10; + +type Pos = [isize; 2]; + +fn main() { + let stdin = std::io::stdin(); + let mut handle = stdin.lock(); + + let mut buf: Vec = Vec::new(); + let mut seen: HashSet<[isize; 2]> = HashSet::new(); + let mut positions: [Pos; NUM_SEGMENTS] = [[0; 2]; NUM_SEGMENTS]; + seen.insert(positions[NUM_SEGMENTS-1].clone()); + + loop { + buf.clear(); + let num_bytes = handle.read_until(b'\n', &mut buf).expect("IO error"); + if num_bytes == 0 { break; } + + if buf[buf.len() - 1] == b'\n' { buf.pop(); } + + let direction = buf[0]; + let num_steps: usize = std::str::from_utf8(& buf[2..]).expect("Malformed input") + .parse().expect("Malformed input"); + + for dir in std::iter::repeat(direction).take(num_steps) { + match dir { + b'L' => positions[0][0] -= 1, + b'R' => positions[0][0] += 1, + b'U' => positions[0][1] += 1, + b'D' => positions[0][1] -= 1, + _ => panic!("Malformed input") + }; + + for i in 1..NUM_SEGMENTS { + let delta: [isize; 2] = { + let mut ret: [isize; 2] = [0; 2]; + for d in 0..2 { ret[d] = positions[i-1][d] - positions[i][d]; } + ret + }; + if delta[0].abs() == 2 { + positions[i][0] += delta[0].signum(); + if delta[1].abs() == 1 { + positions[i][1] += delta[1].signum(); + } + } + if delta[1].abs() == 2 { + positions[i][1] += delta[1].signum(); + if delta[0].abs() == 1 { + positions[i][0] += delta[0].signum(); + } + } + } + seen.insert(positions[NUM_SEGMENTS-1].clone()); + } + } + + println!("{}", seen.len()); + + +} -- cgit v1.2.3