@@ -97,7 +97,7 @@ fn game(players: usize, last: usize) -> u64 {
9797 // The number of marbles needed for scoring.
9898 let needed = 2 + 16 * blocks;
9999 // Each block adds 37 marbles, so allow a little extra capacity to prevent reallocation.
100- let mut circle: Vec < u32 > = Vec :: with_capacity ( needed + 37 ) ;
100+ let mut circle: Vec < u32 > = vec ! [ 0 ; needed + 37 ] ;
101101 // The score for each block is deterministic so the number of players only affects how scores
102102 // are distributed. Type is `u64` to prevent overflow during part two.
103103 let mut scores = vec ! [ 0 ; players] ;
@@ -107,9 +107,11 @@ fn game(players: usize, last: usize) -> u64 {
107107 let mut head = 23 ;
108108 // Keep track of previous marbles to re-add to the start of the circle and for scoring.
109109 let mut tail = 0 ;
110+ // Keep track of how many marbles have been placed.
111+ let mut placed = 22 ;
110112 // Add pre-generated marbles for first block.
111113 let start = [ 2 , 20 , 10 , 21 , 5 , 22 , 11 , 1 , 12 , 6 , 13 , 3 , 14 , 7 , 15 , 0 , 16 , 8 , 17 , 4 , 18 , 19 ] ;
112- circle. extend_from_slice ( & start) ;
114+ circle[ 0 .. 22 ] . copy_from_slice ( & start) ;
113115
114116 for _ in 0 ..blocks {
115117 // Score the previous block.
@@ -118,7 +120,7 @@ fn game(players: usize, last: usize) -> u64 {
118120 pickup = circle[ tail + 18 ] ;
119121
120122 // Generate the next block only until we have enough marbles to finish the game.
121- if circle . len ( ) <= needed {
123+ if placed <= needed {
122124 // Extending a vector from a slice is faster than adding elements one at a time.
123125 let slice = & [
124126 circle[ tail] ,
@@ -160,7 +162,7 @@ fn game(players: usize, last: usize) -> u64 {
160162 // circle[tail + 18] 19th marble is picked up and removed.
161163 head + 19 ,
162164 ] ;
163- circle. extend_from_slice ( slice) ;
165+ circle[ placed..placed + 37 ] . copy_from_slice ( slice) ;
164166
165167 // Overwrite the tail for the 20th, 21st and 22nd marbles.
166168 let slice = & [
@@ -172,6 +174,9 @@ fn game(players: usize, last: usize) -> u64 {
172174 head + 22 ,
173175 ] ;
174176 circle[ tail + 16 ..tail + 22 ] . copy_from_slice ( slice) ;
177+
178+ // Keep track of how many marbles have been placed.
179+ placed += 37 ;
175180 }
176181
177182 // Marbles increase by 23 per block but the tail only by 16 as we reset by 7 marbles
0 commit comments