From 306408e6c7e7e1fca83793827792502215f11056 Mon Sep 17 00:00:00 2001 From: Pat Thoyts Date: Thu, 7 Dec 2023 12:27:55 +0000 Subject: [PATCH] day6: [rust] completed --- day6/Cargo.toml | 7 +++++ day6/src/main.rs | 81 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 day6/Cargo.toml create mode 100644 day6/src/main.rs diff --git a/day6/Cargo.toml b/day6/Cargo.toml new file mode 100644 index 0000000..06d4c25 --- /dev/null +++ b/day6/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "aoc2023-day6" +version = "1.0.0" + +[dependencies] +clap = { version="4.4.11", features=["derive"] } +rayon = "1.8.0" diff --git a/day6/src/main.rs b/day6/src/main.rs new file mode 100644 index 0000000..e1e2d8d --- /dev/null +++ b/day6/src/main.rs @@ -0,0 +1,81 @@ +extern crate clap; +extern crate rayon; + +use std::error::Error; +use std::fs::File; +use std::io::{prelude::*, BufReader}; + +use rayon::prelude::*; +use clap::{Parser, ArgAction}; + +/// Advent of Code 2023 day 6 +#[derive(Parser, Default, Debug)] +struct Arguments { + /// specify the input file name + filename: String, + #[arg(short, long, action=ArgAction::SetTrue)] + /// enable debug output + debug: Option, +} + +type Parsed = (Vec, Vec); + +fn parse_input(filename: &str) -> Parsed { + let input = File::open(filename).expect("file not found"); + let buffered = BufReader::new(input); + let data: Vec = buffered.lines().collect::>().unwrap(); + ( + data[0].strip_prefix("Time: ") + .unwrap() + .split_whitespace() + .map(|x| x.parse::().unwrap()) + .collect::>(), + data[1].strip_prefix("Distance: ") + .unwrap() + .split_whitespace() + .map(|x| x.parse::().unwrap()) + .collect::>(), + ) +} + +fn part1(input: &Parsed) -> i64 { + input.0.iter().zip(input.1.iter()) + .map(|(&t, &d)| (1..t) + .into_par_iter() + .filter(|&x| x * (t - x) > d) + .count() as i64) + .product() +} + +fn part2(filename: &str) -> i64 { + let handle = File::open(filename).expect("file not found"); + let buffered = BufReader::new(handle); + let data: Vec = buffered.lines().collect::>().unwrap(); + let input = ( + data[0].strip_prefix("Time: ") + .unwrap() + .split_whitespace() + .collect::() + .parse() + .unwrap(), + data[1].strip_prefix("Distance: ") + .unwrap() + .split_whitespace() + .collect::() + .parse() + .unwrap() + ); + part1(&(vec![input.0], vec![input.1])) +} + +fn main() -> Result<(), Box> { + let args = Arguments::parse(); + let input = parse_input(&args.filename); + if args.debug.is_some() { + println!("Time: {:?}, Distance: {:?}", input.0, input.1); + } + println!("part 1: {}", part1(&input)); + println!("part 2: {}", part2(&args.filename)); + + Ok(()) +} -- 2.23.0