1
0
Fork 0

day(03): refactor parsing

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2022-12-03 14:31:03 +01:00
parent de1b5d9d5e
commit c96bab1a71
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -1,25 +1,53 @@
use std::collections::HashSet;
use std::str::FromStr;
use aoc_2022::*;
use color_eyre::eyre::Result;
use color_eyre::eyre::{Report, Result};
use tracing::*;
use tracing_subscriber::EnvFilter;
type Input = Vec<(HashSet<i32>, HashSet<i32>)>;
struct Backpack(HashSet<i32>, HashSet<i32>);
type Input = Vec<Backpack>;
type Output = i32;
impl FromStr for Backpack {
type Err = Report;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut left: HashSet<i32> = HashSet::new();
let mut right: HashSet<i32> = HashSet::new();
let mid = s.len() / 2;
for (i, c) in s.chars().enumerate() {
let s = if i < mid { &mut left } else { &mut right };
s.insert(
c as i32
+ if c.is_ascii_lowercase() {
1 - 'a' as i32
} else {
27 - 'A' as i32
},
);
}
Ok(Backpack(left, right))
}
}
fn part_1(input: &Input) -> Output {
input
.iter()
.map(|(left, right)| left.intersection(right).sum::<i32>())
.map(|Backpack(left, right)| left.intersection(right).sum::<i32>())
.sum()
}
fn part_2(input: &Input) -> Output {
input
.iter()
.map(|(left, right)| left.union(right).cloned().collect())
.map(|Backpack(left, right)| left.union(right).cloned().collect())
.collect::<Vec<HashSet<i32>>>()
.chunks(3)
.map(|sets| {
@ -36,26 +64,7 @@ fn part_2(input: &Input) -> Output {
}
fn parse_input(pathname: &str) -> Input {
file_to_lines(pathname)
.iter()
.map(|line| {
let mut left: HashSet<i32> = HashSet::new();
let mut right: HashSet<i32> = HashSet::new();
let mid = line.len() / 2;
for (i, c) in line.chars().enumerate() {
let s = if i < mid { &mut left } else { &mut right };
s.insert(if c < 'a' {
c as i32 - 'A' as i32 + 27
} else {
c as i32 - 'a' as i32 + 1
});
}
(left, right)
})
.collect()
file_to_structs(pathname)
}
fn main() -> Result<()> {