Block Permutation

HTML

<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
<body>
  <button id="startbutton">START</button>
</body>

JavaScript

document.getElementById("startbutton").onclick = function() {

  // This Array is about to get permuted
  var permuteThisArr = ["1", "2", "3", "4", "5"];

  // Start time
  var beginTime = performance.now();

  // Start permutation
  var resultArr = arrBlockPermute(permuteThisArr);

  // thetime?
  console.log(resultArr.length + " permutations in " + (performance.now() - beginTime));

  // If you like to see the result.. (do this with 5 Elements in permuteThisArr)
   for (var i=0, l=resultArr.length; i<l; i++) console.log(resultArr[i].join(","));

}

function arrBlockPermute(startArr) {
  var startArrLen = startArr.length;
  
  if (startArrLen > 1) {

		// 1.) something to start with :)
    var arr = [ [startArr[0], startArr[1]], [startArr[1], startArr[0]] ];

		// 2.) loop through startArr
    for (var i = 2; i < startArrLen; i++) {
			var arrLen = arr.length;
      
      // 2.1) append arr i times to itself			
    	var counter = i;
    	while (counter--) {
      	var j = arrLen +1;
      	while (--j) {
        	arr.push(arr[arrLen-j].slice(0));
      	}
   	  }
      
      // 2.2) loop through arr and insert startArr[i] in each row
      var row = arr.length;
      var col = 0;
      while (row--) {
        arr[row].splice(col, 0, startArr[i]);
        if (row % arrLen == 0) col++;
      }
    }
    // 3.) we're done ^.^
    // in case you'd like to discard all reversed doubles, uncomment this:
    // var len = arr.length / 2;
    // arr.splice(len, len);
    return arr; 
  }
  else {
    return startArr;
  }
}



// speeeeeeeed ?
window.performance = window.performance || {};
performance.now = (function() {
  return performance.now ||
    performance.mozNow ||
    performance.msNow ||
    performance.oNow ||
    performance.webkitNow ||
    function() {
      return new Date().getTime();
    };
})();