1 /* The Great Computer Language Shootout 2 http://shootout.alioth.debian.org/ 3 contributed by Isaac Gouy */ 4 5 function fannkuch(n) { 6 var check = 0; 7 var perm = Array(n); 8 var perm1 = Array(n); 9 var count = Array(n); 10 var maxPerm = Array(n); 11 var maxFlipsCount = 0; 12 var m = n - 1; 13 14 for (var i = 0; i < n; i++) perm1[i] = i; 15 var r = n; 16 17 while (true) { 18 // write-out the first 30 permutations 19 if (check < 30){ 20 var s = ""; 21 for(var i=0; i<n; i++) s += (perm1[i]+1).toString(); 22 check++; 23 } 24 25 while (r != 1) { count[r - 1] = r; r--; } 26 if (!(perm1[0] == 0 || perm1[m] == m)) { 27 for (var i = 0; i < n; i++) perm[i] = perm1[i]; 28 29 var flipsCount = 0; 30 var k; 31 32 while (!((k = perm[0]) == 0)) { 33 var k2 = (k + 1) >> 1; 34 for (var i = 0; i < k2; i++) { 35 var temp = perm[i]; perm[i] = perm[k - i]; perm[k - i] = temp; 36 } 37 flipsCount++; 38 } 39 40 if (flipsCount > maxFlipsCount) { 41 maxFlipsCount = flipsCount; 42 for (var i = 0; i < n; i++) maxPerm[i] = perm1[i]; 43 } 44 } 45 46 while (true) { 47 if (r == n) return maxFlipsCount; 48 var perm0 = perm1[0]; 49 var i = 0; 50 while (i < r) { 51 var j = i + 1; 52 perm1[i] = perm1[j]; 53 i = j; 54 } 55 perm1[r] = perm0; 56 57 count[r] = count[r] - 1; 58 if (count[r] > 0) break; 59 r++; 60 } 61 } 62 } 63 64 var n = 8; 65 var ret = fannkuch(n); 66 67