Skip to content

Instantly share code, notes, and snippets.

@lukalot
Last active June 1, 2021 01:01
Show Gist options
  • Save lukalot/a735b5f8301cbdf5819544ca291caddb to your computer and use it in GitHub Desktop.
Save lukalot/a735b5f8301cbdf5819544ca291caddb to your computer and use it in GitHub Desktop.
One Dimensional Cellular Automata ( C Practice Project )
#include<stdio.h>
#include<stdint.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
#include<stdbool.h>
// Enables or disables random initialization
const int RANDOM_INIT = true;
// --------------- Begin code
// Converts a 3 cell (bit) neighborhood to an integer describing it's state
uint8_t getNeighborhoodValue (uint8_t w[], int index) {
unsigned char neighborhood = w[index-1]*4 + w[index]*2 + w[index+1]*1; // 4 = 100, 2 = 010, 1 = 001
return neighborhood;
}
// Replaces 1 and 0 with more visualizable characters
char* getCellChar(uint8_t c) {
if (c == 0)
return " ";
else
return "█";
}
int randFromRange(int min, int max) {
return (rand() % (max - min + 1)) + min;
}
int main (int argc, char* argv[]) {
srand(time(NULL));
// rule can be expressed as a single byte
uint8_t rule = randFromRange(0,255);
// Rows to print / loop count
const int loops = 100;
if (argc > 1)
sscanf(argv[1], "%d", &rule);
sscanf(argv[2], "%d", &loops);
printf("Generating rule %d for %d generations\n", rule, loops);
uint8_t world[100] = {};
uint8_t world_new_state[100] = {};
const int WORLD_SIZE = sizeof world / sizeof world[0];
if (RANDOM_INIT == true) {
for (int i = 0; i < sizeof world; i ++) {
world[i] = rand()%2;
}
} else {
// flip a cell
world[WORLD_SIZE-1] = 1;
}
for (int i = loops; i > 0; i--) {
// Iterate on cells
for (int j = 0; j < WORLD_SIZE; j++) {
// Display current cell
printf(getCellChar(world[j]));
// Get the outcome for the current neighborhood based on the game rule.
world_new_state[j] = (rule >> getNeighborhoodValue(world, j)) & 1;
}
// Overwrite current state with new world state
memcpy(world, world_new_state, sizeof world);
printf("\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment