aboutsummaryrefslogtreecommitdiff
path: root/04/part1.c
diff options
context:
space:
mode:
authorMistivia <i@mistivia.com>2025-12-21 18:45:50 +0800
committerMistivia <i@mistivia.com>2025-12-21 18:45:50 +0800
commit91c777fc315233341b19677f816048ab63a8a667 (patch)
treebb54486044123e25708c22e74f08ccbd6881629e /04/part1.c
parentb01124e56ca4cee22649d5a0e885c898685ecf00 (diff)
day 4 part1
Diffstat (limited to '04/part1.c')
-rw-r--r--04/part1.c89
1 files changed, 89 insertions, 0 deletions
diff --git a/04/part1.c b/04/part1.c
new file mode 100644
index 0000000..0603946
--- /dev/null
+++ b/04/part1.c
@@ -0,0 +1,89 @@
+#include <algds/str.h>
+#include <algds/vec.h>
+
+StringVector readmap() {
+ StringVector map;
+ StringVector_init(&map);
+ while (1) {
+ char *l = fgetline(stdin);
+ if (!l) {
+ return map;
+ }
+ char *nl = str_strip(l);
+ free(l);
+ l = nl;
+ if (strlen(l) == 0) {
+ return map;
+ }
+ StringVector_push_back(&map, l);
+ }
+ return map;
+}
+
+char map_read(StringVector *map, int x, int y) {
+ int height = StringVector_len(map);
+ if (height == 0) {
+ return '\0';
+ }
+ int width = strlen(*StringVector_ref(map, 0));
+ if (x >= width || x < 0) {
+ return '\0';
+ }
+ if (y >= height || y < 0) {
+ return '\0';
+ }
+ return (*StringVector_ref(map, y))[x];
+}
+
+
+bool is_paper(StringVector *map, int x, int y) {
+ return map_read(map, x, y) == '@';
+}
+
+int count_adjacent(StringVector *map, int x, int y) {
+ int count = 0;
+ if (is_paper(map, x - 1, y - 1)) {
+ count++;
+ }
+ if (is_paper(map, x - 1, y)) {
+ count++;
+ }
+ if (is_paper(map, x, y - 1)) {
+ count++;
+ }
+ if (is_paper(map, x + 1, y + 1)) {
+ count++;
+ }
+ if (is_paper(map, x + 1, y)) {
+ count++;
+ }
+ if (is_paper(map, x, y + 1)) {
+ count++;
+ }
+ if (is_paper(map, x + 1, y - 1)) {
+ count++;
+ }
+ if (is_paper(map, x - 1, y + 1)) {
+ count++;
+ }
+ return count;
+}
+
+int main() {
+ StringVector map = readmap();
+ int height = StringVector_len(&map);
+ int width = strlen(*StringVector_ref(&map, 0));
+ int res = 0;
+ for (int x = 0; x < width; x++) {
+ for (int y = 0; y < height; y++) {
+ if (map_read(&map, x, y) != '@') {
+ continue;
+ }
+ if (count_adjacent(&map, x, y) < 4) {
+ res++;
+ }
+ }
+ }
+ printf("%d\n", res);
+ return 0;
+} \ No newline at end of file