Jump to content

Topswops: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 42:
{{trans|Python:_Faster_Version}}
 
<langsyntaxhighlight lang="11l">V best = [0] * 16
 
F try_swaps(&deck, f, =s, d, n)
Line 83:
 
L(i) 1..12
print(‘#2: #.’.format(i, topswops(i)))</langsyntaxhighlight>
 
{{out}}
Line 103:
=={{header|360 Assembly}}==
The program uses two ASSIST macro (XDECO,XPRNT) to keep the code as short as possible.
<langsyntaxhighlight lang="360asm">* Topswops optimized 12/07/2016
TOPSWOPS CSECT
USING TOPSWOPS,R13 base register
Line 223:
BR R14 ---------------}-----------------------------------
YREGS
END TOPSWOPS</langsyntaxhighlight>
{{out}}
<pre>
Line 241:
This is a straightforward approach that counts the number of swaps for each permutation. To generate all permutations over 1 .. N, for each of N in 1 .. 10, the package Generic_Perm from the Permutations task is used [[http://rosettacode.org/wiki/Permutations#The_generic_package_Generic_Perm]].
 
<langsyntaxhighlight Adalang="ada">with Ada.Integer_Text_IO, Generic_Perm;
 
procedure Topswaps is
Line 279:
Ada.Integer_Text_IO.Put(Item => Topswaps(I), Width => 3);
end loop;
end Topswaps;</langsyntaxhighlight>
 
{{out}}<pre> 0 1 2 4 7 10 16 22 30 38</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Topswops(Obj, n){
R := []
for i, val in obj{
Line 295:
R[A_Index]:= A_LoopField
return R
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">Cards := [2, 4, 1, 3]
Res := Print(Cards)
while (Cards[1]<>1)
Line 309:
Res .= (A_Index=1?"":"`t") val
return Trim(Res,"`n")
}</langsyntaxhighlight>
Outputs:<pre>2 4 1 3
4 2 1 3
Line 318:
=={{header|C}}==
An algorithm that doesn't go through all permutations, per Knuth tAoCP 7.2.1.2 exercise 107 (possible bad implementation on my part notwithstanding):
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <string.h>
 
Line 362:
 
return 0;
}</langsyntaxhighlight>
The code contains critical small loops, which can be manually unrolled for those with OCD. POSIX thread support is useful if you got more than one CPUs.
<langsyntaxhighlight lang="c">#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
Line 479:
return 0;
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <vector>
Line 507:
}
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 525:
http://rosettacode.org/wiki/Permutations#Faster_Lazy_Version
{{trans|Haskell}}
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, permutations2;
 
int topswops(in int n) pure @safe {
Line 539:
foreach (immutable i; 1 .. 11)
writeln(i, ": ", i.topswops);
}</langsyntaxhighlight>
{{out}}
<pre>1: 0
Line 554:
===D: Faster Version===
{{trans|C}}
<langsyntaxhighlight lang="d">import std.stdio, std.typecons;
 
__gshared uint[32] best;
Line 605:
foreach (immutable i; staticIota!(1, 14))
writefln("%2d: %d", i, topswops!i());
}</langsyntaxhighlight>
{{out}}
<pre> 1: 0
Line 623:
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
TOPSWOPS
Line 735:
 
end
</syntaxhighlight>
</lang>
Test:
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 759:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 776:
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule Topswops do
def get_1_first( [1 | _t] ), do: 0
def get_1_first( list ), do: 1 + get_1_first( swap(list) )
Line 799:
end
 
Topswops.task</langsyntaxhighlight>
 
{{out}}
Line 818:
=={{header|Erlang}}==
This code is using the [[Permutations | permutation]] code by someone else. Thank you.
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( topswops ).
 
Line 840:
 
get_1_first_many( N_permutations ) -> [get_1_first(X) || X <- N_permutations].
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 858:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: formatting kernel math math.combinatorics math.order
math.ranges sequences ;
FROM: sequences.private => exchange-unsafe ;
Line 883:
10 [1,b] [ dup topswops "%2d: %2d\n" printf ] each ;
 
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>
Line 899:
 
=={{header|Fortran}}==
<langsyntaxhighlight Fortranlang="fortran">module top
implicit none
contains
Line 955:
end do
end program
</syntaxhighlight>
</lang>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">// Adapted from http://www-cs-faculty.stanford.edu/~uno/programs/topswops.w
// at Donald Knuth's web site. Algorithm credited there to Pepperdine
// and referenced to Mathematical Gazette 73 (1989), 131-133.
Line 1,012:
}
return m
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,029:
=={{header|Haskell}}==
====Searching permutations====
<langsyntaxhighlight Haskelllang="haskell">import Data.List (permutations)
 
