You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
89 lines
2.1 KiB
89 lines
2.1 KiB
#include <stdlib.h>
|
|
#include <stdio.h>
|
|
|
|
struct marble {
|
|
struct marble *next;
|
|
struct marble *prev;
|
|
int value;
|
|
};
|
|
|
|
void *xmalloc(size_t size)
|
|
{
|
|
void *res = malloc(size);
|
|
if (!res) {
|
|
perror("malloc");
|
|
exit(1);
|
|
}
|
|
return res;
|
|
}
|
|
|
|
void *xcalloc(size_t nmemb, size_t size)
|
|
{
|
|
void *res = calloc(nmemb, size);
|
|
if (!res) {
|
|
perror("calloc");
|
|
exit(1);
|
|
}
|
|
return res;
|
|
}
|
|
|
|
int main(int argc, char *argv[])
|
|
{
|
|
if (argc <= 2) {
|
|
fprintf(stderr, "Usage: %s <players> <marbles>\n", argv[0]);
|
|
return 1;
|
|
}
|
|
|
|
int players = strtol(argv[1], NULL, 0);
|
|
int marbles = strtol(argv[2], NULL, 0);
|
|
if (!players || marbles <= 1) return 1;
|
|
|
|
int *scores = xcalloc(players, sizeof(int));
|
|
int player = 0;
|
|
|
|
struct marble *current = xmalloc(sizeof(struct marble));
|
|
current->next = current;
|
|
current->prev = current;
|
|
current->value = 0;
|
|
|
|
for (int i = 1; i <= marbles; i++) {
|
|
if (i % 23 == 0) {
|
|
scores[player] += i;
|
|
for (int i = 0; i < 7; i++) {
|
|
current = current->prev;
|
|
}
|
|
scores[player] += current->value;
|
|
current->prev->next = current->next;
|
|
current->next->prev = current->prev;
|
|
|
|
struct marble *remove = current;
|
|
current = current->next;
|
|
free(remove);
|
|
} else {
|
|
current = current->next;
|
|
struct marble *new = xmalloc(sizeof(struct marble));
|
|
new->next = current->next;
|
|
new->prev = current;
|
|
new->next->prev = new;
|
|
new->prev->next = new;
|
|
new->value = i;
|
|
current = new;
|
|
}
|
|
|
|
if (++player >= players) player = 0;
|
|
}
|
|
|
|
int highest = 0;
|
|
for (int *score = scores; score < scores + players; score++) {
|
|
if (*score > highest) highest = *score;
|
|
}
|
|
printf("Highest score: %d\n", highest);
|
|
|
|
current->prev->next = NULL;
|
|
while (current->next) {
|
|
current = current->next;
|
|
free(current->prev);
|
|
}
|
|
free(current);
|
|
return 0;
|
|
}
|
|
|