random-boolean-network/random_boolean_network.c

107 lines
2.4 KiB
C
Raw Permalink Normal View History

2020-11-15 14:47:49 +01:00
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define NUM_NODES 80
#define NUM_CONNECTIONS 4
#define NUM_GENERATIONS 250
#define TRUTH_TABLE_SIZE (1 << NUM_CONNECTIONS)
const unsigned char CHAR_ZERO = '0';
const unsigned char CHAR_ONE = ' ';
unsigned int nodes[NUM_NODES];
unsigned int buffer[NUM_NODES];
unsigned int connections[NUM_NODES][NUM_CONNECTIONS];
unsigned int truth_table[TRUTH_TABLE_SIZE];
void randomize_boolean_array(unsigned int *arr, unsigned int length);
void randomize_connections();
void propagate();
void print_truth_table();
void print_connections();
void print_generation(unsigned int g);
int main(void)
{
srand(time(NULL));
randomize_boolean_array(nodes, NUM_NODES);
randomize_boolean_array(truth_table, TRUTH_TABLE_SIZE);
randomize_connections();
print_truth_table();
print_connections();
print_generation(0);
for (unsigned int i = 1; i < NUM_GENERATIONS; i++) {
propagate();
print_generation(i);
}
return 0;
}
void propagate()
{
unsigned int i, j, tt_index;
memcpy(buffer, nodes, NUM_NODES * sizeof(unsigned int));
for (i = 0; i < NUM_NODES; i++) {
tt_index = 0;
for (j = 0; j < NUM_CONNECTIONS; j++) {
tt_index += buffer[connections[i][j]] << (NUM_CONNECTIONS - 1 - j);
}
nodes[i] = truth_table[tt_index];
}
}
void randomize_boolean_array(unsigned int *arr, unsigned int length)
{
for (unsigned int i = 0; i < length; i++) {
arr[i] = rand() % 2;
}
}
void randomize_connections()
{
unsigned int i, j;
for (i = 0; i < NUM_NODES; i++) {
for (j = 0; j < NUM_CONNECTIONS; j++) {
connections[i][j] = rand() % 20;
}
}
}
void print_truth_table()
{
unsigned int i;
printf("Truth table:\n");
for (i = 0; i < TRUTH_TABLE_SIZE; i++) {
printf("[%3d] => [%d]\n", i, truth_table[i]);
}
}
void print_connections()
{
unsigned int i, j;
printf("Connections:\n");
for (i = 0; i < NUM_NODES; i++) {
printf("[%3d] => [", i);
for (j = 0; j < NUM_CONNECTIONS; j++) {
printf("%d, ", connections[i][j]);
}
printf("]\n");
}
}
void print_generation(unsigned int g)
{
unsigned int i;
printf("G%5d ", g);
for (i = 0; i < NUM_NODES; i++) {
printf("%c ", nodes[i] == 0 ? CHAR_ZERO : CHAR_ONE);
}
printf("\n");
}