Hill Climbing

var target:Array = ("actionsnippet").split("");
var leng:int=target.length;
var iterations:int = 0;

var alphabet:Array = ("abcdefghijklmnopqrstuvwxyz").split("");
var search:Array = randomString();
var indices:Array = new Array();
for (var i:int = 0; i<leng; i++) indices.push(i);

addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	for (var i:int = 0; i<10; i++){
		if (indices.length > 0){
		   var ii:int = int(Math.random()*indices.length);
		   var index:int = indices[ii];
		 
		   search[index] = randomChar();
		   
		   if (search[index] == target[index]){
			   indices.splice(ii,1);   
		   }
		   trace(search);
		   iterations++;
		}else{
			trace("found after "+iterations+" iterations");
			removeEventListener(Event.ENTER_FRAME, onLoop);
			break;
		}
	}
}
function randomChar():String { return alphabet[int(Math.random()*alphabet.length)]; };
function randomString():Array {
	var str:Array = new Array();
	for (var i:int = 0; i<leng; i++) {
		str.push(randomChar());
	}
	return str;
}

A little random hill climbing…

Here are the last few iterations… lowest number of iterations I noticed was round 250…

....
j,c,t,i,o,n,s,n,i,p,p,e,t
y,c,t,i,o,n,s,n,i,p,p,e,t
s,c,t,i,o,n,s,n,i,p,p,e,t
w,c,t,i,o,n,s,n,i,p,p,e,t
e,c,t,i,o,n,s,n,i,p,p,e,t
j,c,t,i,o,n,s,n,i,p,p,e,t
z,c,t,i,o,n,s,n,i,p,p,e,t
l,c,t,i,o,n,s,n,i,p,p,e,t
f,c,t,i,o,n,s,n,i,p,p,e,t
a,c,t,i,o,n,s,n,i,p,p,e,t
found after 361 iterations

5 comments

  1. This is great! It really shows me where to expand my blog. I think that sometime in the future I might try to write a book to go along with my blog, but we will see…Good post with useful tips and ideas

  2. I was thinking about about having a “submit snippet” page… if I think the snippet is good I would post it with full credit….. something about that idea doesn’t seem fully realized.

    Another idea was to have a page that people could just freely post code snippets of any length… I think I might like that one better…

    Do you have something specific in mind?

  3. Excellently written article, if only all bloggers offered the same content as you, the internet would be a much better place. Please keep it up!

Leave a Reply

Your email address will not be published. Required fields are marked *