Skip to main content

aoc/year2021/
day21.rs

1//! # Dirac Dice
2use crate::util::iter::*;
3use crate::util::parse::*;
4
5/// Rolling the Dirac dice 3 times results in 27 quantum universes. However, the dice total is
6/// one of only 7 possible values. Instead of handling 27 values, we encode the possible dice
7/// totals with the number of times that they occur. For example, a score of 3 (1 + 1 + 1) only
8/// happens once in the 27 rolls, but a score of 6 happens a total of 7 times.
9const DIRAC: [Pair; 7] = [(3, 1), (4, 3), (5, 6), (6, 7), (7, 6), (8, 3), (9, 1)];
10
11type Pair = (usize, usize);
12
13/// Extract the starting position for both players converting to zero-based indices.
14pub 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
19/// The initial deterministic dice roll total is 6 (1 + 2 + 3) and increases by 9 each turn.
20/// An interesting observation is that since the player's position is always modulo 10, we can
21/// also increase the dice total modulo 10, as (a + b) % 10 = (a % 10) + (b % 10). Additionally,
22/// both players end up back in the same position every 10 moves, so we can compute the score per
23/// batch of 10 moves before simulating only the remainder.
24pub fn part1(input: &Pair) -> usize {
25    let mut dice = 6;
26    let (player, other) = *input;
27
28    // Utilize the periodic visitation pattern to compute the 10-turn score increase per player.
29    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; // 2 players * 3 dice * 10 turns per batch.
37    let mut state = ((player, player_batch * batches), (other, other_batch * batches));
38
39    loop {
40        // Player position is 0 based from 0 to 9, but score is 1 based from 1 to 10.
41        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        // Return the score of the losing player times the number of dice rolls.
49        if next_score >= 1000 {
50            break other_score * rolls;
51        }
52
53        // Swap the players so that they take alternating turns.
54        state = ((other_position, other_score), (next_position, next_score));
55    }
56}
57
58/// Handle each player separately. The number of universes for each player grows independently.
59/// When a player wins, then multiply the number of states by the other player's states.
60pub 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}