Created
December 3, 2022 17:42
-
-
Save shaleh/20a8f2b9efc5d1ad4fcc955cbd493b66 to your computer and use it in GitHub Desktop.
advent of code 2022 day 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::collections::HashSet; | |
use std::io::{self, BufRead}; | |
use itertools::Itertools; | |
fn read_input() -> Vec<Vec<char>> { | |
let stdin = io::stdin(); | |
let handle = stdin.lock(); | |
handle | |
.lines() | |
.map(|x| x.unwrap().trim().chars().collect()) | |
.collect() | |
} | |
fn into_priority(item: char) -> u32 { | |
if ('A'..='Z').contains(&item) { | |
item as u32 - 'A' as u32 + 27 | |
} else { | |
item as u32 - 'a' as u32 + 1 | |
} | |
} | |
fn find_item(items: &Vec<char>) -> u32 { | |
let size = items.len(); | |
let left: HashSet<char> = items[0..size / 2].iter().copied().collect(); | |
let right: HashSet<char> = items[size / 2..].iter().copied().collect(); | |
let mut intersection = left.intersection(&right); | |
into_priority(*(intersection.next().unwrap())) | |
} | |
fn part_one(rucksacks: &[Vec<char>]) -> u32 { | |
rucksacks.iter().map(find_item).sum() | |
} | |
fn find_badge<'a>(triplet: impl Iterator<Item = &'a Vec<char>>) -> u32 { | |
let tmp: Vec<HashSet<char>> = triplet | |
.map(|items| items.iter().copied().collect()) | |
.collect(); | |
let all_items: HashSet<char> = tmp[0].intersection(&tmp[1]).copied().collect(); | |
let mut all_items = all_items.intersection(&tmp[2]).copied(); | |
let badge = all_items.next().unwrap(); | |
into_priority(badge) | |
} | |
fn part_two(rucksacks: &[Vec<char>]) -> u32 { | |
rucksacks.iter().chunks(3).into_iter().map(find_badge).sum() | |
} | |
fn main() { | |
let input = read_input(); | |
println!("Part one: {}", part_one(&input)); | |
println!("Part two: {}", part_two(&input)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment