day 3
This commit is contained in:
7
src/bin/day03_1.rs
Normal file
7
src/bin/day03_1.rs
Normal file
@@ -0,0 +1,7 @@
|
||||
use aoc2022::day03::process_part_1;
|
||||
use std::fs;
|
||||
|
||||
fn main() {
|
||||
let file = fs::read_to_string("./inputs/day3.txt").unwrap();
|
||||
println!("{}", process_part_1(&file));
|
||||
}
|
||||
7
src/bin/day03_2.rs
Normal file
7
src/bin/day03_2.rs
Normal file
@@ -0,0 +1,7 @@
|
||||
use aoc2022::day03::process_part_2;
|
||||
use std::fs;
|
||||
|
||||
fn main() {
|
||||
let file = fs::read_to_string("./inputs/day3.txt").unwrap();
|
||||
println!("{}", process_part_2(&file));
|
||||
}
|
||||
68
src/day03.rs
Normal file
68
src/day03.rs
Normal file
@@ -0,0 +1,68 @@
|
||||
use itertools::Itertools;
|
||||
|
||||
pub fn process_part_1(input: &str) -> u32 {
|
||||
input
|
||||
.lines()
|
||||
.map(|line| {
|
||||
let compartments = line.split_at(line.len() / 2);
|
||||
let overlap = compartments
|
||||
.0
|
||||
.chars()
|
||||
.find(|ch| compartments.1.contains(*ch))
|
||||
.expect("There should be one overlapping item");
|
||||
|
||||
match overlap {
|
||||
'a'..='z' => 1 + overlap as u32 - 'a' as u32,
|
||||
'A'..='Z' => 27 + overlap as u32 - 'A' as u32,
|
||||
_ => panic!("Invalid overlapping item"),
|
||||
}
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
pub fn process_part_2(input: &str) -> u32 {
|
||||
let result = input
|
||||
.lines()
|
||||
.chunks(3)
|
||||
.into_iter()
|
||||
.map(|chunk| {
|
||||
let lines: Vec<_> = chunk
|
||||
.map(|l| l.chars().unique().collect::<Vec<_>>())
|
||||
.collect();
|
||||
|
||||
let overlap = *lines[0]
|
||||
.iter()
|
||||
.find(|c| lines[1].contains(*c) && lines[2].contains(*c))
|
||||
.unwrap();
|
||||
|
||||
match overlap {
|
||||
'a'..='z' => 1 + overlap as u32 - 'a' as u32,
|
||||
'A'..='Z' => 27 + overlap as u32 - 'A' as u32,
|
||||
_ => panic!("Invalid overlapping item"),
|
||||
}
|
||||
})
|
||||
.sum();
|
||||
return result;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const INPUT: &str = "vJrwpWtwJgWrhcsFMMfFFhFp
|
||||
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
|
||||
PmmdzqPrVvPwwTWBwg
|
||||
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
|
||||
ttgJtRGJQctTZtZT
|
||||
CrZsJsPPZsGzwwsLwLmpwMDw";
|
||||
|
||||
#[test]
|
||||
fn day1() {
|
||||
assert_eq!(process_part_1(INPUT), 157);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn day2() {
|
||||
assert_eq!(process_part_2(INPUT), 70);
|
||||
}
|
||||
}
|
||||
@@ -1,2 +1,5 @@
|
||||
extern crate core;
|
||||
|
||||
pub mod day01;
|
||||
pub mod day02;
|
||||
pub mod day03;
|
||||
|
||||
Reference in New Issue
Block a user