commit ebb6d16853a66713fac9edc654b2534282fc2cec (patch)
parent 4204d91abdeb375b6f05a507a2d52d6175a530dc
Author: Alex Karle <alex@alexkarle.com>
Date: Sun, 5 Dec 2021 11:29:26 -0500
day5: Add C solution! So fast, so clean :)
It's looking like I'm fine at doing C so long as I don't need any
advanced data structures (mutable lists, hashmaps, etc).
I'd like to go back and brush up on both those when I have time. In the
meanwhile, I'll bask in the joy of a 5/b that's 20x faster than b.py!
$ time 5/b.py < 5/input
21305
0m00.69s real 0m00.66s user 0m00.03s system
$ time 5/b < 5/input
21305
0m00.03s real 0m00.01s user 0m00.01s system
Wild, no? It's almost definitely because we preallocate the 1000x1000
array ahead of time (although, if you see my previous commit, 1000x1000
in python wasn't actually faster than the defaultdict, which is odd...)
Diffstat:
A | 5/a.c | | | 36 | ++++++++++++++++++++++++++++++++++++ |
A | 5/b.c | | | 36 | ++++++++++++++++++++++++++++++++++++ |
M | Makefile | | | 2 | +- |
3 files changed, 73 insertions(+), 1 deletion(-)
diff --git a/5/a.c b/5/a.c
@@ -0,0 +1,36 @@
+#include <stdio.h>
+#include <stdlib.h>
+
+int main(void) {
+ int grid[1000][1000] = {0};
+
+ int x1, y1, x2, y2;
+ while (scanf("%d,%d -> %d,%d\n", &x1, &y1, &x2, &y2) != EOF) {
+ /* key: for vert/horiz lines doesn't matter which one you
+ * start at (since you draw the same line either way */
+ if (x1 == x2) {
+ int dist = abs(y1 - y2);
+ int start = y1 < y2 ? y1 : y2;
+ for (int i = start; i <= start + dist; i++) {
+ grid[x1][i]++;
+ }
+ } else if (y1 == y2) {
+ int dist = abs(x1 - x2);
+ int start = x1 < x2 ? x1 : x2;
+ for (int i = start; i <= start + dist; i++) {
+ grid[i][y1]++;
+ }
+ }
+ }
+
+ int count = 0;
+ for (int r = 0; r < 1000; r++) {
+ for (int c = 0; c < 1000; c++) {
+ if (grid[r][c] > 1) {
+ count++;
+ }
+ }
+ }
+ printf("%d\n", count);
+ return 0;
+}
diff --git a/5/b.c b/5/b.c
@@ -0,0 +1,36 @@
+#include <stdio.h>
+#include <stdlib.h>
+
+int grid[1000][1000] = {0};
+
+void draw(int x1, int y1, int x2, int y2) {
+ int r = x1;
+ int c = y1;
+ int rstep = x1 == x2 ? 0 : (x1 < x2 ? 1 : -1);
+ int cstep = y1 == y2 ? 0 : (y1 < y2 ? 1 : -1);
+ while (r != x2 || c != y2) {
+ grid[r][c]++;
+ r += rstep;
+ c += cstep;
+ }
+ /* loop stops before marking last point! */
+ grid[x2][y2]++;
+}
+
+int main(void) {
+ int x1, y1, x2, y2;
+ while (scanf("%d,%d -> %d,%d\n", &x1, &y1, &x2, &y2) != EOF) {
+ draw(x1, y1, x2, y2);
+ }
+
+ int count = 0;
+ for (int r = 0; r < 1000; r++) {
+ for (int c = 0; c < 1000; c++) {
+ if (grid[r][c] > 1) {
+ count++;
+ }
+ }
+ }
+ printf("%d\n", count);
+ return 0;
+}
diff --git a/Makefile b/Makefile
@@ -11,7 +11,7 @@
CFLAGS = -g -O2 -Wall -Wpedantic -Wextra
DAY = *
-TARGETS = 1/a 1/b 2/a 2/b 3/a
+TARGETS = 1/a 1/b 2/a 2/b 3/a 5/a 5/b
.PHONY: build
build: $(TARGETS)