day 1 golfed M4 500 significant bytes
[aoc_eblake.git] / 2017 / advent20.c
blobf3160d413770dd84d43784fbe57dcedcc76b1a74
1 #define _GNU_SOURCE 1
2 #include <stdio.h>
3 #include <string.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6 #include <stdbool.h>
7 #include <ctype.h>
9 #define MAX 1000 // determined by wc on the input
11 typedef struct particle particle;
12 struct particle {
13 int px;
14 int py;
15 int pz;
16 int vx;
17 int vy;
18 int vz;
19 int ax;
20 int ay;
21 int az;
22 bool dead;
23 } field[MAX];
25 int
26 main (int argc, char **argv)
28 int minrow;
29 int minvalue = 999999;
30 particle *p = field;
31 while (scanf ("p=<%d,%d,%d>, v=<%d,%d,%d>, a=<%d,%d,%d>\n", &p->px, &p->py,
32 &p->pz, &p->vx, &p->vy, &p->vz, &p->ax, &p->ay, &p->az) == 9) {
33 int value = abs (p->ax) + abs (p->ay) + abs (p->az);
34 if (value < minvalue) {
35 minvalue = value;
36 minrow = p - field;
38 p++;
40 printf ("closest particle among %d is %d\n", (int) (p - field), minrow);
41 int gen = 0, i, j;
42 bool done = false;
43 while (!done) {
44 // remove collisions
45 done = true;
46 for (i = 0; i < MAX - 1; i++) {
47 bool dead = false;
48 if (field[i].dead)
49 continue;
50 for (j = i + 1; j < MAX; j++)
51 if (!field[j].dead && field[i].px == field[j].px &&
52 field[i].py == field[j].py && field[i].pz == field[j].pz)
53 dead = field[j].dead = true;
54 field[i].dead = dead;
56 // move particles; keep iterating if position or velocity decreases
57 int alive = 0;
58 for (i = 0; i < MAX; i++) {
59 p = &field[i];
60 if (p->dead)
61 continue;
62 alive++;
63 int oldp = abs (p->px) + abs (p->py) + abs (p->pz);
64 int oldv = abs (p->vx) + abs (p->vy) + abs (p->vz);
65 p->vx += p->ax;
66 p->vy += p->ay;
67 p->vz += p->az;
68 p->px += p->vx;
69 p->py += p->vy;
70 p->pz += p->vz;
71 if (oldp > abs (p->px) + abs (p->py) + abs (p->pz) ||
72 oldv > abs (p->vx) + abs (p->vy) + abs (p->vz))
73 done = false;
75 printf ("at time %d with %d particles\n", gen, alive);
76 gen++;
78 printf ("all particles resolved\n");
79 return 0;