]> git.friedersdorff.com Git - max/gol.git/blob - array.c
Making more progress (hopefully)
[max/gol.git] / array.c
1 #include <stddef.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include "array.h"
5
6 /*
7  * Implements a linear search.
8  */
9 int gol_is_live(struct gol_board *const state, int_least32_t x, int_least32_t y)
10 {
11         for (unsigned int i = 0; i < state->n; i += 2) {
12                 if (state->live_cells[i] == x &&
13                         state->live_cells[i+1] == y) {
14                         return 1;
15                 }
16         }
17         return 0;
18 }
19
20 int gol_vivify(struct gol_board *const state, int_least32_t x, int_least32_t y)
21 {
22         int_least32_t *tmp_cells = NULL;
23         size_t tmp_size = 0;
24         if (state->n == state->size) {
25                 tmp_size = 2 * state->size;
26                 tmp_cells = malloc(tmp_size * sizeof(typeof(tmp_cells)));
27                 if (!tmp_cells) {
28                         return 1;
29                 }
30                 memcpy(tmp_cells, state->live_cells,
31                         tmp_size * sizeof(typeof(tmp_cells)));
32                 state->size = tmp_size;
33                 free(state->live_cells);
34                 state->live_cells = tmp_cells;
35         }
36
37         state->live_cells[state->n] = x;
38         state->live_cells[state->n + 1] = y;
39
40         state->n += 2;
41
42         if (x > state->max_x) {
43                 state->max_x = x;
44         } else if (x < state->min_x) {
45                 state->min_x = x;
46         }
47
48         if (y > state->max_y) {
49                 state->max_y = y;
50         } else if (y < state->min_y) {
51                 state->min_y = y;
52         }
53         return 1;
54 }