(phixonline)-->
with javascript_semantics
function fannkuch(integer n)
sequence count = tagset(n),
perm1 = tagset(n)
integer maxFlipsCount = 0, r = n+1
while true do
while r!=1 do
count[r-1] = r
r -= 1
end while
if not (perm1[1]=1 or perm1[n]=n) then
sequence perm = perm1
integer flipsCount = 0,
k = perm[1]
while k!=1 do
perm = reverse(perm[1..k]) & perm[k+1..n]
flipsCount += 1
k = perm[1]
end while
if flipsCount>maxFlipsCount then
maxFlipsCount = flipsCount
end if
end if
-- Use incremental change to generate another permutation
while true do
if r>n then return maxFlipsCount end if
integer perm0 = perm1[1]
perm1[1..r-1] = perm1[2..r]
perm1[r] = perm0
count[r] -= 1
if count[r]>1 then exit end if
r += 1
end while
end while
end function -- fannkuch
atom t0 = time()
for i=1 to iff(platform()=JS?9:10) do
?fannkuch(i)
end for
?elapsed(time()-t0)