-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday-22.rs
162 lines (139 loc) · 3.86 KB
/
day-22.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
use std::{
cmp::Ordering,
collections::{hash_map::DefaultHasher, HashSet, VecDeque},
hash::{Hash, Hasher},
str::FromStr,
};
const INPUT: &str = include_str!("day-22.input");
fn main() {
let game: Game = INPUT.parse().unwrap();
println!("part 1: {}", part_1(game.clone()));
println!("part 2: {}", part_2(game));
}
fn part_1(mut game: Game) -> usize {
let deck = game.run_normal();
game.deck(deck).score()
}
fn part_2(mut game: Game) -> usize {
let deck = game.run_recursive();
game.deck(deck).score()
}
#[derive(Clone)]
struct Game {
decks: Vec<Deck>,
hashes: HashSet<u64>,
}
impl FromStr for Game {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self {
decks: s
.trim()
.split("\n\n")
.map(|deck| deck.parse().unwrap())
.collect(),
hashes: HashSet::new(),
})
}
}
impl Game {
fn deck(&mut self, index: usize) -> &mut Deck {
&mut self.decks[index]
}
fn run_normal(&mut self) -> usize {
loop {
if let Some(deck) = self.normal_round() {
break deck;
}
}
}
fn run_recursive(&mut self) -> usize {
loop {
if let Some(deck) = self.recursive_round() {
break deck;
}
}
}
fn normal_round(&mut self) -> Option<usize> {
let drawn = [self.deck(0).draw(), self.deck(1).draw()];
self.highest_win(&drawn)
}
fn recursive_round(&mut self) -> Option<usize> {
let mut hasher = DefaultHasher::new();
self.decks.hash(&mut hasher);
if !self.hashes.insert(hasher.finish()) {
return Some(0);
}
let drawn = [self.deck(0).draw(), self.deck(1).draw()];
if self.deck(0).len() >= drawn[0] && self.deck(1).len() >= drawn[1] {
let mut subgame = self.clone();
subgame.deck(0).truncate(drawn[0]);
subgame.deck(1).truncate(drawn[1]);
self.round_end(&drawn, subgame.run_recursive())
} else {
self.highest_win(&drawn)
}
}
fn highest_win(&mut self, drawn: &[usize; 2]) -> Option<usize> {
self.round_end(
drawn,
match drawn[0].cmp(&drawn[1]) {
Ordering::Greater => 0,
Ordering::Less => 1,
Ordering::Equal => panic!("it's a draw!"),
},
)
}
fn round_end(&mut self, drawn: &[usize; 2], winner: usize) -> Option<usize> {
let loser = 1 - winner;
self.deck(winner).push_2(drawn[winner], drawn[loser]);
if self.deck(loser).is_empty() {
Some(winner)
} else {
None
}
}
}
#[derive(Clone, Hash)]
struct Deck {
name: String,
cards: VecDeque<usize>,
}
impl FromStr for Deck {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut it = s.lines();
let name = it.next().unwrap();
let name = name[..name.rfind(':').unwrap()].to_string();
let cards = it.map(|line| line.parse().unwrap()).collect();
Ok(Self { name, cards })
}
}
impl Deck {
fn is_empty(&self) -> bool {
self.cards.is_empty()
}
fn len(&self) -> usize {
self.cards.len()
}
fn truncate(&mut self, len: usize) {
self.cards.truncate(len)
}
fn draw(&mut self) -> usize {
self.cards.pop_front().unwrap()
}
fn push_2(&mut self, a: usize, b: usize) {
self.cards.push_back(a);
self.cards.push_back(b);
}
fn score(&self) -> usize {
self.iter()
.rev()
.enumerate()
.map(|(i, card)| (i + 1) * card)
.sum()
}
fn iter(&self) -> impl DoubleEndedIterator<Item = usize> + '_ {
self.cards.iter().copied()
}
}