day 25 optimize and improve heuristics
[aoc_eblake.git] / 2018 / day10.c
blob9e4792184c33db2b7df06023886a3272049e27c3
1 #define _GNU_SOURCE 1
2 #include <stdio.h>
3 #include <string.h>
4 #include <stdlib.h>
5 #include <stdarg.h>
6 #include <stdbool.h>
7 #include <assert.h>
9 void debug(const char *fmt, ...) {
10 va_list ap;
11 if (getenv("DEBUG")) {
12 va_start(ap, fmt);
13 vfprintf(stderr, fmt, ap);
14 va_end(ap);
18 #define LIMIT 300
20 static struct data {
21 int x;
22 int y;
23 int vx;
24 int vy;
25 } list[LIMIT];
27 void display(int count, int y, int minx, int maxx) {
28 int i, j;
29 for (i = minx; i <= maxx; i++) {
30 char c = '.';
31 for (j = 0; j < count; j++)
32 if (list[j].y == y && list[j].x == i)
33 c = '#';
34 putchar(c);
36 putchar('\n');
39 int main(int argc, char **argv) {
40 size_t len = 0, count = 0;
41 char *line;
42 int i;
43 int minx, miny, maxx, maxy, gap;
44 int iters = 0;
46 /* Part 1 - read in lines */
47 if (argc > 1)
48 if (!(stdin = freopen(argv[1], "r", stdin))) {
49 perror("failure");
50 exit(2);
53 while (getline(&line, &len, stdin) >= 0) {
54 if (sscanf(line, "position=<%d,%d> velocity=<%d,%d> ", &list[count].x,
55 &list[count].y, &list[count].vx, &list[count].vy) != 4) {
56 fprintf(stderr, "bad input\n");
57 exit(1);
59 ++count;
61 printf("Read %zu lines\n", count);
63 /* Part 2 - minimize gap */
64 minx = miny = 100000;
65 maxx = maxy = -100000;
66 gap = 200000;
67 for (i = 0; i < count; i++) {
68 if (list[i].y > maxy)
69 maxy = list[i].y;
70 if (list[i].y < miny)
71 miny = list[i].y;
72 if (list[i].x > maxx)
73 maxx = list[i].x;
74 if (list[i].x < minx)
75 minx = list[i].x;
77 printf("Starting with gap %d, column %d\n", maxy - miny, minx);
78 do {
79 iters++;
80 gap = maxy - miny;
81 minx = miny = 100000;
82 maxx = maxy = -100000;
83 for (i = 0; i < count; i++) {
84 list[i].x += list[i].vx;
85 list[i].y += list[i].vy;
86 if (list[i].y > maxy)
87 maxy = list[i].y;
88 if (list[i].y < miny)
89 miny = list[i].y;
90 if (list[i].x > maxx)
91 maxx = list[i].x;
92 if (list[i].x < minx)
93 minx = list[i].x;
95 } while (maxy - miny < gap);
96 printf("After %d iters, gap is %d, column %d\n", iters, gap, minx);
98 /* Part 3 - undo last iteration, and print array */
99 for (i = 0; i < count; i++) {
100 list[i].x -= list[i].vx;
101 list[i].y -= list[i].vy;
103 for (i = miny - 2; i < maxy + 2; i++)
104 display(count, i, minx - 3, maxx + 3);
105 return 0;