Find a String Naive Hill Climbing
const target = 'snippetzone'.split``;
const leng = target.length;
const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split``;
function randomString() {
let str = [];
for (let i = 0; i < leng; i++) {
str.push(randomChar());
}
return str;
}
function randomChar() {
return alphabet[Math.floor(Math.random() * alphabet.length)];
}
let iterations = 0;
const search = randomString();
const indices = [];
for (var i = 0; i < leng; i++) indices.push(i);
let found = false;
function loop() {
for (let i = 0; i < 10; i++) {
if (indices.length > 0) {
let ii = Math.floor(Math.random() * indices.length);
let index = indices[ii];
search[index] = randomChar();
if (search[index] == target[index]) {
indices.splice(ii, 1);
}
console.log(search.join(','));
iterations++;
} else {
console.log('found after', iterations, 'iterations');
found = true;
break;
}
}
if (!found) {
requestAnimationFrame(loop);
}
}
loop();
This is a port of an old snippet of mine. It naively and randomly finds a target string. In this case the string “snippetzone”.
It’s fun to see it randomly perform better/worse…
e,f,k,w,q,s,o,h,n,r,f
e,f,k,w,q,s,o,h,n,r,u
k,f,k,w,q,s,o,h,n,r,u
k,f,k,w,q,o,o,h,n,r,u
k,f,k,w,q,o,o,v,n,r,u
k,f,k,w,q,v,o,v,n,r,u
...
s,e,i,p,p,e,t,z,o,n,e
s,v,i,p,p,e,t,z,o,n,e
s,h,i,p,p,e,t,z,o,n,e
s,d,i,p,p,e,t,z,o,n,e
s,s,i,p,p,e,t,z,o,n,e
s,e,i,p,p,e,t,z,o,n,e
s,g,i,p,p,e,t,z,o,n,e
s,q,i,p,p,e,t,z,o,n,e
s,m,i,p,p,e,t,z,o,n,e
s,w,i,p,p,e,t,z,o,n,e
s,g,i,p,p,e,t,z,o,n,e
s,x,i,p,p,e,t,z,o,n,e
s,t,i,p,p,e,t,z,o,n,e
s,o,i,p,p,e,t,z,o,n,e
s,e,i,p,p,e,t,z,o,n,e
s,k,i,p,p,e,t,z,o,n,e
s,p,i,p,p,e,t,z,o,n,e
s,b,i,p,p,e,t,z,o,n,e
s,n,i,p,p,e,t,z,o,n,e
found after 176 iterations