day9.rs (1919B)
1 use core::panic; 2 use std::collections::HashSet; 3 4 type Pt = (i32, i32); 5 /** 6 * how should the tail move to catch up with the head? 7 */ 8 fn catchup(head: Pt, tail: Pt) -> Pt { 9 let (hx, hy) = head; 10 let (tx, ty) = tail; 11 let xdiff = hx - tx; 12 let ydiff = hy - ty; 13 // only move if we're not adjescent (incl diagonally) 14 if xdiff.abs() > 1 || ydiff.abs() > 1 { 15 // only move 1 square (x and or y) in the direction of the head 16 (tail.0 + xdiff.signum(), tail.1 + ydiff.signum()) 17 } else { 18 (tail.0, tail.1) 19 } 20 21 } 22 pub fn run(input: String) { 23 // series of steps 24 // let mut head: Pt = (0,0); 25 // let mut tail: Pt = (0,0); 26 // let mut htrail: Vec<Pt> = Vec::new(); 27 let mut rope: Vec<Pt> = (0..10).map(|_| { (0,0) as Pt}).collect(); 28 let mut trail: Vec<Pt> = Vec::new(); 29 for line in input.lines() { 30 let mut toks = line.split_whitespace(); 31 let dir: &str = toks.next().expect("expected a direction!"); 32 let reps: u32 = toks.next().expect("expected a reps!").parse().expect("reps wasn't a number!"); 33 for _ in 0..reps { 34 let head = rope[0]; 35 let newhead = match dir { 36 "U" => (head.0, head.1+1), 37 "D" => (head.0, head.1-1), 38 "L" => (head.0-1, head.1), 39 "R" => (head.0+1, head.1), 40 dir => panic!("unexpected direction {}", dir), 41 }; 42 rope[0] = newhead; 43 for l in 1..rope.len() { 44 rope[l] = catchup(rope[l-1], rope[l]); 45 } 46 let tail = rope.last().unwrap(); 47 // htrail.push(head); 48 // tail = catchup(head, tail); 49 trail.push(*tail); 50 } 51 } 52 //println!("htrail {:?}", htrail); 53 //println!("trail {:?}", trail); 54 let trailsz = trail.into_iter().collect::<HashSet<Pt>>().len(); 55 println!("Day 9: {}", trailsz); 56 }