86 lines
2.3 KiB
Rust
86 lines
2.3 KiB
Rust
use categorized_hand::{CategorizedHand, JokerOrdered};
|
|
use crate::solutions::day7::dealt_hand::DealtHand;
|
|
|
|
mod categorized_hand;
|
|
mod dealt_hand;
|
|
mod hand_kind;
|
|
mod parsing;
|
|
mod second_ordering;
|
|
mod hello;
|
|
|
|
pub fn solve_task_1(input: &str) -> String {
|
|
let parsed = parsing::parse_input(input);
|
|
let sorted_and_categorized = {
|
|
let mut categorized: Vec<_> = parsed.into_iter().map(CategorizedHand::from).collect();
|
|
categorized.sort();
|
|
categorized
|
|
};
|
|
let total_winning = calc_total_winning(&sorted_and_categorized);
|
|
total_winning.to_string()
|
|
}
|
|
|
|
pub fn solve_task_2(input: &str) -> String {
|
|
const JOKER: char = 'J';
|
|
let parsed = parsing::parse_input(input);
|
|
let sorted_and_categorized= categorize_and_sort_with_a_joker(parsed, JOKER);
|
|
let total_winning = calc_total_winning(&sorted_and_categorized);
|
|
total_winning.to_string()
|
|
}
|
|
|
|
fn categorize_and_sort_with_a_joker(parsed: Vec<DealtHand>, joker: char) -> Vec<CategorizedHand> {
|
|
let mut categorized: Vec<JokerOrdered> = parsed
|
|
.into_iter()
|
|
.map(|not_categorized| (not_categorized, joker).into())
|
|
.map(JokerOrdered::new)
|
|
.collect();
|
|
categorized.sort();
|
|
|
|
categorized
|
|
.into_iter()
|
|
.map(|to_unwrap| to_unwrap.into())
|
|
.collect()
|
|
}
|
|
|
|
fn calc_total_winning(sorted: &[CategorizedHand]) -> usize {
|
|
sorted
|
|
.into_iter()
|
|
.enumerate()
|
|
.map(|(index, hand)| {
|
|
let rank = index.saturating_add(1);
|
|
let score = hand.bid();
|
|
score.checked_mul(rank).unwrap_or_else(|| {
|
|
panic!(
|
|
"Multiplication of score ({}) with rank ({}) resulted in overflow",
|
|
score, rank
|
|
)
|
|
})
|
|
})
|
|
.sum()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
const TEST_INPUT: &str = "32T3K 765
|
|
T55J5 684
|
|
KK677 28
|
|
KTJJT 220
|
|
QQQJA 483
|
|
";
|
|
|
|
#[cfg(test)]
|
|
mod testing {
|
|
use super::TEST_INPUT;
|
|
|
|
#[test]
|
|
fn solve_example_according_to_task_1() {
|
|
let actual = super::solve_task_1(TEST_INPUT);
|
|
let expected = "6440";
|
|
assert_eq!(expected, actual);
|
|
}
|
|
|
|
#[test]
|
|
fn solve_example_according_to_task_2() {
|
|
let actual = super::solve_task_2(TEST_INPUT);
|
|
let expected = "5905";
|
|
assert_eq!(expected, actual);
|
|
}
|
|
}
|