~quf/computers-are-fast-2020

computers-are-fast-2020/src/12.c -rw-r--r-- 2.0 KiB
6f56515eLukas Himbert Draw the rest of the fine owl. 1 year, 7 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

#define abs(x) (x > 0 ? x : -x)

typedef struct {
  long x;
  long y;
} point_t;

#define dir_t unsigned
#define EAST 0
#define NORTH 1
#define WEST 2
#define SOUTH 3

point_t move_forward(point_t position, dir_t direction, long steps) {
  point_t result = position;
  switch (direction) {
    case EAST: /* east */
      result.x += steps;
      break;
    case NORTH: /* north */
      result.y += steps;
      break;
    case WEST: /* west */
      result.x -= steps;
      break;
    case SOUTH: /* south */
      result.y -= steps;
      break;
    default:
      break;
  }
  return result;
}

point_t rot_r(point_t p) {
  point_t result = {
    .x =  p.y,
    .y = -p.x,
  };
  return result;
}

point_t rot_l(point_t p) {
  point_t result = {
    .x = -p.y,
    .y =  p.x,
  };
  return result;
}

int main(void) {
  point_t pos1 = { .x = 0, .y = 0 };
  dir_t dir1 = EAST;

  point_t pos2 = { .x = 0, .y = 0 };
  point_t wp2 = { .x = 10, .y = 1 };

  dir_t directions[1<<CHAR_BIT] = { 0, };
  directions['E'] = EAST;
  directions['N'] = NORTH;
  directions['W'] = WEST;
  directions['S'] = SOUTH;

  int ret = 0;
  char c = 0;
  long n = 0;
  while ((ret = scanf("%c%ld\n", &c, &n)) > 0) {
    switch(c) {
      case 'L':
        for (long i = 0; i < n; i += 90) {
          dir1 = (dir1 + 1) % 4;
          wp2 = rot_l(wp2);
        }
        break;
      case 'R':
        for (long i = 0; i < n; i += 90) {
          dir1 = (dir1 + 3) % 4;
          wp2 = rot_r(wp2);
        }
        break;
      case 'F':
        pos1 = move_forward(pos1, dir1, n);
        pos2.x += n * wp2.x;
        pos2.y += n * wp2.y;
        break;
      default:
        pos1 = move_forward(pos1, directions[(size_t) c], n);
        wp2  = move_forward(wp2,  directions[(size_t) c], n);
        break;
    }
  }
  if (ret != EOF) {
    fprintf(stderr, "Input error: %s.\n", strerror(errno));
    return 1;
  }

  printf("%ld\n", abs(pos1.x) + abs(pos1.y));
  printf("%ld\n", abs(pos2.x) + abs(pos2.y));

  return 0;
}