diff --git a/2022/day14/rust/Cargo.toml b/2022/day14/rust/Cargo.toml index a05c5af..86897fd 100644 --- a/2022/day14/rust/Cargo.toml +++ b/2022/day14/rust/Cargo.toml @@ -7,4 +7,4 @@ edition = "2021" [dependencies] aoc = { path = "../../../common/rust" } -nom = "7.1.1" +itertools = "0.10.5" diff --git a/2022/day14/rust/src/main.rs b/2022/day14/rust/src/main.rs index c674d18..dd39689 100644 --- a/2022/day14/rust/src/main.rs +++ b/2022/day14/rust/src/main.rs @@ -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, ()> { - separated_list1( - tag(" -> "), - separated_pair(i32, tag(","), i32).map(Vec2::from), - )(s) +fn parse_points(s: &str) -> impl Iterator + '_ { + 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, floor: Option) -> usize { +fn simulate(structures: HashSet, floor: Option) -> 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, floor: Option) -> 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, floor: Option) -> usize { } fn main() { - let lines = stdin().lines().flat_map(|line| { - parse_points(&line.unwrap()) - .unwrap() - .1 - .windows(2) - .map(|x| Line { - start: x[0], - end: x[1], - }) - .collect::>() - }); - let points: BTreeSet = lines.flat_map(|line| line.points().unwrap()).collect(); + let points: HashSet = stdin() + .lines() + .flat_map(|line| { + parse_points(&line.unwrap()) + .tuple_windows() + .map(|(start, end)| Line { start, end }) + .collect::>() + }) + .flat_map(|line| line.points().unwrap()) + .collect(); println!("{}", simulate(points.clone(), None)); println!("{}", simulate(points, Some(2))); diff --git a/Cargo.lock b/Cargo.lock index cd7d67c..606b8a9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -598,7 +598,7 @@ name = "rust_2022_14" version = "0.1.0" dependencies = [ "aoc", - "nom", + "itertools", ] [[package]]