mirror of
https://github.com/theoludwig/advent_of_code_2023.git
synced 2024-10-29 22:17:19 +01:00
feat: add day 7 - part 1
This commit is contained in:
parent
471d49c27e
commit
21433caf63
13
Cargo.lock
generated
13
Cargo.lock
generated
@ -2,6 +2,12 @@
|
||||
# It is not intended for manual editing.
|
||||
version = 3
|
||||
|
||||
[[package]]
|
||||
name = "array-init"
|
||||
version = "2.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3d62b7694a562cdf5a74227903507c56ab2cc8bdd1f781ed5cb4cf9c9f810bfc"
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.1.0"
|
||||
@ -91,6 +97,13 @@ dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "day_7"
|
||||
version = "1.0.0"
|
||||
dependencies = [
|
||||
"array-init",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.9.0"
|
||||
|
@ -1,9 +1,8 @@
|
||||
[workspace]
|
||||
members = [
|
||||
"day_*",
|
||||
]
|
||||
members = ["day_*"]
|
||||
resolver = "2"
|
||||
|
||||
[workspace.dependencies]
|
||||
rayon = { version = "=1.8.0" }
|
||||
indicatif = { version = "=0.17.7", features = ["rayon"] }
|
||||
array-init = { version = "=2.1.0" }
|
||||
|
@ -5,7 +5,7 @@
|
||||
This repository contains my solutions for the [Advent of Code 2023](https://adventofcode.com/2023) challenges implemented in the [Rust Programming Language](https://www.rust-lang.org/) v1.74.0.
|
||||
|
||||
```sh
|
||||
# Run the tests (input examples)
|
||||
# Run the tests
|
||||
cargo test
|
||||
|
||||
# Run a specific day's challenge (e.g. Day 1)
|
||||
|
1
day_7/.gitignore
vendored
Normal file
1
day_7/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
/target
|
7
day_7/Cargo.toml
Normal file
7
day_7/Cargo.toml
Normal file
@ -0,0 +1,7 @@
|
||||
[package]
|
||||
name = "day_7"
|
||||
version = "1.0.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
array-init = { workspace = true }
|
87
day_7/README.md
Normal file
87
day_7/README.md
Normal file
@ -0,0 +1,87 @@
|
||||
# - Day 7: Camel Cards -
|
||||
|
||||
Source: <https://adventofcode.com/2023/day/7>
|
||||
|
||||
## Instructions - Part 1
|
||||
|
||||
Your all-expenses-paid trip turns out to be a one-way, five-minute ride in an [airship](https://en.wikipedia.org/wiki/Airship). (At least it's a **cool** airship!) It drops you off at the edge of a vast desert and descends back to Island Island.
|
||||
|
||||
"Did you bring the parts?"
|
||||
|
||||
You turn around to see an Elf completely covered in white clothing, wearing goggles, and riding a large [camel](https://en.wikipedia.org/wiki/Dromedary).
|
||||
|
||||
"Did you bring the parts?" she asks again, louder this time. You aren't sure what parts she's looking for; you're here to figure out why the sand stopped.
|
||||
|
||||
"The parts! For the sand, yes! Come with me; I will show you." She beckons you onto the camel.
|
||||
|
||||
After riding a bit across the sands of Desert Island, you can see what look like very large rocks covering half of the horizon. The Elf explains that the rocks are all along the part of Desert Island that is directly above Island Island, making it hard to even get there. Normally, they use big machines to move the rocks and filter the sand, but the machines have broken down because Desert Island recently stopped receiving the **parts** they need to fix the machines.
|
||||
|
||||
You've already assumed it'll be your job to figure out why the parts stopped when she asks if you can help. You agree automatically.
|
||||
|
||||
Because the journey will take a few days, she offers to teach you the game of **Camel Cards**. Camel Cards is sort of similar to [poker](https://en.wikipedia.org/wiki/List_of_poker_hands) except it's designed to be easier to play while riding a camel.
|
||||
|
||||
In Camel Cards, you get a list of **hands**, and your goal is to order them based on the **strength** of each hand. A hand consists of **five cards** labeled one of `A`, `K`, `Q`, `J`, `T`, `9`, `8`, `7`, `6`, `5`, `4`, `3`, or `2`. The relative strength of each card follows this order, where `A` is the highest and `2` is the lowest.
|
||||
|
||||
Every hand is exactly one **type**. From strongest to weakest, they are:
|
||||
|
||||
- **Five of a kind**, where all five cards have the same label: `AAAAA`
|
||||
- **Four of a kind**, where four cards have the same label and one card has a different label: `AA8AA`
|
||||
- **Full house**, where three cards have the same label, and the remaining two cards share a different label: `23332`
|
||||
- **Three of a kind**, where three cards have the same label, and the remaining two cards are each different from any other card in the hand: `TTT98`
|
||||
- **Two pair**, where two cards share one label, two other cards share a second label, and the remaining card has a third label: `23432`
|
||||
- **One pair**, where two cards share one label, and the other three cards have a different label from the pair and each other: `A23A4`
|
||||
- **High card**, where all cards' labels are distinct: `23456`
|
||||
|
||||
Hands are primarily ordered based on type; for example, every **full house** is stronger than any **three of a kind**.
|
||||
|
||||
If two hands have the same type, a second ordering rule takes effect. Start by comparing the **first card in each hand**. If these cards are different, the hand with the stronger first card is considered stronger. If the first card in each hand have the **same label**, however, then move on to considering the **second card in each hand**. If they differ, the hand with the higher second card wins; otherwise, continue with the third card in each hand, then the fourth, then the fifth.
|
||||
|
||||
So, `33332` and `2AAAA` are both **four of a kind** hands, but `33332` is stronger because its first card is stronger. Similarly, `77888` and `77788` are both a **full house**, but `77888` is stronger because its third card is stronger (and both hands have the same first and second card).
|
||||
|
||||
To play Camel Cards, you are given a list of hands and their corresponding **bid** (your puzzle input). For example:
|
||||
|
||||
```txt
|
||||
32T3K 765
|
||||
T55J5 684
|
||||
KK677 28
|
||||
KTJJT 220
|
||||
QQQJA 483
|
||||
```
|
||||
|
||||
This example shows five hands; each hand is followed by its **bid** amount. Each hand wins an amount equal to its bid multiplied by its **rank**, where the weakest hand gets rank 1, the second-weakest hand gets rank 2, and so on up to the strongest hand. Because there are five hands in this example, the strongest hand will have rank 5 and its bid will be multiplied by 5.
|
||||
|
||||
So, the first step is to put the hands in order of strength:
|
||||
|
||||
- `32T3K` is the only **one pair** and the other hands are all a stronger type, so it gets rank **`1`**.
|
||||
- `KK677` and `KTJJT` are both **two pair**. Their first cards both have the same label, but the second card of `KK677` is stronger (`K` vs `T`), so `KTJJT` gets rank **`2`** and `KK677` gets rank **`3`**.
|
||||
- `T55J5` and `QQQJA` are both **three of a kind**. `QQQJA` has a stronger first card, so it gets rank **`5`** and `T55J5` gets rank **`4`**.
|
||||
|
||||
Now, you can determine the total winnings of this set of hands by adding up the result of multiplying each hand's bid with its rank (`765` \* 1 + `220` \* 2 + `28` \* 3 + `684` \* 4 + `483` \* 5). So the **total winnings** in this example are **`6440`**.
|
||||
|
||||
Find the rank of every hand in your set. **What are the total winnings?**
|
||||
|
||||
## Instructions - Part 2
|
||||
|
||||
To make things a little more interesting, the Elf introduces one additional rule. Now, `J` cards are [jokers](https://en.wikipedia.org/wiki/Joker_(playing_card)) - wildcards that can act like whatever card would make the hand the strongest type possible.
|
||||
|
||||
To balance this, **`J` cards are now the weakest** individual cards, weaker even than `2`. The other cards stay in the same order: `A`, `K`, `Q`, `T`, `9`, `8`, `7`, `6`, `5`, `4`, `3`, `2`, `J`.
|
||||
|
||||
`J` cards can pretend to be whatever card is best for the purpose of determining hand type; for example, `QJJQ2` is now considered **four of a kind**. However, for the purpose of breaking ties between two hands of the same type, `J` is always treated as `J`, not the card it's pretending to be: `JKKK2` is weaker than `QQQQ2` because `J` is weaker than `Q`.
|
||||
|
||||
Now, the above example goes very differently:
|
||||
|
||||
```txt
|
||||
32T3K 765
|
||||
T55J5 684
|
||||
KK677 28
|
||||
KTJJT 220
|
||||
QQQJA 483
|
||||
```
|
||||
|
||||
- `2T3K` is still the only **one pair**; it doesn't contain any jokers, so its strength doesn't increase.
|
||||
- `KK677` is now the only **two pair**, making it the second-weakest hand.
|
||||
- `T55J5`, `KTJJT`, and `QQQJA` are now all **four of a kind**! `T55J5` gets rank 3, `QQQJA` gets rank 4, and `KTJJT` gets rank 5.
|
||||
|
||||
With the new joker rule, the total winnings in this example are **`5905`**.
|
||||
|
||||
Using the new joker rule, find the rank of every hand in your set. **What are the new total winnings?**
|
1000
day_7/input.txt
Normal file
1000
day_7/input.txt
Normal file
File diff suppressed because it is too large
Load Diff
5
day_7/input_example_1.txt
Normal file
5
day_7/input_example_1.txt
Normal file
@ -0,0 +1,5 @@
|
||||
32T3K 765
|
||||
T55J5 684
|
||||
KK677 28
|
||||
KTJJT 220
|
||||
QQQJA 483
|
282
day_7/src/lib.rs
Normal file
282
day_7/src/lib.rs
Normal file
@ -0,0 +1,282 @@
|
||||
use core::str::FromStr;
|
||||
use std::{cmp::Ordering, collections::HashMap};
|
||||
|
||||
#[derive(Debug, Default, PartialEq, Eq, Clone)]
|
||||
pub struct Card {
|
||||
pub label: char,
|
||||
}
|
||||
|
||||
impl Card {
|
||||
const LABELS: [char; 13] = [
|
||||
'A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2',
|
||||
];
|
||||
|
||||
pub fn strength(&self) -> usize {
|
||||
Card::LABELS.len()
|
||||
- Card::LABELS
|
||||
.iter()
|
||||
.position(|¤t| current == self.label)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for Card {
|
||||
fn cmp(&self, other: &Self) -> Ordering {
|
||||
self.strength().cmp(&other.strength())
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for Card {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<char> for Card {
|
||||
fn from(label: char) -> Self {
|
||||
Card { label }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, PartialEq, Eq, Copy, Clone)]
|
||||
pub enum CardsHandType {
|
||||
#[default]
|
||||
HighCard = 1,
|
||||
OnePair = 2,
|
||||
TwoPair = 3,
|
||||
ThreeOfAKind = 4,
|
||||
FullHouse = 5,
|
||||
FourOfAKind = 6,
|
||||
FiveOfAKind = 7,
|
||||
}
|
||||
|
||||
impl CardsHandType {
|
||||
pub const fn strength(&self) -> usize {
|
||||
*self as usize
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for CardsHandType {
|
||||
fn cmp(&self, other: &Self) -> Ordering {
|
||||
self.strength().cmp(&other.strength())
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for CardsHandType {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, PartialEq, Eq, Clone)]
|
||||
pub struct CardsHand {
|
||||
pub cards: [Card; 5],
|
||||
pub bid: usize,
|
||||
}
|
||||
|
||||
impl CardsHand {
|
||||
pub fn hand_type(&self) -> CardsHandType {
|
||||
let mut label_counts: HashMap<char, usize> = HashMap::new();
|
||||
for card in &self.cards {
|
||||
if let Some(label_count) = label_counts.get_mut(&card.label) {
|
||||
*label_count += 1;
|
||||
} else {
|
||||
label_counts.insert(card.label, 1);
|
||||
}
|
||||
}
|
||||
let keys = label_counts.keys();
|
||||
if keys.len() == 1 {
|
||||
return CardsHandType::FiveOfAKind;
|
||||
}
|
||||
if keys.len() == 2 && label_counts.iter().any(|(_, &value)| value == 4) {
|
||||
return CardsHandType::FourOfAKind;
|
||||
}
|
||||
if keys.len() == 2 && label_counts.iter().any(|(_, &value)| value == 3) {
|
||||
return CardsHandType::FullHouse;
|
||||
}
|
||||
if keys.len() == 3 && label_counts.iter().any(|(_, &value)| value == 3) {
|
||||
return CardsHandType::ThreeOfAKind;
|
||||
}
|
||||
if keys.len() == 3 && label_counts.iter().any(|(_, &value)| value == 2) {
|
||||
return CardsHandType::TwoPair;
|
||||
}
|
||||
if keys.len() == 5 {
|
||||
return CardsHandType::HighCard;
|
||||
}
|
||||
CardsHandType::OnePair
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for CardsHand {
|
||||
fn cmp(&self, other: &Self) -> Ordering {
|
||||
if self.hand_type() != other.hand_type() {
|
||||
return self
|
||||
.hand_type()
|
||||
.strength()
|
||||
.cmp(&other.hand_type().strength());
|
||||
}
|
||||
for (self_card, other_card) in self.cards.iter().zip(other.cards.iter()) {
|
||||
if self_card != other_card {
|
||||
return self_card.cmp(other_card);
|
||||
}
|
||||
}
|
||||
Ordering::Equal
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for CardsHand {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for CardsHand {
|
||||
type Err = &'static str;
|
||||
|
||||
/// Parses a string `string` to return a value of [`CardsHand`]
|
||||
///
|
||||
/// If parsing succeeds, return the value inside [`Ok`], otherwise
|
||||
/// when the string is ill-formatted return an error specific to the
|
||||
/// inside [`Err`].
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use std::str::FromStr;
|
||||
/// use day_7::{Card, CardsHand, CardsHandType};
|
||||
///
|
||||
/// let string = "32T3K 765";
|
||||
/// let expected_result = CardsHand {
|
||||
/// cards: [Card { label: '3' }, Card { label: '2' }, Card { label: 'T' }, Card { label: '3' }, Card { label: 'K' } ],
|
||||
/// bid: 765,
|
||||
/// };
|
||||
///
|
||||
/// let actual_result = CardsHand::from_str(string).unwrap();
|
||||
/// let actual_hand_type = actual_result.hand_type();
|
||||
/// assert_eq!(actual_result, expected_result);
|
||||
/// ```
|
||||
fn from_str(string: &str) -> Result<Self, Self::Err> {
|
||||
let mut input = string.split_ascii_whitespace();
|
||||
let result = CardsHand {
|
||||
cards: array_init::from_iter(input.next().unwrap_or_default().chars().map(Card::from))
|
||||
.unwrap_or_default(),
|
||||
bid: input
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.trim()
|
||||
.parse()
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, PartialEq, Eq, Clone)]
|
||||
pub struct CamelCards {
|
||||
cards_hands: Vec<CardsHand>,
|
||||
}
|
||||
|
||||
impl FromStr for CamelCards {
|
||||
type Err = &'static str;
|
||||
|
||||
fn from_str(string: &str) -> Result<Self, Self::Err> {
|
||||
Ok(CamelCards {
|
||||
cards_hands: string
|
||||
.trim()
|
||||
.lines()
|
||||
.map(|line| CardsHand::from_str(line.trim()).unwrap_or_default())
|
||||
.collect::<Vec<CardsHand>>(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn part_1(input: &str) -> usize {
|
||||
let mut camel_cards = CamelCards::from_str(input).unwrap_or_default();
|
||||
camel_cards.cards_hands.sort();
|
||||
camel_cards
|
||||
.cards_hands
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, card_hand)| {
|
||||
let rank = index + 1;
|
||||
card_hand.bid * rank
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod day_7_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_part_1_example() {
|
||||
assert_eq!(part_1(include_str!("../input_example_1.txt")), 6440);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_part_1() {
|
||||
assert_eq!(part_1(include_str!("../input.txt")), 250370104);
|
||||
}
|
||||
|
||||
mod hand_types {
|
||||
use std::str::FromStr;
|
||||
|
||||
use crate::{CardsHand, CardsHandType};
|
||||
|
||||
#[test]
|
||||
fn test_five_of_a_kind() {
|
||||
let cards_hand = CardsHand::from_str("AAAAA").unwrap();
|
||||
let expected = CardsHandType::FiveOfAKind;
|
||||
let actual = cards_hand.hand_type();
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_four_of_a_kind() {
|
||||
let cards_hand = CardsHand::from_str("AA8AA").unwrap();
|
||||
let expected = CardsHandType::FourOfAKind;
|
||||
let actual = cards_hand.hand_type();
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_full_house() {
|
||||
let cards_hand = CardsHand::from_str("23332").unwrap();
|
||||
let expected = CardsHandType::FullHouse;
|
||||
let actual = cards_hand.hand_type();
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_three_of_a_kind() {
|
||||
let cards_hand = CardsHand::from_str("TTT98").unwrap();
|
||||
let expected = CardsHandType::ThreeOfAKind;
|
||||
let actual = cards_hand.hand_type();
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_two_pair() {
|
||||
let cards_hand = CardsHand::from_str("23432").unwrap();
|
||||
let expected = CardsHandType::TwoPair;
|
||||
let actual = cards_hand.hand_type();
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_one_pair() {
|
||||
let cards_hand = CardsHand::from_str("A23A4").unwrap();
|
||||
let expected = CardsHandType::OnePair;
|
||||
let actual = cards_hand.hand_type();
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_high_card() {
|
||||
let cards_hand = CardsHand::from_str("23456").unwrap();
|
||||
let expected = CardsHandType::HighCard;
|
||||
let actual = cards_hand.hand_type();
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
}
|
||||
}
|
8
day_7/src/main.rs
Normal file
8
day_7/src/main.rs
Normal file
@ -0,0 +1,8 @@
|
||||
use day_7::part_1;
|
||||
|
||||
fn main() {
|
||||
let input = include_str!("../input.txt");
|
||||
println!("- Day 7: Camel Cards -");
|
||||
println!("Answer Part 1: {}", part_1(input));
|
||||
// println!("Answer Part 2: {}", part_2(input));
|
||||
}
|
Loading…
Reference in New Issue
Block a user