Add C version (20x faster)

This commit is contained in:
Joop Schilder 2020-11-15 14:47:49 +01:00
parent f72bbfbe96
commit 915ec5c9b8
3 changed files with 112 additions and 3 deletions

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
/tags
/a.out

106
random_boolean_network.c Normal file
View File

@ -0,0 +1,106 @@
#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");
}

View File

@ -8,9 +8,9 @@
Fri 13 Nov
*/
const NUM_NODES = 20;
const NUM_CONNECTIONS = 3;
const NUM_GENERATIONS = 20;
const NUM_NODES = 80;
const NUM_CONNECTIONS = 4;
const NUM_GENERATIONS = 250;
const CHAR_ON_ZERO = '0';
const CHAR_ON_ONE = ' ';