Disgustingly functional

This commit is contained in:
Daniel Flanagan 2022-12-03 00:35:29 -06:00
parent 1b042a164b
commit a9429f5ab6
Signed by: lytedev
GPG key ID: 5B2020A0F9921EF4
2 changed files with 38 additions and 41 deletions

View file

@ -12,7 +12,6 @@ fetch_input.sh 2` to fetch input as soon as it's available and I use `watchexec
-e rs 'C; clear; cargo test --bin day2 && cargo run --bin day2'` to run my -e rs 'C; clear; cargo test --bin day2 && cargo run --bin day2'` to run my
file(s) as I edit them. file(s) as I edit them.
## Running ## Running
First, you will want to fetch your input for the day you want to run. You will First, you will want to fetch your input for the day you want to run. You will
@ -46,4 +45,14 @@ cargo build --release --bin day1
time ./target/release/day1 time ./target/release/day1
``` ```
### Everything
You can use this `fish` script to build all binaries in release mode and run/
time them all:
```fish
cargo build --release --bins
for f in (fd 'day.' target/release/ --type executable --max-depth 1); echo $f; time $f; end
```
[at]: https://git.lyte.dev/lytedev/dotfiles/src/branch/master/common/bin/at [at]: https://git.lyte.dev/lytedev/dotfiles/src/branch/master/common/bin/at

View file

@ -9,50 +9,38 @@ fn main() {
println!("Part 2: {}", part2(&input)); println!("Part 2: {}", part2(&input));
} }
fn priority(b: u8) -> i32 {
(b as i32) - if b >= 97 && b <= 122 { 96 } else { 38 }
}
fn part1(input: &str) -> i32 { fn part1(input: &str) -> i32 {
let mut r = 0_i32; input.lines().map(str::as_bytes).fold(0, |r, b| {
for l in input.lines() { let h = b.len() / 2;
println!("{}", l); r + priority(
let mut s: HashSet<u8> = HashSet::new(); *HashSet::<u8>::from_iter((&b[0..h]).iter().cloned())
let bytes = l.as_bytes(); .intersection(&HashSet::from_iter((&b[h..b.len()]).iter().cloned()))
let mut n = 0; .next()
let bar = bytes.len() / 2; .unwrap(),
println!("{}", bar); )
for b in bytes { })
print!("{}.", b);
if s.contains(b) && n >= bar {
if *b >= 97 && *b <= 122 {
r += (*b as i32) - 96;
} else {
r += (*b as i32) - 65 + 27;
}
println!(" == {}", r);
break;
} else if n < bar {
s.insert(*b);
}
n += 1
}
}
r
} }
fn part2(input: &str) -> i32 { fn part2(input: &str) -> i32 {
let mut r = 0_i32; input
for t in input.lines().collect::<Vec<&str>>().chunks_exact(3) { .lines()
let a: HashSet<u8> = HashSet::from_iter(t[0].bytes()); .collect::<Vec<&str>>()
let b: HashSet<u8> = HashSet::from_iter(t[1].bytes()); .chunks_exact(3)
let c: HashSet<u8> = HashSet::from_iter(t[2].bytes()); .fold(0, |r, t| {
let ab = HashSet::from_iter(a.intersection(&b).cloned()); r + priority(
let b = ab.intersection(&c).next().unwrap(); *t.iter()
if *b >= 97 && *b <= 122 { .map(|l| HashSet::<u8>::from_iter(l.bytes()))
r += (*b as i32) - 96; .reduce(|a, b| HashSet::from_iter(a.intersection(&b).cloned()))
} else { .unwrap()
r += (*b as i32) - 65 + 27; .iter()
} .next()
println!("+{} = {}", b, r); .unwrap(),
} )
r })
} }
#[cfg(test)] #[cfg(test)]