aboutsummaryrefslogtreecommitdiff
path: root/day18/day18.c
blob: 180cd1e466e22688446d9db46f916ccf51c9d89e (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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <stdio.h>
#include <stdlib.h>

#define ROWS 100
#define COLS 100

void new(int*** a) {
  int i;
  *a = (int**) malloc(ROWS * sizeof(int*));
  for(i=0; i<ROWS; i++)
    (*a)[i] = (int*) malloc(COLS * sizeof(int));
}

void delete(int** a) {
  int i;
  for(i=0; i<ROWS; i++)
    free(a[i]);
  free(a);
}

void copy(int** src, int** dst) {
  int i, j;
  for(i=0; i<ROWS; i++)
    for(j=0; j<COLS; j++)
      dst[i][j] = src[i][j];
}

void readinto(int** a) {
  int i, j, ch;
  for(i=0; i<ROWS; i++) {
    for(j=0; j<COLS; j++) {
      ch = getchar();
      switch(ch) {
        case '.': a[i][j] = 0; break;
        case '#': a[i][j] = 1;
      }
    }
    getchar(); // '\n'
  }
}

int ncount(int** a, int r, int c) {
  int n = 0, i, j;

  for(i=-1; i<2; i++)
    for(j=-1; j<2; j++)
      if((r+i)>=0 && (r+i)<ROWS && (c+j)>=0 && (c+j)<COLS && !(i == 0 && j == 0))
        n += a[r+i][c+j];

  return n;
}

void step(int** old, int** new) {
  int i, j, c;

  for(i=0; i<ROWS; i++)
    for(j=0; j<COLS; j++) {
      c = ncount(old, i, j);
      if(old[i][j]) {
        if(c == 2 || c == 3) new[i][j] = 1;
        else                 new[i][j] = 0;
      } else {
        if(c == 3) new[i][j] = 1;
        else       new[i][j] = 0;
      }
    }
}

void corners(int** a) {
  a[0][0] = a[ROWS-1][0] = a[0][COLS-1] = a[ROWS-1][COLS-1] = 1;
}

int numlights(int** a) {
  int n = 0, i, j;

  for(i=0; i<ROWS; i++)
    for(j=0; j<COLS; j++)
      n += a[i][j];

  return n;
}

int main() {
  int i, **input, **this, **that;

  new(&input);
  new(&this);
  new(&that);

  readinto(input);

  copy(input, this);
  for(i=0; i<50; i++) {
    step(this, that);
    step(that, this);
  }
  printf("Number of lights: %d\n", numlights(this));

  copy(input, this);
  corners(this);
  for(i=0; i<50; i++) {
    step(this, that);
    corners(that);
    step(that, this);
    corners(this);
  }
  printf("Number of lights: %d\n", numlights(this));

  delete(input);
  delete(this);
  delete(that);
  return 0;
}