2022 day14/rust: cleanup

This commit is contained in:
Xiretza 2022-12-14 19:22:11 +01:00
parent f41c0177d8
commit 1b59efa250
3 changed files with 27 additions and 30 deletions

View file

@ -7,4 +7,4 @@ edition = "2021"
[dependencies]
aoc = { path = "../../../common/rust" }
nom = "7.1.1"
itertools = "0.10.5"

View file

@ -1,21 +1,20 @@
#![warn(clippy::pedantic)]
use std::{collections::BTreeSet, io::stdin};
use std::{collections::HashSet, io::stdin};
use aoc::vec2::{Line, Vec2};
use nom::{
bytes::complete::tag, character::complete::i32, multi::separated_list1,
sequence::separated_pair, IResult, Parser,
};
use itertools::Itertools;
fn parse_points(s: &str) -> IResult<&str, Vec<Vec2>, ()> {
separated_list1(
tag(" -> "),
separated_pair(i32, tag(","), i32).map(Vec2::from),
)(s)
fn parse_points(s: &str) -> impl Iterator<Item = Vec2> + '_ {
s.split(" -> ").map(|p| {
let (x, y) = p.split_once(',').unwrap();
let x = x.parse().unwrap();
let y = y.parse().unwrap();
(x, y).into()
})
}
fn simulate(structures: BTreeSet<Vec2>, floor: Option<usize>) -> usize {
fn simulate(structures: HashSet<Vec2>, floor: Option<usize>) -> usize {
let mut points = structures;
let lowest = points.iter().map(|v| v.y).max().unwrap();
let start = Vec2::new(500, 0);
@ -24,13 +23,13 @@ fn simulate(structures: BTreeSet<Vec2>, floor: Option<usize>) -> usize {
'pieces: loop {
let mut pos = start;
'fall: loop {
let direction = [(0, 1), (-1, 1), (1, 1)]
let new_pos = [(0, 1), (-1, 1), (1, 1)]
.into_iter()
.map(Vec2::from)
.find(|&direction| !points.contains(&(pos + direction)));
.map(|direction| pos + direction.into())
.find(|pos| !points.contains(pos));
if let Some(direction) = direction {
pos += direction;
if let Some(new_pos) = new_pos {
pos = new_pos;
match floor {
Some(offset) => {
@ -65,18 +64,16 @@ fn simulate(structures: BTreeSet<Vec2>, floor: Option<usize>) -> usize {
}
fn main() {
let lines = stdin().lines().flat_map(|line| {
let points: HashSet<Vec2> = stdin()
.lines()
.flat_map(|line| {
parse_points(&line.unwrap())
.unwrap()
.1
.windows(2)
.map(|x| Line {
start: x[0],
end: x[1],
})
.tuple_windows()
.map(|(start, end)| Line { start, end })
.collect::<Vec<_>>()
});
let points: BTreeSet<Vec2> = lines.flat_map(|line| line.points().unwrap()).collect();
})
.flat_map(|line| line.points().unwrap())
.collect();
println!("{}", simulate(points.clone(), None));
println!("{}", simulate(points, Some(2)));

2
Cargo.lock generated
View file

@ -598,7 +598,7 @@ name = "rust_2022_14"
version = "0.1.0"
dependencies = [
"aoc",
"nom",
"itertools",
]
[[package]]