1use crate::util::iter::*;
3use crate::util::parse::*;
4
5const DIRAC: [Pair; 7] = [(3, 1), (4, 3), (5, 6), (6, 7), (7, 6), (8, 3), (9, 1)];
10
11type Pair = (usize, usize);
12
13pub fn parse(input: &str) -> Pair {
15 let [_, one, _, two]: [usize; 4] = input.iter_unsigned().chunk::<4>().next().unwrap();
16 (one - 1, two - 1)
17}
18
19pub fn part1(input: &Pair) -> usize {
25 let mut dice = 6;
26 let (player, other) = *input;
27
28 let batch_score = |position, offsets: &[usize]| -> usize {
30 offsets.iter().map(|offset| (position + offset) % 10 + 1).sum()
31 };
32 let player_batch = batch_score(player, &[6, 0, 2, 2, 0, 6, 0, 2, 2, 0]);
33 let other_batch = batch_score(other, &[5, 8, 9, 8, 5, 0, 3, 4, 3, 0]);
34
35 let batches = 999 / player_batch.max(other_batch);
36 let mut rolls = batches * 60; let mut state = ((player, player_batch * batches), (other, other_batch * batches));
38
39 loop {
40 let ((player_position, player_score), (other_position, other_score)) = state;
42 let next_position = (player_position + dice) % 10;
43 let next_score = player_score + next_position + 1;
44
45 dice = (dice + 9) % 10;
46 rolls += 3;
47
48 if next_score >= 1000 {
50 break other_score * rolls;
51 }
52
53 state = ((other_position, other_score), (next_position, next_score));
55 }
56}
57
58pub fn part2(input: &Pair) -> usize {
61 let (player, other) = *input;
62
63 let mut current = [[[0; 21]; 10]; 2];
64 let mut wins = [0; 2];
65 let mut universes = 1;
66 let mut turn = 0;
67
68 current[0][player][0] = 1;
69 current[1][other][0] = 1;
70
71 while universes > 0 {
72 let mut next = [[0; 21]; 10];
73
74 for (dice, frequency) in DIRAC {
75 for (position, row) in current[turn].iter().enumerate() {
76 let next_position = (position + dice) % 10;
77 let (todo, won) = row.split_at(20 - next_position);
78
79 for (score, &amount) in todo.iter().enumerate() {
80 next[next_position][score + next_position + 1] += frequency * amount;
81 }
82
83 wins[turn] += universes * frequency * won.iter().sum::<usize>();
84 }
85 }
86
87 current[turn] = next;
88 universes = current[turn].iter().flatten().sum();
89 turn ^= 1;
90 }
91
92 wins[0].max(wins[1])
93}