)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

Find a String Naive Hill Climbing

  1. const target = 'snippetzone'.split``;
  2. const leng = target.length;
  3. const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split``;
  4.  
  5. function randomString() {
  6.   let str = [];
  7.   for (let i = 0; i < leng; i++) {
  8.     str.push(randomChar());
  9.   }
  10.   return str;
  11. }
  12.  
  13. function randomChar() {
  14.   return alphabet[Math.floor(Math.random() * alphabet.length)];
  15. }
  16.  
  17. let iterations = 0;
  18. const search = randomString();
  19. const indices = [];
  20. for (var i = 0; i < leng; i++) indices.push(i);
  21. let found = false;
  22.  
  23. function loop() {
  24.   for (let i = 0; i < 10; i++) {
  25.     if (indices.length > 0) {
  26.       let ii = Math.floor(Math.random() * indices.length);
  27.       let index = indices[ii];
  28.       search[index] = randomChar();
  29.       if (search[index] == target[index]) {
  30.         indices.splice(ii, 1);
  31.       }
  32.       console.log(search.join(','));
  33.       iterations++;
  34.     } else {
  35.       console.log('found after', iterations, 'iterations');
  36.       found = true;
  37.       break;
  38.     }
  39.   }
  40.  
  41.   if (!found) {
  42.     requestAnimationFrame(loop);
  43.   }
  44. }
  45. 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
snippet.zone ~ 2021-24 /// {s/z}