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