diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/day9.rs | 56 | ||||
-rw-r--r-- | src/main.rs | 2 |
2 files changed, 58 insertions, 0 deletions
diff --git a/src/day9.rs b/src/day9.rs new file mode 100644 index 0000000..ac21e4d --- /dev/null +++ b/src/day9.rs @@ -0,0 +1,56 @@ +use core::panic; +use std::collections::HashSet; + +type Pt = (i32, i32); +/** + * how should the tail move to catch up with the head? + */ +fn catchup(head: Pt, tail: Pt) -> Pt { + let (hx, hy) = head; + let (tx, ty) = tail; + let xdiff = hx - tx; + let ydiff = hy - ty; + // only move if we're not adjescent (incl diagonally) + if xdiff.abs() > 1 || ydiff.abs() > 1 { + // only move 1 square (x and or y) in the direction of the head + (tail.0 + xdiff.signum(), tail.1 + ydiff.signum()) + } else { + (tail.0, tail.1) + } + +} +pub fn run(input: String) { + // series of steps + // let mut head: Pt = (0,0); + // let mut tail: Pt = (0,0); + // let mut htrail: Vec<Pt> = Vec::new(); + let mut rope: Vec<Pt> = (0..10).map(|_| { (0,0) as Pt}).collect(); + let mut trail: Vec<Pt> = Vec::new(); + for line in input.lines() { + let mut toks = line.split_whitespace(); + let dir: &str = toks.next().expect("expected a direction!"); + let reps: u32 = toks.next().expect("expected a reps!").parse().expect("reps wasn't a number!"); + for _ in 0..reps { + let head = rope[0]; + let newhead = match dir { + "U" => (head.0, head.1+1), + "D" => (head.0, head.1-1), + "L" => (head.0-1, head.1), + "R" => (head.0+1, head.1), + dir => panic!("unexpected direction {}", dir), + }; + rope[0] = newhead; + for l in 1..rope.len() { + rope[l] = catchup(rope[l-1], rope[l]); + } + let tail = rope.last().unwrap(); + // htrail.push(head); + // tail = catchup(head, tail); + trail.push(*tail); + } + } + //println!("htrail {:?}", htrail); + //println!("trail {:?}", trail); + let trailsz = trail.into_iter().collect::<HashSet<Pt>>().len(); + println!("Day 9: {}", trailsz); +}
\ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 5a7634b..e9ea587 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,6 +8,7 @@ mod day5; mod day6; mod day7; mod day8; +mod day9; fn main() { day1::run(fs::read_to_string("input/day1.txt").expect("Failed to read input file!")); @@ -18,4 +19,5 @@ fn main() { day6::run(fs::read_to_string("input/day6.txt").expect("Failed to read input file!")); day7::run(fs::read_to_string("input/day7.txt").expect("Failed to read input file!")); day8::run(fs::read_to_string("input/day8.txt").expect("Failed to read input file!")); + day9::run(fs::read_to_string("input/day9.txt").expect("Failed to read input file!")); } |