Browse Source

day9p1

master
mid-kid 6 years ago
parent
commit
c6ed79ba6a
  1. 12
      day9p1/Makefile
  2. 1
      day9p1/input
  3. 89
      day9p1/main.c

12
day9p1/Makefile

@ -0,0 +1,12 @@
CFLAGS := -Wall -Wextra -std=c17 -D_GNU_SOURCE
#LIBS := glib-2.0
#CFLAGS += $(shell pkg-config --cflags $(LIBS))
#LDLIBS := $(shell pkg-config --libs $(LIBS))
.PHONY: all
all: main
.PHONY: clean
clean:
rm -f main

1
day9p1/input

@ -0,0 +1 @@
447 players; last marble is worth 71510 points

89
day9p1/main.c

@ -0,0 +1,89 @@
#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;
}
Loading…
Cancel
Save