Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Roblox
GitHub Repository: Roblox/luau
Path: blob/master/bench/tests/sunspider/fannkuch.lua
2727 views
1
--[[
2
The Great Computer Language Shootout
3
http://shootout.alioth.debian.org/
4
contributed by Isaac Gouy
5
]]
6
local function prequire(name) local success, result = pcall(require, name); return success and result end
7
local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../../bench_support")
8
9
function test()
10
11
local function fannkuch(n)
12
local check = 0;
13
local perm = {};
14
local perm1 = {};
15
local count = {};
16
local maxPerm = {};
17
local maxFlipsCount = 0;
18
local m = n - 1;
19
20
for i = 1,n do perm1[i] = i - 1; end
21
local r = n;
22
23
while (true) do
24
-- write-out the first 30 permutations
25
if (check < 30) then
26
local s = "";
27
for i = 1,n do s = s .. tostring(perm1[i]+1); end
28
check = check + 1;
29
end
30
31
while (r ~= 1) do count[r] = r; r = r - 1; end
32
33
if (not (perm1[1] == 0 or perm1[m + 1] == m)) then
34
for i = 1,n do perm[i] = perm1[i]; end
35
36
local flipsCount = 0;
37
local k;
38
39
k = perm[1]
40
41
while (not (k == 0)) do
42
local k2 = math.floor((k + 1) / 2);
43
for i = 0,k2-1 do
44
local temp = perm[i + 1];
45
perm[i + 1] = perm[k - i + 1];
46
perm[k - i + 1] = temp;
47
end
48
49
flipsCount = flipsCount + 1;
50
51
k = perm[1]
52
end
53
54
if (flipsCount > maxFlipsCount) then
55
maxFlipsCount = flipsCount;
56
for i = 1,n do maxPerm[i] = perm1[i]; end
57
end
58
end
59
60
while (true) do
61
if (r == n) then return maxFlipsCount; end
62
63
local perm0 = perm1[1];
64
local i = 0;
65
while (i < r) do
66
local j = i + 1;
67
perm1[i + 1] = perm1[j + 1];
68
i = j;
69
end
70
perm1[r + 1] = perm0;
71
72
count[r + 1] = count[r + 1] - 1;
73
if (count[r + 1] > 0) then break; end
74
r = r + 1;
75
end
76
end
77
78
return 0
79
end
80
81
local n = 8;
82
local ret = fannkuch(n);
83
84
local expected = 22;
85
if (ret ~= expected) then
86
assert(false, "ERROR: bad result: expected " .. expected .. " but got " .. ret);
87
end
88
89
end
90
91
bench.runCode(test, "fannkuch")
92
93