From: Greg Burri Date: Sat, 3 Dec 2022 16:05:01 +0000 (+0100) Subject: Day 3 X-Git-Url: https://git.euphorik.ch/?a=commitdiff_plain;h=af5aa543982d4b40a44d91a1005d3f6ffc4d2b65;p=advent_of_code_2022.git Day 3 --- diff --git a/src/day03.rs b/src/day03.rs index fb593c2..a15f11b 100644 --- a/src/day03.rs +++ b/src/day03.rs @@ -1,18 +1,61 @@ -use std::io::BufRead; +use std::io::{BufRead, Lines}; -pub fn read_(reader: R) -> Vec +use itertools::Itertools; + +pub fn priority_sum(reader: R) -> i32 where R: BufRead { - /* - let mut shapes: Vec<(Shape, Shape)> = Vec::new(); + let mut sum = 0; + let mut item_count = [0i32; 52]; for l in reader.lines() { - let s: Vec = l.unwrap().trim().split(' ').map(Shape::parse).collect(); - shapes.push((s[0], s[1])); + item_count.fill(0); + let l = l.unwrap(); + let items = l.as_bytes(); + for i in 0..items.len() / 2 { + let v = letter_to_priority(items[i]); + item_count[v as usize - 1] += 1; + } + for i in items.len() / 2..items.len() { + let v = letter_to_priority(items[i]); + if item_count[v as usize - 1] > 0 { + sum += v as i32; + break; + } + } + } + sum +} + +pub fn badge_sum(reader: R) -> i32 +where + R: BufRead +{ + let mut sum = 0; + let mut item_count = [0i32; 52]; + for group in reader.lines().chunks(3).into_iter() { + item_count.fill(0); + for (i, rucksack) in group.enumerate() { + let items = rucksack.unwrap(); + for b in items.as_bytes().into_iter() { + let v = letter_to_priority(*b); + if i == 2 && item_count[v as usize - 1] == 3 { + sum += v as i32; + break; + } + item_count[v as usize - 1] |= 1 << i; + } + } + } + sum +} + +fn letter_to_priority(v: u8) -> u8 { + if v >= 97 { // >= 'a' + v - 96 + } else { // < 'a' + v - 38 } - shapes - */ - Vec::new() } #[cfg(test)] @@ -21,11 +64,27 @@ mod tests { #[test] fn part1() { - assert_eq!(1, 1); + let rucksacks = + "vJrwpWtwJgWrhcsFMMfFFhFp +jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL +PmmdzqPrVvPwwTWBwg +wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn +ttgJtRGJQctTZtZT +CrZsJsPPZsGzwwsLwLmpwMDw"; + + assert_eq!(priority_sum(rucksacks.as_bytes()), 157); } #[test] fn part2() { - assert_eq!(2, 2); + let rucksacks = + "vJrwpWtwJgWrhcsFMMfFFhFp +jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL +PmmdzqPrVvPwwTWBwg +wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn +ttgJtRGJQctTZtZT +CrZsJsPPZsGzwwsLwLmpwMDw"; + + assert_eq!(badge_sum(rucksacks.as_bytes()), 70); } } \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 6a78796..66d8ef0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -20,7 +20,11 @@ fn day02() -> String { } fn day03() -> String { - format!("part1: {}, part2: {}", 0, 0) + let mut f = fs::File::open("data/day03.input").unwrap(); + let part1 = day03::priority_sum(BufReader::new(f.try_clone().unwrap())); + let _ = f.seek(SeekFrom::Start(0)); + let part2 = day03::badge_sum(BufReader::new(f)); + format!("part1: {}, part2: {}", part1, part2) } fn format_micros(t: u128) -> String {