summary refs log tree commit diff homepage
path: root/2018/day09.c
blob: 804392bdf7ae5cb407a8d11d3b342718f1814ca1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <stdio.h>
#include <stdlib.h>

typedef unsigned uint;

static struct Marble {
	uint num;
	struct Marble *prev;
	struct Marble *next;
} *current;

static struct Marble *ins(struct Marble *prev, uint num) {
	struct Marble *next = malloc(sizeof(*next));
	next->num = num;
	next->prev = prev;
	next->next = prev->next;
	next->prev->next = next;
	next->next->prev = next;
	return next;
}

static struct Marble *rem(struct Marble *marb) {
	struct Marble *next = marb->next;
	marb->prev->next = marb->next;
	marb->next->prev = marb->prev;
	free(marb);
	return next;
}

int main() {
	uint players, marbles;
	scanf("%u players; last marble is worth %u points", &players, &marbles);
	marbles += 1;

	uint scores[players];
	for (uint i = 0; i < players; ++i) {
		scores[i] = 0;
	}

	current = malloc(sizeof(*current));
	current->num = 0;
	current->prev = current;
	current->next = current;

	uint marble = 1;
	while (marble < marbles) {
		for (uint i = 0; i < players; ++i) {
			if (marble % 23) {
				current = ins(current->next, marble);
			} else {
				scores[i] += marble;
				struct Marble *marb = current;
				for (uint j = 0; j < 7; ++j) {
					marb = marb->prev;
				}
				scores[i] += marb->num;
				current = rem(marb);
			}
			if (++marble == marbles) break;
		}
	}

	uint max = 0;
	for (uint i = 0; i < players; ++i) {
		if (scores[i] > max) max = scores[i];
	}
	printf("%u\n", max);
}