AoC/2022/days/03/rucksack/src/rucksack.rs

46 lines
1.2 KiB
Rust
Executable File

/// lowercase `a` to `z` have priorities 1 to 26, uppercase `A` through `Z` have priority 27 through 52.
fn priority(item: char) -> u32 {
let value: u32;
if item.is_lowercase() {
value = item as u32 - 96;
} else {
value = item as u32 - 64 + 26;
}
value
}
pub fn sum_priorities_items_both_compartiments(sacks: &str) -> u32 {
let mut sum: u32 = 0;
for sack in sacks.lines() {
let middle_index: usize = sack.len() / 2;
let first_compartiment: &str = &sack[..middle_index];
let second_compartiment: &str = &sack[middle_index..];
for item in first_compartiment.chars() {
if second_compartiment.contains(item) {
sum += priority(item);
break;
}
}
}
sum
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_priority() {
assert_eq!(priority('a'), 1);
assert_eq!(priority('z'), 26);
assert_eq!(priority('A'), 27);
assert_eq!(priority('Z'), 52);
}
#[test]
fn test_sum_priorities_items_both_compartiments() {
assert_eq!(sum_priorities_items_both_compartiments("aAa"), 1);
assert_eq!(sum_priorities_items_both_compartiments("AbilABC"), 27);
}
}