Day 1, 2 and 3
This commit is contained in:
47
day3/src/main.rs
Normal file
47
day3/src/main.rs
Normal file
@ -0,0 +1,47 @@
|
||||
use std::{collections::HashSet, fs::read_to_string};
|
||||
|
||||
use color_eyre::{eyre::*, Result};
|
||||
use itertools::Itertools;
|
||||
|
||||
fn priority(item: &char) -> usize {
|
||||
('a'..='z')
|
||||
.position(|c| *item == c)
|
||||
.map(|i| i + 1)
|
||||
.or_else(|| ('A'..='Z').position(|c| *item == c).map(|i| i + 27))
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
fn initial(input: &str) -> (usize, usize) {
|
||||
let output1 = input
|
||||
.lines()
|
||||
.map(|line| {
|
||||
let (compartment1, compartment2) = line.split_at(line.len() / 2);
|
||||
let compartment1 = compartment1.chars().collect::<HashSet<_>>();
|
||||
let compartment2 = compartment2.chars().collect::<HashSet<_>>();
|
||||
compartment1
|
||||
.intersection(&compartment2)
|
||||
.map(priority)
|
||||
.sum::<usize>()
|
||||
})
|
||||
.sum();
|
||||
let output2 = input
|
||||
.lines()
|
||||
.chunks(3)
|
||||
.into_iter()
|
||||
.map(|group| {
|
||||
group
|
||||
.map(|line| line.chars().collect::<HashSet<_>>())
|
||||
.coalesce(|a, b| Ok(a.intersection(&b).copied().collect()))
|
||||
.map(|set| set.iter().map(priority).sum::<usize>())
|
||||
.sum::<usize>()
|
||||
})
|
||||
.sum();
|
||||
(output1, output2)
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let input = read_to_string("input.txt").wrap_err("reading input.txt")?;
|
||||
let output = initial(&input);
|
||||
println!("output: {output:?}");
|
||||
Ok(())
|
||||
}
|
Reference in New Issue
Block a user