JSFiddle - React, Tailwind, and code Playground
JavaScript
function print(msg) { //quick and dirty way to get data out.
document.body.innerHTML+="<br>"+msg;
}
function print_image(msg,v) { // print message and image from the vector
for (var i=0,s=""; i<v.length; i++) {
var c=Math.floor(v[i]*200+50); // expand to 0...255 and make integer
s+="<td style='background-color:rgb("+c+","+c+","+c+")'> </td>"
} //the background of the cell displays the color.
print("<table cellpadding=0><tr>"+s+"<td>"+msg+"</td></tr></table>")
}
try {
// This is the world as we have been told it exists... or...
// the pattern we are looking for in the world.
pattern = [1,1,0,1,0,1,1];
print_image("Starting pattern",pattern);
// This is what we remember about what we have seen.
memory = new Array(pattern.length);
// It starts uniformly unsure. Each cell is equally likely, total is 1
for (var i=0;i<pattern.length;i++) memory[i]=1/pattern.length;
//print(memory); //should show uniform probability, total=1
function mod(i, m) { //circular modulus is
var r = i % m; //regular modulus
if (r<0) r+=m; //with a wrap if negative
return r;
}
// Sensors arn't always totally accurate.
wHit = 0.9; //weight of a match between sensor and memory
wMiss = 0.1; //weight of a mismatch
function sense(memory, pattern, input) {
output = []; //new memory state
var s=0;
for (var i=0; i<memory.length;i++) {
var d = 1-Math.abs(pattern[i] - input); //compare pattern with input
var p = memory[i] * (d * wHit + (1-d) * wMiss); //new probabilities
output.push(p);
s += p; //sum probabilities.
}
for (var i=0;i<output.length;i++) output[i] /= s; //normalize
return output;
}
print_image("See a zero, or",sense(memory, pattern, 0))
// Robots don't alway move exactly as commanded. Wheels slip, etc...
wExactMove = 0.8; // probibility that we will move exactly 1 cell
wOvershoot = (1-wExactMove) / 2; // Remaining chance is half over...
wUndershoot = (1-wExactMove) / 2; // and half undershoot when moving.
function...