--[[1MIT License23Copyright (c) 2017 Gabriel de Quadros Ligneul45Permission is hereby granted, free of charge, to any person obtaining a copy6of this software and associated documentation files (the "Software"), to deal7in the Software without restriction, including without limitation the rights8to use, copy, modify, merge, publish, distribute, sublicense, and/or sell9copies of the Software, and to permit persons to whom the Software is10furnished to do so, subject to the following conditions:1112The above copyright notice and this permission notice shall be included in all13copies or substantial portions of the Software.1415THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR16IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,17FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE18AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER19LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,20OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE21SOFTWARE.22]]23-- The Computer Language Benchmarks Game24-- http://benchmarksgame.alioth.debian.org/25-- contributed by Mike Pall2627local function prequire(name) local success, result = pcall(require, name); return success and result end28local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../../bench_support")2930function test()3132local function fannkuch(n)33local p, q, s, sign, maxflips, sum = {}, {}, {}, 1, 0, 034for i=1,n do p[i] = i; q[i] = i; s[i] = i end35repeat36-- Copy and flip.37local q1 = p[1] -- Cache 1st element.38if q1 ~= 1 then39for i=2,n do q[i] = p[i] end -- Work on a copy.40local flips = 141repeat42local qq = q[q1]43if qq == 1 then -- ... until 1st element is 1.44sum = sum + sign*flips45if flips > maxflips then maxflips = flips end -- New maximum?46break47end48q[q1] = q149if q1 >= 4 then50local i, j = 2, q1 - 151repeat q[i], q[j] = q[j], q[i]; i = i + 1; j = j - 1; until i >= j52end53q1 = qq; flips = flips + 154until false55end56if sign == 1 then57p[2], p[1] = p[1], p[2]; sign = -1 -- Rotate 1<-2.58else59p[2], p[3] = p[3], p[2]; sign = 1 -- Rotate 1<-2 and 1<-2<-3.60for i=3,n do61local sx = s[i]62if sx ~= 1 then s[i] = sx-1; break end63if i == n then return sum, maxflips end -- Out of permutations.64s[i] = i65-- Rotate 1<-...<-i+1.66local t = p[1]; for j=1,i do p[j] = p[j+1] end; p[i+1] = t67end68end69until false70end7172local n = tonumber(arg and arg[1]) or 873local sum, flips = fannkuch(n)74print(sum, "\nPfannkuchen(", n, ") = ", flips, "\n")7576end7778bench.runCode(test, "fannkuchen-redux")798081