summaryrefslogtreecommitdiff
path: root/09/src/part-2.rs
diff options
context:
space:
mode:
Diffstat (limited to '09/src/part-2.rs')
-rw-r--r--09/src/part-2.rs65
1 files changed, 65 insertions, 0 deletions
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<u8> = 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());
+
+
+}