day03 task 1 very functional

This commit is contained in:
Johannes
2019-12-03 20:39:25 +01:00
parent e4fc27ffa9
commit c3b314c7b5

View File

@@ -33,32 +33,42 @@ fn visited_points(p: &Vec<&str>) -> HashSet<(i32, i32)> {
(direction, number) (direction, number)
}) })
.scan((0, 0), |(cx, cy), (direction, number)| { .scan((0, 0), |(cx, cy), (direction, number)| {
let sx = *cx; fn fi(i: i32) -> i32 {
let sy = *cy; i + 1
let mut tx = *cx;
let mut ty = *cy;
let iter: Box<dyn Iterator<Item = (i32, i32)>> = match direction {
'U' => {
ty += number;
Box::new((*cy + 1..=ty).map(move |y| (sx, y)))
} }
'D' => { fn fd(i: i32) -> i32 {
ty -= number; i - 1
Box::new((ty..*cy).map(move |y| (sx, y)))
} }
'R' => { let fstep = match direction {
tx += number; 'U' | 'R' => fi,
Box::new((*cx + 1..=tx).map(move |x| (x, sy))) 'D' | 'L' => fd,
} _ => panic!("Unexpected input"),
'L' => {
tx -= number;
Box::new((tx..*cx).map(move |x| (x, sy)))
}
_ => panic!("unknown direction {}", direction),
}; };
*cx = tx; fn fx(point: (i32, i32), f: fn(i32) -> i32) -> (i32, i32) {
*cy = ty; let (x, y) = point;
Some(iter) (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::<Vec<(i32, i32)>>();
let last = steps.iter().last().unwrap();
*cx = last.0;
*cy = last.1;
Some(steps)
}) })
.flatten() .flatten()
.collect() .collect()