day 1 done, no winnow

This commit is contained in:
Joe Ardent 2024-12-15 15:55:17 -08:00
commit f5c9c54214
6 changed files with 113 additions and 0 deletions

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
target/
*/input

4
.rustfmt.toml Normal file
View file

@ -0,0 +1,4 @@
imports_granularity = "Crate"
group_imports = "StdExternalCrate"
wrap_comments = true
edition = "2024"

25
Cargo.lock generated Normal file
View file

@ -0,0 +1,25 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "day01"
version = "0.1.0"
dependencies = [
"winnow",
]
[[package]]
name = "memchr"
version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
[[package]]
name = "winnow"
version = "0.6.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "36c1fec1a2bb5866f07c25f68c26e565c4c200aebb96d7e55710c19d3e8ac49b"
dependencies = [
"memchr",
]

6
Cargo.toml Normal file
View file

@ -0,0 +1,6 @@
[workspace]
resolver = "2"
members = ["day01"]
[workspace.dependencies]
winnow = "0.6"

7
day01/Cargo.toml Normal file
View file

@ -0,0 +1,7 @@
[package]
name = "day01"
version = "0.1.0"
edition = "2024"
[dependencies]
winnow.workspace = true

69
day01/src/main.rs Normal file
View file

@ -0,0 +1,69 @@
use std::collections::HashMap;
fn main() {
let input = std::fs::read_to_string("input").unwrap();
println!("{}", pt2(&input));
}
fn pt1(input: &str) -> i32 {
let (mut left, mut right) = parse_input(input);
left.sort_unstable();
right.sort_unstable();
left.iter()
.zip(right.iter())
.map(|(l, r)| (l - r).abs())
.sum()
}
fn pt2(input: &str) -> i32 {
let (left, right) = parse_input(input);
let mut rights = HashMap::new();
for num in &right {
*rights.entry(num).or_insert(0) += 1;
}
left.iter().map(|n| n * rights.get(n).unwrap_or(&0)).sum()
}
fn parse_input(input: &str) -> (Vec<i32>, Vec<i32>) {
let mut left = Vec::new();
let mut right = Vec::new();
for line in input.split("\n") {
let line: Vec<&str> = line
.split(|c: char| c.is_whitespace())
.filter(|c| !c.is_empty())
.collect();
if line.len() < 2 {
continue;
}
let l: i32 = line[0].parse().unwrap();
let r: i32 = line[1].parse().unwrap();
left.push(l);
right.push(r);
}
(left, right)
}
#[cfg(test)]
mod test {
use super::*;
static P1_TEST: &str = "3 4
4 3
2 5
1 3
3 9
3 3
";
#[test]
fn test_p1() {
let val = pt1(P1_TEST);
assert_eq!(11, val);
}
#[test]
fn test_p2() {
let val = pt2(P1_TEST);
assert_eq!(31, val);
}
}