This commit is contained in:
Maxime Augier 2023-12-12 15:33:05 +01:00
parent 99b5bda691
commit 6489efa279
6 changed files with 90 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
target

16
day6/Cargo.lock generated Normal file
View File

@ -0,0 +1,16 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "anyhow"
version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
[[package]]
name = "day6"
version = "0.1.0"
dependencies = [
"anyhow",
]

9
day6/Cargo.toml Normal file
View File

@ -0,0 +1,9 @@
[package]
name = "day6"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
anyhow = "1.0.75"

2
day6/input Normal file
View File

@ -0,0 +1,2 @@
Time: 56 97 77 93
Distance: 499 2210 1097 1440

60
day6/src/main.rs Normal file
View File

@ -0,0 +1,60 @@
use std::io::{stdin, BufRead};
use anyhow::{anyhow, Result};
fn collect_list(prefix: &str, buf: &str) -> Result<Vec<usize>> {
Ok(buf.strip_prefix(prefix)
.ok_or(anyhow!("Incorrect line: {buf:?}"))?
.split_whitespace()
.map(|v| v.parse::<usize>())
.collect::<Result<_,_>>()?)
}
fn aggregate(nums: &[usize]) -> usize {
nums.iter().fold(0, |acc, d| { acc * (10u64.pow(d.ilog10() + 1) as usize) + d } )
}
fn ways((t,d) : (usize, usize)) -> usize {
if t*t < 4*d { return 0; }
let dq = t*t - 4*d;
let delta = (dq as f64).sqrt();
let b1 = ((t as f64 - delta)/2f64).floor() as usize + 1;
let b2 = ((t as f64 + delta)/2f64).ceil() as usize - 1;
if b2 < b1 { return 0; }
eprintln!("t={t} d={d} b1={b1} b2={b2}");
b2 - b1 + 1
}
fn main() -> Result<()> {
let mut stdin = stdin().lock();
let mut buf = String::with_capacity(1024);
stdin.read_line(&mut buf)?;
let times = collect_list("Time:", &buf)?;
buf.clear();
stdin.read_line(&mut buf)?;
let distances = collect_list("Distance:", &buf)?;
buf.clear();
let ways1: usize = times.iter().copied()
.zip(distances.iter().copied())
.map(ways)
.product();
println!("Part 1: {ways1} ways.");
let time2 = aggregate(&times);
let dist2 = aggregate(&distances);
let ways2 = ways((time2, dist2));
println!("Part 2: {ways2} ways.");
Ok(())
}

2
day6/test Normal file
View File

@ -0,0 +1,2 @@
Time: 7 15 30
Distance: 9 40 200