topswops :: Int -> Int
Line 1,040:
 
main =
mapM_ (putStrLn . ((++) <$> show <*> (":\t" ++) . show . topswops)) [1 .. 10]</langsyntaxhighlight>
{{out}}
<pre>1: 0
Line 1,056:
'''Alternate version'''
<br>Uses only permutations with all elements out of place.
<langsyntaxhighlight Haskelllang="haskell">import Data.List (permutations, inits)
import Control.Arrow (first)
 
Line 1,075:
 
main :: IO ()
main = mapM_ print $ take 10 $ topSwops [1 ..]</langsyntaxhighlight>
'''Output'''
<pre>(1,0)
Line 1,093:
build the original list of 1..n values.
 
<langsyntaxhighlight lang="unicon">procedure main()
every n := 1 to 10 do {
ts := 0
Line 1,113:
if *A <= 1 then return A
suspend [(A[1]<->A[i := 1 to *A])] ||| permute(A[2:0])
end</langsyntaxhighlight>
 
Sample run:
Line 1,132:
 
=={{header|J}}==
'''Solution''':<langsyntaxhighlight lang="j"> swops =: ((|.@:{. , }.)~ {.)^:a:</langsyntaxhighlight>
'''Example''' (''from task introduction''):<langsyntaxhighlight lang="j"> swops 2 4 1 3
2 4 1 3
4 2 1 3
3 1 2 4
2 1 3 4
1 2 3 4</langsyntaxhighlight>
'''Example''' (''topswops of all permutations of the integers 1..10''):<langsyntaxhighlight lang="j"> (,. _1 + ! >./@:(#@swops@A. >:)&i. ])&> 1+i.10
1 0
2 1
Line 1,149:
8 22
9 30
10 38</langsyntaxhighlight>
'''Notes''': Readers less familiar with array-oriented programming may find [[Talk:Topswops#Alternate_J_solution|an alternate solution]] written in the structured programming style more accessible.
 
=={{header|Java}}==
{{trans|D}}
<langsyntaxhighlight lang="java">public class Topswops {
static final int maxBest = 32;
static int[] best;
Line 1,200:
System.out.println(i + ": " + topswops(i));
}
}</langsyntaxhighlight>
{{out}}
<pre>1: 0
Line 1,217:
 
'''Infrastructure:'''
<langsyntaxhighlight lang="jq"># "while" as defined here is included in recent versions (>1.4) of jq:
def until(cond; next):
def _until:
Line 1,236:
else
. as $n | ($n-1) | permutations | [$n-1, .] | insert
end;</langsyntaxhighlight>
'''Topswops:'''
<langsyntaxhighlight lang="jq"># Input: a permutation; output: an integer
def flips:
# state: [i, array]
Line 1,250:
def fannkuch:
reduce permutations as $p
(0; [., ($p|flips) ] | max);</langsyntaxhighlight>
 
'''Example:'''
<langsyntaxhighlight lang="jq">range(1; 11) | [., fannkuch ]</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -n -c -f topswops.jq
[1,0]
[2,1]
Line 1,265:
[8,22]
[9,30]
[10,38]</langsyntaxhighlight>
 
=={{header|Julia}}==
Fast, efficient version
<langsyntaxhighlight lang="julia">function fannkuch(n)
n == 1 && return 0
n == 2 && return 1
Line 1,333:
end
end
end</langsyntaxhighlight>
{{out}}
<pre>julia> function main()
Line 1,358:
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">// version 1.1.2
 
val best = IntArray(32)
Line 1,392:
fun main(args: Array<String>) {
for (i in 1..10) println("${"%2d".format(i)} : ${topswops(i)}")
}</langsyntaxhighlight>
 
{{out}}
Line 1,409:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">-- Return an iterator to produce every permutation of list
function permute (list)
local function perm (list, n)
Line 1,451:
-- Main procedure
for i = 1, 10 do print(i, topswops(i)) end</langsyntaxhighlight>
{{out}}
<pre>1 0
Line 1,466:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
An exhaustive search of all possible permutations is done
<langsyntaxhighlight Mathematicalang="mathematica">flip[a_] := Block[{a1 = First@a}, If[a1 == Length@a, Reverse[a], Join[Reverse[a[[;; a1]]], a[[a1 + 1 ;;]]]]]
swaps[a_] := Length@FixedPointList[flip, a] - 2
Print[#, ": ", Max[swaps /@ Permutations[Range@#]]] & /@ Range[10];</langsyntaxhighlight>
{{out}}
<pre>1: 0
Line 1,483:
=={{header|Nim}}==
{{trans|Java}}
<langsyntaxhighlight lang="nim">import strformat
 
const maxBest = 32
Line 1,522:
 
for i in 1..10:
echo &"{i:2}: {topswops(i):2}"</langsyntaxhighlight>
{{out}}
<pre>
Line 1,539:
=={{header|PARI/GP}}==
Naive solution:
<langsyntaxhighlight lang="parigp">flip(v:vec)={
my(t=v[1]+1);
if (t==2, return(0));
Line 1,552:
mx;
}
vector(10,n,topswops(n))</langsyntaxhighlight>
{{out}}
<pre>%1 = [0, 1, 2, 4, 7, 10, 16, 22, 30, 38]</pre>
Line 1,560:
=={{header|Perl}}==
Recursive backtracking solution, starting with the final state and going backwards.
<langsyntaxhighlight lang="perl">
sub next_swop {
my( $max, $level, $p, $d ) = @_;
Line 1,596:
 
printf "Maximum swops for %2d cards: %2d\n", $_, topswops $_ for 1..10;
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,614:
=={{header|Phix}}==
Originally contributed by Jason Gade as part of the Euphoria version of the Great Computer Language Shootout benchmarks.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">fannkuch</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
Line 1,656:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,674:
 
=={{header|Picat}}==
<langsyntaxhighlight Picatlang="picat">go ?=>
member(N,1..10),
Perm = 1..N,
Line 1,725:
S := S + 1
end
end.</langsyntaxhighlight>
 
{{out}}
Line 1,741:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de fannkuch (N)
(let (Lst (range 1 N) L Lst Max)
(recur (L) # Permute
Line 1,755:
 
(for I 10
(println I (fannkuch I)) )</langsyntaxhighlight>
Output:
<pre>1 0
Line 1,770:
=={{header|PL/I}}==
{{incorrect|PL/I|Shown output is incorrect at the very least.}}
<syntaxhighlight lang="pl/i">
<lang PL/I>
(subscriptrange):
topswap: procedure options (main); /* 12 November 2013 */
Line 1,803:
end;
end topswap;
</syntaxhighlight>
</lang>
<pre>
1: 1
Line 1,818:
 
=={{header|Potion}}==
<langsyntaxhighlight lang="potion">range = (a, b):
i = 0, l = list(b-a+1)
while (a + i <= b):
Line 1,872:
if (n<1): n=10.
fannkuch(n)
</syntaxhighlight>
</lang>
 
Output follows that of Raku and Python, ~2.5x faster than perl5
Line 1,878:
=={{header|Python}}==
This solution uses cards numbered from 0..n-1 and variable p0 is introduced as a speed optimisation
<langsyntaxhighlight lang="python">>>> from itertools import permutations
>>> def f1(p):
i = 0
Line 1,903:
9 30
10 38
>>> </langsyntaxhighlight>
 
===Python: Faster Version===
{{trans|C}}
<langsyntaxhighlight lang="python">try:
import psyco
psyco.full()
Line 1,952:
 
for i in xrange(1, 13):
print "%2d: %d" % (i, topswops(i))</langsyntaxhighlight>
{{out}}
<pre> 1: 0
Line 1,969:
=={{header|R}}==
Using iterpc package for optimization
<syntaxhighlight lang="r">
<lang R>
topswops <- function(x){
i <- 0
Line 1,995:
result <- rbind(result, c(i, max(A$flips)))
}
</syntaxhighlight>
</lang>
 
Output:
Line 2,015:
Simple search, only "optimization" is to consider only all-misplaced permutations (as in the alternative Haskell solution), which shaves off around 2 seconds (from ~5).
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 2,033:
 
(for ([i (in-range 1 11)]) (printf "~a\t~a\n" i (topswops i)))
</syntaxhighlight>
</lang>
 
Output:
Line 2,051:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>sub swops(@a is copy) {
my int $count = 0;
until @a[0] == 1 {
Line 2,062:
sub topswops($n) { max (1..$n).permutations.race.map: &swops }
 
say "$_ {topswops $_}" for 1 .. 10;</langsyntaxhighlight>
{{Out}}
<pre>1 0
Line 2,077:
Alternately, using string manipulation instead. Much faster, though honestly, still not very fast.
 
<syntaxhighlight lang="raku" perl6line>sub swops($a is copy) {
my int $count = 0;
while (my \l = $a.ord) > 1 {
Line 2,088:
sub topswops($n) { max (1..$n).permutations.map: { .chrs.join.&swops } }
 
say "$_ {topswops $_}" for 1 .. 10;</langsyntaxhighlight>
 
Same output
Line 2,095:
The &nbsp; '''decks''' &nbsp; function is a modified permSets (permutation sets) subroutine,
<br>and is optimized somewhat to take advantage by eliminating one-swop "decks".
<langsyntaxhighlight lang="rexx">/*REXX program generates N decks of numbered cards and finds the maximum "swops". */
parse arg things .; if things=='' then things= 10
 
Line 2,132:
end /*h*/
z= reverse( subword(z, 1, t) ) subword(z, t + 1)
end /*u*/</langsyntaxhighlight>
Some older REXXes don't have a &nbsp; '''changestr''' &nbsp; BIF, &nbsp; so one is included here &nbsp; ───► &nbsp; [[CHANGESTR.REX]].
Line 2,151:
=={{header|Ruby}}==
{{trans|Python}}
<langsyntaxhighlight lang="ruby">def f1(a)
i = 0
while (a0 = a[0]) > 1
Line 2,166:
for n in 1..10
puts "%2d : %d" % [n, fannkuch(n)]
end</langsyntaxhighlight>
 
{{out}}
Line 2,184:
'''Faster Version'''
{{trans|Java}}
<langsyntaxhighlight lang="ruby">def try_swaps(deck, f, d, n)
@best[n] = d if d > @best[n]
(n-1).downto(0) do |i|
Line 2,214:
for i in 1..10
puts "%2d : %d" % [i, topswops(i)]
end</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
use itertools::Itertools;
 
Line 2,250:
(1_usize..=10).for_each(|x| println!("{}: {}", x, topswops(x)));
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,266:
 
=={{header|Scala}}==
{{libheader|Scala}}<langsyntaxhighlight Scalalang="scala">object Fannkuch extends App {
 
def fannkuchen(l: List[Int], n: Int, i: Int, acc: Int): Int = {
Line 2,297:
assert(result == Vector((1, 0), (2, 1), (3, 2), (4, 4), (5, 7), (6, 10), (7, 16), (8, 22), (9, 30), (10, 38)), "Bad results")
println(s"Successfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]")
}</langsyntaxhighlight>{{out}}
Computing results...
Pfannkuchen(1) = 0
Line 2,315:
=={{header|Tcl}}==
{{tcllib|struct::list}}<!-- Note that struct::list 1.8.1 (and probably earlier too) has a bug which makes this code hang when computing topswops(10). -->Probably an integer overflow at n=10.
<langsyntaxhighlight lang="tcl">package require struct::list
 
proc swap {listVar} {
Line 2,348:
}
}
topswopsTo 10</langsyntaxhighlight>{{out}}
n topswops(n)
1 0
Line 2,364:
{{trans|Go}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight lang="ecmascript">import "/fmt" for Fmt
 
var maxn = 10
Line 2,413:
}
 
for (i in 1..maxn) Fmt.print("$2d: $d", i, steps.call(i))</langsyntaxhighlight>
 
{{out}}
Line 2,430:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code ChOut=8, CrLf=9, IntOut=11;
int N, Max, Card1(16), Card2(16);
 
Line 2,466:
IntOut(0, N); ChOut(0, ^ ); IntOut(0, Max); CrLf(0);
];
]</langsyntaxhighlight>
 
{{out}}
Line 2,485:
{{trans|C}}
 
<langsyntaxhighlight XPL0lang="xpl0">code CrLf=9, IntOut=11, Text=12;
int N, D, Best(16);
Line 2,520:
IntOut(0, N); Text(0, ": "); IntOut(0, Best(N)); CrLf(0);
];
]</langsyntaxhighlight>
 
{{out}}
Line 2,542:
{{trans|D}}
Slow version
<langsyntaxhighlight lang="zkl">fcn topswops(n){
flip:=fcn(xa){
if (not xa[0]) return(0);
Line 2,551:
}
 
foreach n in ([1 .. 10]){ println(n, ": ", topswops(n)) }</langsyntaxhighlight>
{{out}}
<pre>
10,333

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.