day3. Actually had some errors from the borrow checker! Luckily I could
just do what it told me to do, instead of having to actually _understand_ anything about it... for now.
This commit is contained in:
parent
25ce8c21e5
commit
a502096736
5 changed files with 358 additions and 0 deletions
37
day3/src/main.rs
Normal file
37
day3/src/main.rs
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
fn main() {
|
||||
let contents = std::fs::read_to_string("data.txt").expect("Failed to read file");
|
||||
let lines: Vec<&str> = contents.lines().collect();
|
||||
|
||||
// Part 1
|
||||
let sacks: Vec<(&str, &str)> = lines.iter().map(|&x| x.split_at(x.len() / 2)).collect();
|
||||
let common_items_part1: Vec<char> = sacks.iter().map(find_common_item).collect();
|
||||
let priorities_part1: Vec<u32> = common_items_part1.iter().map(char_to_code).collect();
|
||||
let sum_part1: u32 = priorities_part1.iter().sum();
|
||||
println!("Part 1 Sum: {sum_part1}");
|
||||
|
||||
// Part 2
|
||||
let groups: Vec<&[&str]> = lines.chunks(3).collect();
|
||||
let common_items_part2: Vec<char> = groups.iter().map(find_badge).collect();
|
||||
let priorities_part2: Vec<u32> = common_items_part2.iter().map(char_to_code).collect();
|
||||
let sum_part2: u32 = priorities_part2.iter().sum();
|
||||
println!("Part 2 Sum: {sum_part2}");
|
||||
}
|
||||
|
||||
fn char_to_code(c: &char) -> u32 {
|
||||
let offset = if c.is_ascii_uppercase() { 38 } else { 96 };
|
||||
*c as u32 - offset
|
||||
}
|
||||
|
||||
fn find_common_item(pair: &(&str, &str)) -> char {
|
||||
pair.0
|
||||
.chars()
|
||||
.filter(|&x| pair.1.contains(x))
|
||||
.collect::<Vec<char>>()[0]
|
||||
}
|
||||
|
||||
fn find_badge(set: &&[&str]) -> char {
|
||||
set[0]
|
||||
.chars()
|
||||
.filter(|&x| set[1].contains(x) && set[2].contains(x))
|
||||
.collect::<Vec<char>>()[0]
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue