mirror of
https://github.com/bertptrs/adventofcode.git
synced 2025-12-25 21:00:31 +01:00
Modify points in-place
Thanks to skius from libera##rust for the idea
This commit is contained in:
@@ -54,27 +54,19 @@ fn read_input(input: &mut dyn Read) -> (Vec<Coords>, Vec<Fold>) {
|
|||||||
parse_input(&input_buffer).finish().unwrap().1
|
parse_input(&input_buffer).finish().unwrap().1
|
||||||
}
|
}
|
||||||
|
|
||||||
fn apply_fold(dots: &mut Vec<Coords>, fold: Fold, to_fold: &mut Vec<Coords>) {
|
fn apply_fold(dots: &mut Vec<Coords>, fold: Fold) {
|
||||||
match fold {
|
match fold {
|
||||||
Fold::X(coord) => dots.retain(|&(x, y)| {
|
Fold::X(coord) => dots.iter_mut().for_each(|(x, _)| {
|
||||||
if x < coord {
|
if *x >= coord {
|
||||||
true
|
*x = 2 * coord - *x;
|
||||||
} else {
|
|
||||||
to_fold.push((2 * coord - x, y));
|
|
||||||
false
|
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
Fold::Y(coord) => dots.retain(|&(x, y)| {
|
Fold::Y(coord) => dots.iter_mut().for_each(|(_, y)| {
|
||||||
if y < coord {
|
if *y >= coord {
|
||||||
true
|
*y = 2 * coord - *y;
|
||||||
} else {
|
|
||||||
to_fold.push((x, 2 * coord - y));
|
|
||||||
false
|
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
|
|
||||||
dots.append(to_fold);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn print_dots(dots: &[Coords]) -> String {
|
fn print_dots(dots: &[Coords]) -> String {
|
||||||
@@ -98,7 +90,7 @@ fn print_dots(dots: &[Coords]) -> String {
|
|||||||
pub fn part1(input: &mut dyn Read) -> String {
|
pub fn part1(input: &mut dyn Read) -> String {
|
||||||
let (mut dots, folds) = read_input(input);
|
let (mut dots, folds) = read_input(input);
|
||||||
|
|
||||||
apply_fold(&mut dots, folds[0], &mut Vec::new());
|
apply_fold(&mut dots, folds[0]);
|
||||||
|
|
||||||
dots.sort_unstable();
|
dots.sort_unstable();
|
||||||
|
|
||||||
@@ -108,11 +100,9 @@ pub fn part1(input: &mut dyn Read) -> String {
|
|||||||
pub fn part2(input: &mut dyn Read) -> String {
|
pub fn part2(input: &mut dyn Read) -> String {
|
||||||
let (mut dots, folds) = read_input(input);
|
let (mut dots, folds) = read_input(input);
|
||||||
|
|
||||||
let mut to_fold = Vec::new();
|
|
||||||
|
|
||||||
folds
|
folds
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.for_each(|fold| apply_fold(&mut dots, fold, &mut to_fold));
|
.for_each(|fold| apply_fold(&mut dots, fold));
|
||||||
|
|
||||||
print_dots(&dots)
|
print_dots(&dots)
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user