jQuery(function($) { var baroque_tower = function(start, goal) { var queue = [], hash = {}; queue.push([0,'*',start,null]); hash[start.toString()] = 1; while (queue.length > 0) { var now = queue.shift(); for (var i = 0; i < 4; i++) { var next = []; next[2] = now[2].concat(); for (var j = 0; j < 4; j++) { if ((i+1)%4 == j) continue; next[2][j] = (next[2][j]+1)%4; } if (!hash[next[2].toString()]) { next[0] = now[0]+1; next[1] = i; next[3] = now; if (next[2].toString() == goal.toString()) return print(next); hash[next[2].toString()] = 1; queue.push(next); } } } return ''; }; var print = function(p) { var s = ''; while (p) { s = '('+p[0]+') ['+p[1]+'] '+p[2].toString()+'<br>'+s; p = p[3]; } return s; }; var s = baroque_tower([3,2,2,3],[2,3,0,1]); $('#answer').html(s); });