#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 int score[MAX_ELVES] = {0};
int winning_score = 0;
int elf, num_elves, winner;
#define MAX_MARBLES 100000
static int stock[MAX_MARBLES];
static int circle[MAX_MARBLES];
int circle_size = 0;
int current, next, 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. */
for (int i = 0; i <= last; ++i) {
stock[i] = i;
}
next = 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[current = circle_size++] = stock[next++];
/* Then, each Elf takes a turn... */
for (;;) for (elf = 0; elf < num_elves; ++elf) {
if (0) {
printf("%d: ", elf);
for (int i = 0; i < circle_size; ++i) {
printf("%s%d%s ", "["+(i!=current), circle[i], "]"+(i!=current));
}
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 (stock[next] % 23) {
current = (current + 2) % circle_size;
for (int i = circle_size++; i > current; --i) {
circle[i] = circle[i - 1];
}
circle[current] = stock[next++];
}
else {
/* First, the current player keeps the marble
* they would have placed, adding it to their
* score. */
score[elf] += stock[next++];
/* 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. */
current += circle_size - 7 % circle_size;
current %= circle_size;
score[elf] += circle[current];
--circle_size;
for (int i = current; i < circle_size; ++i) {
circle[i] = circle[i + 1];
}
/* The goal is to be the player with the highest score... */
if (score[elf] > winning_score) {
winning_score = score[winner = elf];
if (0) {
printf("%d: %d\n", winner, winning_score);
}
}
}
/* ...after the last marble is used up. */
if (next > last) {
printf("%d\n", winning_score);
return 0;
}
}
}