From c3b314c7b55669a5d8f9f18ba85a875529bb7e80 Mon Sep 17 00:00:00 2001 From: Johannes Date: Tue, 3 Dec 2019 20:39:25 +0100 Subject: [PATCH] day03 task 1 very functional --- src/tasks/day03.rs | 60 +++++++++++++++++++++++++++------------------- 1 file changed, 35 insertions(+), 25 deletions(-) diff --git a/src/tasks/day03.rs b/src/tasks/day03.rs index 6b4c5d7..e684dd4 100644 --- a/src/tasks/day03.rs +++ b/src/tasks/day03.rs @@ -33,32 +33,42 @@ fn visited_points(p: &Vec<&str>) -> HashSet<(i32, i32)> { (direction, number) }) .scan((0, 0), |(cx, cy), (direction, number)| { - let sx = *cx; - let sy = *cy; - let mut tx = *cx; - let mut ty = *cy; - let iter: Box> = match direction { - 'U' => { - ty += number; - Box::new((*cy + 1..=ty).map(move |y| (sx, y))) - } - 'D' => { - ty -= number; - Box::new((ty..*cy).map(move |y| (sx, y))) - } - 'R' => { - tx += number; - Box::new((*cx + 1..=tx).map(move |x| (x, sy))) - } - 'L' => { - tx -= number; - Box::new((tx..*cx).map(move |x| (x, sy))) - } - _ => panic!("unknown direction {}", direction), + fn fi(i: i32) -> i32 { + i + 1 + } + fn fd(i: i32) -> i32 { + i - 1 + } + let fstep = match direction { + 'U' | 'R' => fi, + 'D' | 'L' => fd, + _ => panic!("Unexpected input"), }; - *cx = tx; - *cy = ty; - Some(iter) + fn fx(point: (i32, i32), f: fn(i32) -> i32) -> (i32, i32) { + let (x, y) = point; + (f(x), y) + } + fn fy(point: (i32, i32), f: fn(i32) -> i32) -> (i32, i32) { + let (x, y) = point; + (x, f(y)) + } + let faxis = match direction { + 'U' | 'D' => fy, + 'R' | 'L' => fx, + _ => panic!("Unexpected input"), + }; + let steps = (0..number) + .scan((*cx, *cy), |(sx, sy), _| { + let (newx, newy) = faxis((*sx, *sy), fstep); + *sx = newx; + *sy = newy; + Some((newx, newy)) + }) + .collect::>(); + let last = steps.iter().last().unwrap(); + *cx = last.0; + *cy = last.1; + Some(steps) }) .flatten() .collect()