#include
int main(int argc, char *argv[]) {
/* The Elves play this game by taking turns arranging the marbles in
* a circle according to very particular rules. */
#define MAX_ELVES 1000
static long score[MAX_ELVES] = {0};
long winning_score;
int elf, num_elves;
#define MAX_MARBLES 0x800000 // must be a power of 2
static int circle[MAX_MARBLES];
int current, gap, mask = MAX_MARBLES - 1;
int marble, last;
if (
argc < 3 ||
sscanf(argv[1], "%d", &num_elves) != 1 ||
num_elves > MAX_ELVES ||
sscanf(argv[2], "%d", &last) != 1 ||
last >= MAX_MARBLES
) return 1;
/* The marbles are numbered starting with 0 and increasing by 1
* until every marble has a number. */
marble = 0;
/* First, the marble numbered 0 is placed in the circle.
* At this point, while it contains only a single marble, it is
* still a circle: the marble is both clockwise from itself and
* counter-clockwise from itself. This marble is designated the
* current marble. */
circle[0] = marble++;
current = 0;
gap = 1;
/* Then, each Elf takes a turn... */
for (;;) for (elf = 0; elf < num_elves; elf++) {
if (0) {
printf("%d: @%d ", elf, current);
for (int i = current; i != gap;) {
printf("%d ", circle[i]);
i = i + 1 & mask;
}
putchar('\n');
}
/* ...placing the lowest-numbered remaining marble
* into the circle between the marbles that are 1 and
* 2 marbles clockwise of the current marble. (When
* the circle is large enough, this means that there
* is one marble between the marble that was just
* placed and the current marble.) The marble that
* was just placed then becomes the current marble.
*
* However, if the marble that is about to be placed
* has a number which is a multiple of 23, something
* entirely different happens. */
if (marble % 23) {
circle[gap] = circle[current];
gap = gap + 1 & mask;
current = current + 1 & mask;
circle[gap] = circle[current];
gap = gap + 1 & mask;
circle[current] = marble++;
}
else {
/* First, the current player keeps the marble
* they would have placed, adding it to their
* score. */
score[elf] += marble++;
/* In addition, the marble 7 marbles counter-
* clockwise from the current marble is removed
* from the circle and also added to the
* current player's score. The marble located
* immediately clockwise of the marble that was
* removed becomes the new current marble. */
for (int i = 0; i < 6; i++) {
current = current - 1 & mask;
gap = gap - 1 & mask;
circle[current] = circle[gap];
}
gap = gap - 1 & mask;
score[elf] += circle[gap];
}
/* The goal is to be the player with the highest score */
/* after the last marble is used up. */
if (marble > last) goto game_over;
}
game_over:
winning_score = 0;
for (elf = 0; elf < num_elves; elf++) {
if (score[elf] > winning_score) {
winning_score = score[elf];
}
}
printf("%ld\n", winning_score);
return 0;
}