Day 3, Part 1
This commit is contained in:
parent
00944b19b6
commit
1f605618e8
3 changed files with 366 additions and 0 deletions
60
2022/aoc2022/src/day3.rs
Normal file
60
2022/aoc2022/src/day3.rs
Normal file
|
@ -0,0 +1,60 @@
|
|||
use std::collections::HashSet;
|
||||
use std::collections::hash_set::{Intersection, IntoIter};
|
||||
use std::io::Result;
|
||||
use std::iter::Sum;
|
||||
|
||||
use crate::file::line_reader_for_file;
|
||||
|
||||
pub fn main(filename: &str) -> Result<()> {
|
||||
let line_reader = line_reader_for_file(filename)?;
|
||||
|
||||
let mut priority_letters: Vec<char> = Vec::new();
|
||||
|
||||
for line in line_reader {
|
||||
let line = line?;
|
||||
assert!(line.len() % 2 == 0);
|
||||
|
||||
let compartment_size: usize = line.len() / 2;
|
||||
|
||||
let (left_compartment, right_compartment) = line.split_at(compartment_size);
|
||||
let left_compartment_set: HashSet<char> = HashSet::from_iter(left_compartment.chars());
|
||||
let right_compartment_set: HashSet<char> = HashSet::from_iter(right_compartment.chars());
|
||||
|
||||
let intersection = left_compartment_set.intersection(&right_compartment_set);
|
||||
priority_letters.extend(intersection);
|
||||
}
|
||||
|
||||
println!("{}", priority_letters
|
||||
.iter()
|
||||
.map(|c| String::from(*c))
|
||||
.collect::<Vec<String>>()
|
||||
.join(" "));
|
||||
|
||||
const LOWERCASE_A_SCORE: u32 = 'a' as u32;
|
||||
const UPPERCASE_A_SCORE: u32 = 'A' as u32;
|
||||
|
||||
let scored_priority_letters: Vec<u32> =
|
||||
priority_letters
|
||||
.iter()
|
||||
.map(|c| -> u32 {
|
||||
let char_value: u32 = (*c).into();
|
||||
if c.is_lowercase() {
|
||||
char_value - LOWERCASE_A_SCORE + 1
|
||||
} else {
|
||||
char_value - UPPERCASE_A_SCORE + 27
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
println!("{}", scored_priority_letters
|
||||
.iter()
|
||||
.map(|i| i.to_string())
|
||||
.collect::<Vec<String>>()
|
||||
.join(" "));
|
||||
|
||||
let sum_of_scored_priority_letters: u32 = scored_priority_letters
|
||||
.iter().sum();
|
||||
println!("Part 1: sum of scores of all priority items: {}", sum_of_scored_priority_letters);
|
||||
|
||||
Ok(())
|
||||
}
|
|
@ -2,6 +2,7 @@ use std::env;
|
|||
|
||||
mod day1;
|
||||
mod day2;
|
||||
mod day3;
|
||||
mod file;
|
||||
|
||||
fn main() {
|
||||
|
@ -18,4 +19,9 @@ fn main() {
|
|||
let day2_datafile = &args[2];
|
||||
day2::main(day2_datafile.as_str())
|
||||
.expect("Unable to process day2 data file");
|
||||
|
||||
println!("----- Day 3 -----");
|
||||
let day3_datafile = &args[3];
|
||||
day3::main(day3_datafile.as_str())
|
||||
.expect("Unable to process day3 data file");
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue