diff --git a/2022/rust/readme.md b/2022/rust/readme.md index 882fdbd..d179c88 100644 --- a/2022/rust/readme.md +++ b/2022/rust/readme.md @@ -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 file(s) as I edit them. - ## Running 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 ``` +### 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 diff --git a/2022/rust/src/day3.rs b/2022/rust/src/day3.rs index c922e8e..04f648e 100644 --- a/2022/rust/src/day3.rs +++ b/2022/rust/src/day3.rs @@ -9,50 +9,38 @@ fn main() { 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 { - let mut r = 0_i32; - for l in input.lines() { - println!("{}", l); - let mut s: HashSet = HashSet::new(); - let bytes = l.as_bytes(); - let mut n = 0; - let bar = bytes.len() / 2; - 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 + input.lines().map(str::as_bytes).fold(0, |r, b| { + let h = b.len() / 2; + r + priority( + *HashSet::::from_iter((&b[0..h]).iter().cloned()) + .intersection(&HashSet::from_iter((&b[h..b.len()]).iter().cloned())) + .next() + .unwrap(), + ) + }) } fn part2(input: &str) -> i32 { - let mut r = 0_i32; - for t in input.lines().collect::>().chunks_exact(3) { - let a: HashSet = HashSet::from_iter(t[0].bytes()); - let b: HashSet = HashSet::from_iter(t[1].bytes()); - let c: HashSet = HashSet::from_iter(t[2].bytes()); - let ab = HashSet::from_iter(a.intersection(&b).cloned()); - let b = ab.intersection(&c).next().unwrap(); - if *b >= 97 && *b <= 122 { - r += (*b as i32) - 96; - } else { - r += (*b as i32) - 65 + 27; - } - println!("+{} = {}", b, r); - } - r + input + .lines() + .collect::>() + .chunks_exact(3) + .fold(0, |r, t| { + r + priority( + *t.iter() + .map(|l| HashSet::::from_iter(l.bytes())) + .reduce(|a, b| HashSet::from_iter(a.intersection(&b).cloned())) + .unwrap() + .iter() + .next() + .unwrap(), + ) + }) } #[cfg(test)]