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)
})
.scan((0, 0), |(cx, cy), (direction, number)| {
let sx = *cx;
let sy = *cy;
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)))
fn fi(i: i32) -> i32 {
i + 1
}
'D' => {
ty -= number;
Box::new((ty..*cy).map(move |y| (sx, y)))
fn fd(i: i32) -> i32 {
i - 1
}
'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),
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::<Vec<(i32, i32)>>();
let last = steps.iter().last().unwrap();
*cx = last.0;
*cy = last.1;
Some(steps)
})
.flatten()
.collect()