aboutsummaryrefslogtreecommitdiff
path: root/src/2017/day16/aoc.cpp
blob: bf722bdb1dfb852c07c38a9c6a2c25f03efd838a (plain)
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
#include "aoc.h"

namespace aoc2017 {

static int pos(char cs[16], char c) {
  for (int i = 0; i < 16; i++) {
    if (cs[i] == c)
      return i;
  }
  return 16;
}

static void spin(char cs[16], int x) {
  x %= 16;
  char ts[16] = {0};
  memcpy(ts + x, cs, 16 - x);
  memcpy(ts, cs + 16 - x, x);
  memcpy(cs, ts, 16);
}

static void exchange(char cs[16], int x, int y) { std::swap(cs[x], cs[y]); }
static void partner(char cs[16], char c1, char c2) { exchange(cs, pos(cs, c1), pos(cs, c2)); }
static void get_number(const char** pp, int* d) {
  const char* p = *pp;
  while (*p >= '0' && *p <= '9') {
    *d = *d * 10 + *p - '0';
    p++;
  }
  *pp = p;
}

// static void print(char cs[16]) {
//   for (int i = 0; i < 16; i++) {
//     printf("%c", cs[i]);
//   }
//   printf("\n");
// }

static void dance(char cs[16], line_view file) {
  const char* p0 = file.line;
  const char* p1 = p0;

  while (p1 < file.line + file.length) {
    if (*p1 == ',' || *p1 == '\n') {
      switch (*p0) {
      case 's': {
        int d = 0;
        p0 += 1;
        get_number(&p0, &d);
        spin(cs, d);
        break;
      }
      case 'x': {
        int ds[2] = {0, 0};
        p0 += 1;
        get_number(&p0, &ds[0]);
        p0 += 1;
        get_number(&p0, &ds[1]);
        exchange(cs, ds[0], ds[1]);
        break;
      }
      case 'p':
        partner(cs, *(p0 + 1), *(p0 + 3));
        break;
      default:
        break;
      }
      p0 = p1 + 1;
    }
    p1++;
  }
}

std::pair<int64_t, int64_t> day16(line_view file) {
  const char* s = "abcdefghijklmnop";
  char cs[16] = {0};

  for (int i = 0; i < 16; i++) {
    cs[i] = *(s + i);
  }
  size_t billion = 1000000000;
  billion %= 60;
  while (billion-- > 0) {
    dance(cs, file);
    // print(cs);
  }
  return {0, 0};
}
} // namespace aoc2017