Advertisement
Douma37

aoc2022/day09

Dec 9th, 2022
789
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.63 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. enum {max_size = 2000};
  6.  
  7. struct cmd {
  8.   char dir;
  9.   int distance;
  10. };
  11.  
  12. struct location {
  13.   int hx, hy, tx, ty;
  14. };
  15.  
  16. void updateLoc(struct location* l, struct cmd* c) {
  17.   char dir = c->dir;
  18.   if (dir == 'U') {
  19.     --l->hy;
  20.   } else if (dir == 'D') {
  21.     ++l->hy;
  22.   } else if (dir == 'L') {
  23.     --l->hx;
  24.   } else if (dir == 'R') {
  25.     ++l->hx;
  26.   } else {
  27.     printf("Direction %c not recognised\n", dir);
  28.   }
  29.   printf("head now at %d,%d\n", l->hx, l->hy);
  30.   // tail follows
  31.   if (l->hx - l->tx > 1)
  32.     ++l->tx;
  33.   if (l->tx - l->hx > 1)
  34.     --l->tx;
  35.   if (l->hy - l->ty > 1)
  36.     ++l->ty;
  37.   if (l->ty - l->hy > 1)
  38.     --l->ty;
  39. }
  40.  
  41. int part1(struct cmd cmds[], int size) {
  42.   printf("in p1\n");
  43.   int grid[max_size][max_size] = {0};
  44.   struct location l;
  45.   l.hx = 1000;
  46.   l.hy = 1000;
  47.   l.tx = 1000;
  48.   l.ty = 1000;
  49.   for (int i = 0; i < size; ++i) {
  50.     printf("command %c %d\n", cmds[i].dir, cmds[i].distance);
  51.     for (int j = 0; j < cmds[i].distance; ++j)
  52.       updateLoc(&l, &cmds[i]);
  53.     printf("location updated\n");
  54.     grid[l.ty][l.tx] = 1;
  55.   }
  56.   int count = 0;
  57.   for (int x = 0; x < max_size; ++x) {
  58.     for (int y = 0; y < max_size; ++y) {
  59.       if (grid[y][x] != 0)
  60.         ++count;
  61.     }
  62.   }
  63.   return count;
  64. }
  65.  
  66. int main() {
  67.   int i = 0;
  68.   struct cmd list[max_size];
  69.   int ret = 2;
  70.   while (ret == 2) {
  71.     ret = scanf("%c %d\n", &list[i].dir, &list[i].distance);
  72.     if (ret < 2) break;
  73.     ++i;
  74.   }
  75.   printf("read %d intructions\n", i);
  76.   int value = part1(list, i);
  77.   printf("%d\n", value);
  78.   //printf("%d\n", part2(list, i));
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement