RBN

by Ehsan Ziya

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.min.js"></script>

JavaScript

// n randomly connected nodes
// k number of inputs for each node - chosen randomly

// n number of nodes
// k number of inputs per node

// choose a random rule for every node

function Node(k, rule) {
    this.state = 1;
    this.inputs = [];
    this.rule = rule;
    this.k = k;
}

Node.prototype.update = function () {
    this.state = this.rule(this.inputs);
};

Node.prototype.connect = function (nodes) {
    for (var i = 0; i < this.k; i++) {
        this.inputs[i] = nodes[Math.floor(Math.random() * nodes.length)];
    }
};

var rule1 = function (inputs) {
    var states = _(inputs).pluck('state').value();

    var exists = _.includes(states, 0);
   
    return exists ? 1 : 0;
};

var rule2 = function (inputs) {
    var states = _(inputs).pluck('state').value();
    var ones = _.filter(states, function(state){
        return state === 1;
    });

    return ones.length > 2 ? 1 : 0;
};

var nodes = [];
var rules = [rule1, rule2];

for (var i = 0; i < 20; i++) {
    var randomRule = rules[Math.floor(Math.random() * rules.length)];
    nodes[i] = new Node(3, randomRule);
}

nodes.forEach(function (node) {
    node.connect(nodes);
    var random = Math.random();
    node.state = random > 0.5 ? 1 : 0;
});

var round = 0;

console.log('initial state', _(nodes).pluck('state').value());
var interval = setInterval(function () {
    console.log('changed state', _(nodes).pluck('state').value());
    if (_(nodes).pluck('state').uniq().value().length > 1) {  
        round++;
        nodes.forEach(function (node) {
            node.update();
        });
    } else {
        console.log('fiished', round);
        window.clearInterval(interval);
    }
}, 300);