65 lines
1.4 KiB
C
65 lines
1.4 KiB
C
#include <stdlib.h>
|
|
#include <stdbool.h>
|
|
#include <string.h>
|
|
#include <inttypes.h>
|
|
#include <stdio.h>
|
|
#include <math.h>
|
|
|
|
#include "common.c"
|
|
|
|
|
|
/// This is the "dumb" implementation in C.
|
|
|
|
|
|
void apply_gravity(int width, int **terrain)
|
|
{
|
|
bool did_something;
|
|
int div;
|
|
|
|
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;
|
|
}
|
|
}
|
|
|
|
|
|
int **sandpile_new(int width)
|
|
{
|
|
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;
|
|
}
|
|
return terrain;
|
|
}
|
|
|
|
|
|
int main(int argc, char **argv)
|
|
{
|
|
args args = {0};
|
|
|
|
if (parse_args(argc, argv, &args))
|
|
return EXIT_FAILURE;
|
|
|
|
int width = sandpile_width(args.height);
|
|
int **terrain = sandpile_new(width);
|
|
terrain[width / 2][width / 2] = args.height;
|
|
apply_gravity(width, terrain);
|
|
save_terrain(width, terrain, &args);
|
|
return EXIT_SUCCESS;
|
|
}
|