fast-abelian-sandpile/sandpile_struct.c

74 lines
1.7 KiB
C

#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <inttypes.h>
#include <stdio.h>
#include <math.h>
#include "common.c"
/// This one is just to measure the cost of using a struct to store
/// together the width and the values.
typedef struct terrain {
int width;
int **cells;
} terrain;
void apply_gravity(terrain *land)
{
bool did_something;
int div;
int width = land->width;
int **terrain = land->cells;
while (1) {
did_something = false;
for (int x = 0; x < width; x++) {
for (int y = 0; y < width; y++) {
if (terrain[x][y] >= 4) {
did_something = true;
div = terrain[x][y] / 4;
terrain[x][y] %= 4;
terrain[x - 1][y] += div;
terrain[x + 1][y] += div;
terrain[x][y + 1] += div;
terrain[x][y - 1] += div;
}
}
}
if (!did_something)
return;
}
}
terrain *sandpile_new(int width)
{
terrain *land = malloc(sizeof(terrain));
int **terrain = calloc(width, sizeof(int*));
int *data = calloc(width * width, sizeof(int));
for (int i = 0; i < width; i++) {
terrain[i] = data + i * width;
}
land->width = width;
land->cells = terrain;
return land;
}
int main(int argc, char **argv)
{
args args = {0};
if (parse_args(argc, argv, &args))
return EXIT_FAILURE;
int width = sandpile_width(args.height);
terrain *land = sandpile_new(width);
land->cells[width / 2][width / 2] = args.height;
apply_gravity(land);
save_terrain(land->width, land->cells, &args);
return EXIT_SUCCESS;
}