Permutations/Derangements: Difference between revisions

Content added Content deleted
(Added solution for Pascal.)
m (syntax highlighting fixup automation)
Line 32: Line 32:
{{trans|Python}}
{{trans|Python}}


<lang 11l>F derangements(n)
<syntaxhighlight lang="11l">F derangements(n)
[[Int]] r
[[Int]] r
V perm = Array(0 .< n)
V perm = Array(0 .< n)
Line 55: Line 55:


n = 20
n = 20
print("\n!#. = #.".format(n, subfact(n)))</lang>
print("\n!#. = #.".format(n, subfact(n)))</syntaxhighlight>


{{out}}
{{out}}
Line 88: Line 88:
{{trans|BBC BASIC}}
{{trans|BBC BASIC}}
Due to 32 bit integers !12 is the limit.
Due to 32 bit integers !12 is the limit.
<lang 360asm>* Permutations/Derangements 01/04/2017
<syntaxhighlight lang="360asm">* Permutations/Derangements 01/04/2017
DERANGE CSECT
DERANGE CSECT
USING DERANGE,R13 base register
USING DERANGE,R13 base register
Line 339: Line 339:
PG DC CL80' ' buffer
PG DC CL80' ' buffer
YREGS
YREGS
END DERANGE</lang>
END DERANGE</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 369: Line 369:
=={{header|Ada}}==
=={{header|Ada}}==
{{trans|C}}
{{trans|C}}
<lang Ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
procedure DePermute is
procedure DePermute is
type U64 is mod 2**64;
type U64 is mod 2**64;
Line 422: Line 422:
end loop;
end loop;
Put_Line ("!20 = " & U64'Image (sub_fact (20)));
Put_Line ("!20 = " & U64'Image (sub_fact (20)));
end DePermute;</lang>
end DePermute;</syntaxhighlight>
{{out}}
{{out}}
<pre>Deranged 4:
<pre>Deranged 4:
Line 449: Line 449:
=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>isClean?: function [s,o][
<syntaxhighlight lang="rebol">isClean?: function [s,o][
loop.with:'i s 'a [
loop.with:'i s 'a [
if a = o\[i] -> return false
if a = o\[i] -> return false
Line 481: Line 481:
]
]


print ~"\n!20 = |subfactorial 20|"</lang>
print ~"\n!20 = |subfactorial 20|"</syntaxhighlight>


{{out}}
{{out}}
Line 515: Line 515:
{{works with|AutoHotkey_L}}
{{works with|AutoHotkey_L}}
Note that the permutations are generated in lexicographic order, from http://www.autohotkey.com/forum/topic77959.html
Note that the permutations are generated in lexicographic order, from http://www.autohotkey.com/forum/topic77959.html
<lang AHK>#NoEnv
<syntaxhighlight lang="ahk">#NoEnv
SetBatchLines -1
SetBatchLines -1
Process, Priority,, high
Process, Priority,, high
Line 610: Line 610:
a *= A_Index
a *= A_Index
return a
return a
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Derangements for 1, 2, 3, 4:
<pre>Derangements for 1, 2, 3, 4:
Line 639: Line 639:
=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang BBC BASIC> PRINT"Derangements for the numbers 0,1,2,3 are:"
<syntaxhighlight lang="bbc basic"> PRINT"Derangements for the numbers 0,1,2,3 are:"
Count% = FN_Derangement_Generate(4,TRUE)
Count% = FN_Derangement_Generate(4,TRUE)
Line 713: Line 713:
REM Or you could use:
REM Or you could use:
REM DEF FN_SubFactorial(N) : IF N<1 THEN =1 ELSE =(N-1)*(FN_SubFactorial(N-1)+FN_SubFactorial(N-2))</lang>
REM DEF FN_SubFactorial(N) : IF N<1 THEN =1 ELSE =(N-1)*(FN_SubFactorial(N-1)+FN_SubFactorial(N-2))</syntaxhighlight>


{{out}}
{{out}}
Line 752: Line 752:
Also the counter <code>count</code> is a global variable.
Also the counter <code>count</code> is a global variable.
<lang bracmat>( ( calculated-!n
<syntaxhighlight lang="bracmat">( ( calculated-!n
= memo answ
= memo answ
. (memo==)
. (memo==)
Line 803: Line 803:
& out$("!20 =" calculated-!n$20)
& out$("!20 =" calculated-!n$20)
& lst$calculated-!n
& lst$calculated-!n
)</lang>
)</syntaxhighlight>
{{out}}
{{out}}
<pre>Derangements of 1 2 3 4
<pre>Derangements of 1 2 3 4
Line 862: Line 862:


=={{header|C}}==
=={{header|C}}==
<lang C>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
typedef unsigned long long LONG;
typedef unsigned long long LONG;


Line 918: Line 918:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Deranged Four:
<pre>Deranged Four:
Line 959: Line 959:
Recursive version
Recursive version


<lang csharp>
<syntaxhighlight lang="csharp">
using System;
using System;
class Derangements
class Derangements
Line 988: Line 988:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Clojure}}==
=={{header|Clojure}}==
Generating functions with no fixed point
Generating functions with no fixed point


<lang Clojure>(ns derangements.core
<syntaxhighlight lang="clojure">(ns derangements.core
(:require [clojure.set :as s]))
(:require [clojure.set :as s]))


Line 1,032: Line 1,032:
(range 10)))
(range 10)))
(println (subfactorial 20))))
(println (subfactorial 20))))
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>[1 0 3 2]
<pre>[1 0 3 2]
Line 1,057: Line 1,057:
=={{header|D}}==
=={{header|D}}==
===Iterative Version===
===Iterative Version===
<lang d>import std.stdio, std.algorithm, std.typecons, std.conv,
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.typecons, std.conv,
std.range, std.traits;
std.range, std.traits;


Line 1,121: Line 1,121:


writefln("\n!20 = %s", 20L.subfact);
writefln("\n!20 = %s", 20L.subfact);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Derangements for n = 4:
<pre>Derangements for n = 4:
Line 1,151: Line 1,151:
Slightly slower but more compact recursive version of the derangements function, based on the [[Permutations#D|D entry]] of the permutations task.
Slightly slower but more compact recursive version of the derangements function, based on the [[Permutations#D|D entry]] of the permutations task.
Same output.
Same output.
<lang d>import std.stdio, std.algorithm, std.typecons, std.conv, std.range;
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.typecons, std.conv, std.range;


T factorial(T)(in T n) pure nothrow {
T factorial(T)(in T n) pure nothrow {
Line 1,197: Line 1,197:


writefln("\n!20 = %s", 20L.subfact);
writefln("\n!20 = %s", 20L.subfact);
}</lang>
}</syntaxhighlight>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(lib 'list) ;; in-permutations
(lib 'list) ;; in-permutations
(lib 'bigint)
(lib 'bigint)
Line 1,221: Line 1,221:
(remember '!n #(1 0))
(remember '!n #(1 0))


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<lang scheme>
<syntaxhighlight lang="scheme">
(derangements 4)
(derangements 4)
→ ((3 0 1 2) (2 0 3 1) (2 3 0 1) (3 2 0 1) (3 2 1 0) (2 3 1 0) (1 2 3 0) (1 3 0 2) (1 0 3 2))
→ ((3 0 1 2) (2 0 3 1) (2 3 0 1) (3 2 0 1) (3 2 1 0) (2 3 1 0) (1 2 3 0) (1 3 0 2) (1 0 3 2))
Line 1,244: Line 1,244:
(!n 20)
(!n 20)
→ 895014631192902121
→ 895014631192902121
</syntaxhighlight>
</lang>


=={{header|Elixir}}==
=={{header|Elixir}}==
{{trans|Ruby}}
{{trans|Ruby}}
<lang elixir>defmodule Permutation do
<syntaxhighlight lang="elixir">defmodule Permutation do
def derangements(n) do
def derangements(n) do
list = Enum.to_list(1..n)
list = Enum.to_list(1..n)
Line 1,276: Line 1,276:
Enum.each(10..20, fn n ->
Enum.each(10..20, fn n ->
:io.format "~2w :~19w~n", [n, Permutation.subfact(n)]
:io.format "~2w :~19w~n", [n, Permutation.subfact(n)]
end)</lang>
end)</syntaxhighlight>


{{out}}
{{out}}
Line 1,318: Line 1,318:
=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
===The Function===
===The Function===
<lang fsharp>
<syntaxhighlight lang="fsharp">
// Generate derangements. Nigel Galloway: July 9th., 2019
// Generate derangements. Nigel Galloway: July 9th., 2019
let derange n=
let derange n=
Line 1,329: Line 1,329:
|_->()}
|_->()}
derange 0 [|1..n|] (n-1)
derange 0 [|1..n|] (n-1)
</syntaxhighlight>
</lang>
===The Task===
===The Task===
<lang fsharp>
<syntaxhighlight lang="fsharp">
derange 4 |> Seq.iter(printfn "%A")
derange 4 |> Seq.iter(printfn "%A")
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,346: Line 1,346:
[|4; 1; 2; 3|]
[|4; 1; 2; 3|]
</pre>
</pre>
<lang fsharp>
<syntaxhighlight lang="fsharp">
let subFact n=let rec fN n g=match n with 0m->int64(round(g/2.7182818284590452353602874713526624978m))|_->fN (n-1m) (g*n) in if n=0 then 1L else fN (decimal n) 1m
let subFact n=let rec fN n g=match n with 0m->int64(round(g/2.7182818284590452353602874713526624978m))|_->fN (n-1m) (g*n) in if n=0 then 1L else fN (decimal n) 1m
[1..9] |> Seq.iter(fun n->printfn "items=%d !n=%d derangements=%d" n (subFact n) (derange n|>Seq.length))
[1..9] |> Seq.iter(fun n->printfn "items=%d !n=%d derangements=%d" n (subFact n) (derange n|>Seq.length))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,365: Line 1,365:
=={{header|Factor}}==
=={{header|Factor}}==
{{works with|Factor|0.98}}
{{works with|Factor|0.98}}
<lang factor>USING: combinators formatting io kernel math math.combinatorics
<syntaxhighlight lang="factor">USING: combinators formatting io kernel math math.combinatorics
prettyprint sequences ;
prettyprint sequences ;
IN: rosetta-code.derangements
IN: rosetta-code.derangements
Line 1,386: Line 1,386:
"%d%8d%8d\n" printf
"%d%8d%8d\n" printf
] each nl
] each nl
"!20 = " write 20 !n .</lang>
"!20 = " write 20 !n .</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,419: Line 1,419:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' version 08-04-2017
<syntaxhighlight lang="freebasic">' version 08-04-2017
' compile with: fbc -s console
' compile with: fbc -s console


Line 1,512: Line 1,512:
Print : Print "hit any key to end program"
Print : Print "hit any key to end program"
Sleep
Sleep
End</lang>
End</syntaxhighlight>
{{out}}
{{out}}
<pre>permutations derangements for n = 4
<pre>permutations derangements for n = 4
Line 1,543: Line 1,543:


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap># All of this is built-in
<syntaxhighlight lang="gap"># All of this is built-in
Derangements([1 .. 4]);
Derangements([1 .. 4]);
# [ [ 2, 1, 4, 3 ], [ 2, 3, 4, 1 ], [ 2, 4, 1, 3 ], [ 3, 1, 4, 2 ], [ 3, 4, 1, 2 ], [ 3, 4, 2, 1 ],
# [ [ 2, 1, 4, 3 ], [ 2, 3, 4, 1 ], [ 2, 4, 1, 3 ], [ 3, 1, 4, 2 ], [ 3, 4, 1, 2 ], [ 3, 4, 2, 1 ],
Line 1,577: Line 1,577:
# [ 7, 1854, 1854, 1854 ],
# [ 7, 1854, 1854, 1854 ],
# [ 8, 14833, 14833, 14833 ],
# [ 8, 14833, 14833, 14833 ],
# [ 9, 133496, 133496, 133496 ] ]</lang>
# [ 9, 133496, 133496, 133496 ] ]</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,650: Line 1,650:
// stretch (sic)
// stretch (sic)
fmt.Println("\n!20 =", subFact(20))
fmt.Println("\n!20 =", subFact(20))
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,682: Line 1,682:
=={{header|Groovy}}==
=={{header|Groovy}}==
Solution:
Solution:
<lang groovy>def fact = { n -> [1,(1..<(n+1)).inject(1) { prod, i -> prod * i }].max() }
<syntaxhighlight lang="groovy">def fact = { n -> [1,(1..<(n+1)).inject(1) { prod, i -> prod * i }].max() }
def subfact
def subfact
subfact = { BigInteger n -> (n == 0) ? 1 : (n == 1) ? 0 : ((n-1) * (subfact(n-1) + subfact(n-2))) }
subfact = { BigInteger n -> (n == 0) ? 1 : (n == 1) ? 0 : ((n-1) * (subfact(n-1) + subfact(n-2))) }
Line 1,690: Line 1,690:
if (l) l.eachPermutation { p -> if ([p,l].transpose().every{ pp, ll -> pp != ll }) d << p }
if (l) l.eachPermutation { p -> if ([p,l].transpose().every{ pp, ll -> pp != ll }) d << p }
d
d
}</lang>
}</syntaxhighlight>


Test:
Test:
<lang groovy>def d = derangement([1,2,3,4])
<syntaxhighlight lang="groovy">def d = derangement([1,2,3,4])
assert d.size() == subfact(4)
assert d.size() == subfact(4)
d.each { println it }
d.each { println it }
Line 1,708: Line 1,708:
println """
println """
!20 == ${subfact(20)}
!20 == ${subfact(20)}
"""</lang>
"""</syntaxhighlight>


{{out}}
{{out}}
Line 1,738: Line 1,738:
=={{header|Haskell}}==
=={{header|Haskell}}==


<lang Haskell>import Control.Monad (forM_)
<syntaxhighlight lang="haskell">import Control.Monad (forM_)


import Data.List (permutations)
import Data.List (permutations)
Line 1,770: Line 1,770:
putStrLn ""
putStrLn ""
-- Print the number of derangements in a list of 20 items
-- Print the number of derangements in a list of 20 items
print $ subfactorial 20</lang>
print $ subfactorial 20</syntaxhighlight>
{{Out}}
{{Out}}
<pre>[[4,3,2,1],[3,4,2,1],[2,3,4,1],[4,1,2,3],[2,4,1,3],[2,1,4,3],[4,3,1,2],[3,4,1,2],[3,1,4,2]]
<pre>[[4,3,2,1],[3,4,2,1],[2,3,4,1],[4,1,2,3],[2,4,1,3],[2,1,4,3],[4,3,1,2],[3,4,1,2],[3,1,4,2]]
Line 1,788: Line 1,788:
Alternatively, this is a backtracking method:
Alternatively, this is a backtracking method:


<lang haskell>derangements xs = loop xs xs
<syntaxhighlight lang="haskell">derangements xs = loop xs xs
where loop [] [] = [[]]
where loop [] [] = [[]]
loop (h:hs) xs = [x:ys | x <- xs, x /= h, ys <- loop hs (delete x xs)]</lang>
loop (h:hs) xs = [x:ys | x <- xs, x /= h, ys <- loop hs (delete x xs)]</syntaxhighlight>


Since the value <i>i</I> cannot occur in position <i>i</i>, we prefix <i>i</i> on all other derangements from 1 to <i>n</i> that do not include <i>i</i>. The first method of filtering permutations is significantly faster, in practice, however.
Since the value <i>i</I> cannot occur in position <i>i</i>, we prefix <i>i</i> on all other derangements from 1 to <i>n</i> that do not include <i>i</i>. The first method of filtering permutations is significantly faster, in practice, however.
Line 1,797: Line 1,797:
Note: <code>!n</code> in J denotes factorial (or gamma n+1), and not subfactorial.
Note: <code>!n</code> in J denotes factorial (or gamma n+1), and not subfactorial.


<lang j>derangement=: (A.&i.~ !)~ (*/ .~: # [) i. NB. task item 1
<syntaxhighlight lang="j">derangement=: (A.&i.~ !)~ (*/ .~: # [) i. NB. task item 1
subfactorial=: ! * +/@(_1&^ % !)@i.@>: NB. task item 3</lang>
subfactorial=: ! * +/@(_1&^ % !)@i.@>: NB. task item 3</syntaxhighlight>


Requested examples:
Requested examples:


<lang j> derangement 4 NB. task item 2
<syntaxhighlight lang="j"> derangement 4 NB. task item 2
1 0 3 2
1 0 3 2
1 2 3 0
1 2 3 0
Line 1,826: Line 1,826:
8.95015e17
8.95015e17
subfactorial 20x NB. using extended precision
subfactorial 20x NB. using extended precision
895014631192902121</lang>
895014631192902121</syntaxhighlight>


Note that derangement 10 was painfully slow (almost 3 seconds, about 10 times slower than derangement 9 and 100 times slower than derangement 8) -- this is a brute force approach. But brute force seems like an appropriate solution here, since factorial divided by subfactorial asymptotically approaches a value near 0.367879 (the reciprocal of e).
Note that derangement 10 was painfully slow (almost 3 seconds, about 10 times slower than derangement 9 and 100 times slower than derangement 8) -- this is a brute force approach. But brute force seems like an appropriate solution here, since factorial divided by subfactorial asymptotically approaches a value near 0.367879 (the reciprocal of e).
Line 1,832: Line 1,832:
=={{header|Java}}==
=={{header|Java}}==
{{trans|D}}
{{trans|D}}
<lang java>import java.util.ArrayList;
<syntaxhighlight lang="java">import java.util.ArrayList;
import java.util.Arrays;
import java.util.Arrays;
import java.util.List;
import java.util.List;
Line 1,926: Line 1,926:
return r;
return r;
}
}
}</lang>
}</syntaxhighlight>


<pre>derangements for n = 4
<pre>derangements for n = 4
Line 1,958: Line 1,958:
{{works with|jq|1.4}}
{{works with|jq|1.4}}
The following implementation of "derangements" generates the derangements directly, without generating all permutations. Since recent versions of jq have tail-call optimization (TCO) for arity-0 recursive functions, the workhorse inner function (deranged/0) is implemented as an arity-0 function.
The following implementation of "derangements" generates the derangements directly, without generating all permutations. Since recent versions of jq have tail-call optimization (TCO) for arity-0 recursive functions, the workhorse inner function (deranged/0) is implemented as an arity-0 function.
<lang jq>def derangements:
<syntaxhighlight lang="jq">def derangements:


# In order to reference the original array conveniently, define _derangements(ary):
# In order to reference the original array conveniently, define _derangements(ary):
Line 1,981: Line 1,981:


# Avoid creating an array just to count the items in a stream:
# Avoid creating an array just to count the items in a stream:
def count(g): reduce g as $i (0; . + 1);</lang>
def count(g): reduce g as $i (0; . + 1);</syntaxhighlight>
'''Tasks''':
'''Tasks''':
<lang jq> "Derangements:",
<syntaxhighlight lang="jq"> "Derangements:",
([range(1;5)] | derangements),
([range(1;5)] | derangements),
"",
"",
Line 1,989: Line 1,989:
(range(1;10) as $i | "\($i): \(count( [range(0;$i)] | derangements)) vs \($i|subfact)"),
(range(1;10) as $i | "\($i): \(count( [range(0;$i)] | derangements)) vs \($i|subfact)"),
"",
"",
"Computed approximation to !20 (15 significant digits): \(20|subfact)"</lang>
"Computed approximation to !20 (15 significant digits): \(20|subfact)"</syntaxhighlight>
{{Out}}
{{Out}}
<lang sh>$ jq -n -c -r -f derangements.jq
<syntaxhighlight lang="sh">$ jq -n -c -r -f derangements.jq
jq -n -c -r -f derangements.jq
jq -n -c -r -f derangements.jq


Line 2,016: Line 2,016:
9: 133496 vs 133496
9: 133496 vs 133496


Computed approximation to !20 (15 significant digits): 895014631192902000</lang>
Computed approximation to !20 (15 significant digits): 895014631192902000</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>using Printf, Combinatorics
<syntaxhighlight lang="julia">using Printf, Combinatorics


derangements(n::Int) = (perm for perm in permutations(1:n)
derangements(n::Int) = (perm for perm in permutations(1:n)
Line 2,050: Line 2,050:
end
end


println("\n!20 = ", subfact(20))</lang>
println("\n!20 = ", subfact(20))</syntaxhighlight>


{{out}}
{{out}}
Line 2,079: Line 2,079:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2


fun <T> permute(input: List<T>): List<List<T>> {
fun <T> permute(input: List<T>): List<List<T>> {
Line 2,124: Line 2,124:
}
}
println("\n!20 = ${subFactorial(20)}")
println("\n!20 = ${subFactorial(20)}")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,157: Line 2,157:


=={{header|Lua}}==
=={{header|Lua}}==
<lang Lua>-- Return an iterator to produce every permutation of list
<syntaxhighlight lang="lua">-- Return an iterator to produce every permutation of list
function permute (list)
function permute (list)
local function perm (list, n)
local function perm (list, n)
Line 2,225: Line 2,225:
print("\t| " .. #derangements(listOneTo(i)))
print("\t| " .. #derangements(listOneTo(i)))
end
end
print("\n\nThe subfactorial of 20 is " .. subFact(20))</lang>
print("\n\nThe subfactorial of 20 is " .. subFact(20))</syntaxhighlight>
{{out}}
{{out}}
<pre>Derangements of [1,2,3,4]
<pre>Derangements of [1,2,3,4]
Line 2,258: Line 2,258:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">
<lang Mathematica>
Needs["Combinatorica`"]
Needs["Combinatorica`"]
derangements[n_] := Derangements[Range[n]]
derangements[n_] := Derangements[Range[n]]
derangements[4]
derangements[4]
Table[{NumberOfDerangements[i], Subfactorial[i]}, {i, 9}] // TableForm
Table[{NumberOfDerangements[i], Subfactorial[i]}, {i, 9}] // TableForm
Subfactorial[20]</lang>
Subfactorial[20]</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,282: Line 2,282:


=={{header|Nim}}==
=={{header|Nim}}==
<lang Nim>import algorithm, sequtils, strformat, strutils, tables
<syntaxhighlight lang="nim">import algorithm, sequtils, strformat, strutils, tables


iterator derangements[T](a: openArray[T]): seq[T] =
iterator derangements[T](a: openArray[T]): seq[T] =
Line 2,308: Line 2,308:
echo &"{n} {toSeq(derangements(toSeq(1..n))).len:>6} {!n:>6}"
echo &"{n} {toSeq(derangements(toSeq(1..n))).len:>6} {!n:>6}"


echo "\n!20 = ", !20</lang>
echo "\n!20 = ", !20</syntaxhighlight>


{{out}}
{{out}}
Line 2,339: Line 2,339:


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>derangements(n)=if(n,round(n!/exp(1)),1);
<syntaxhighlight lang="parigp">derangements(n)=if(n,round(n!/exp(1)),1);
derange(n)={
derange(n)={
my(v=[[]],tmp);
my(v=[[]],tmp);
Line 2,357: Line 2,357:
derange(4)
derange(4)
for(n=0,9,print("!"n" = "#derange(n)" = "derangements(n)))
for(n=0,9,print("!"n" = "#derange(n)" = "derangements(n)))
derangements(20)</lang>
derangements(20)</syntaxhighlight>
{{out}}
{{out}}
<pre>%1 = [[2, 1, 4, 3], [2, 3, 4, 1], [2, 4, 1, 3], [3, 1, 4, 2], [3, 4, 1, 2], [3, 4, 2, 1], [4, 1, 2, 3], [4, 3, 1, 2], [4, 3, 2, 1]]
<pre>%1 = [[2, 1, 4, 3], [2, 3, 4, 1], [2, 4, 1, 3], [3, 1, 4, 2], [3, 4, 1, 2], [3, 4, 2, 1], [4, 1, 2, 3], [4, 3, 1, 2], [4, 3, 2, 1]]
Line 2,375: Line 2,375:


=={{header|Pascal}}==
=={{header|Pascal}}==
<lang pascal>
<syntaxhighlight lang="pascal">
program Derangements_RC;
program Derangements_RC;
(*
(*
Line 2,500: Line 2,500:
WriteLn( 'Subfactorial(20) = ', Subfactorial(20));
WriteLn( 'Subfactorial(20) = ', Subfactorial(20));
end.
end.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,533: Line 2,533:
=={{header|Perl}}==
=={{header|Perl}}==
===Traditional verbose version===
===Traditional verbose version===
<lang Perl>sub d {
<syntaxhighlight lang="perl">sub d {
# compare this with the deranged() sub to see how to turn procedural
# compare this with the deranged() sub to see how to turn procedural
# code into functional one ('functional' as not in 'understandable')
# code into functional one ('functional' as not in 'understandable')
Line 2,598: Line 2,598:


print "\nNumber of derangements:\n";
print "\nNumber of derangements:\n";
print "$_:\t", sub_factorial($_), "\n" for 1 .. 20;</lang>
print "$_:\t", sub_factorial($_), "\n" for 1 .. 20;</syntaxhighlight>


{{out}}
{{out}}
Line 2,648: Line 2,648:
===Using a module===
===Using a module===
{{libheader|ntheory}}
{{libheader|ntheory}}
<lang perl>use ntheory ":all";
<syntaxhighlight lang="perl">use ntheory ":all";


# Count derangements using derangement iterator
# Count derangements using derangement iterator
Line 2,672: Line 2,672:
printf "\n%3s %15s %15s\n","N","List count","!N";
printf "\n%3s %15s %15s\n","N","List count","!N";
printf "%3d %15d %15d %15d\n",$_,countderange($_),subfactorial1($_),subfactorial2($_) for 0..9;
printf "%3d %15d %15d %15d\n",$_,countderange($_),subfactorial1($_),subfactorial2($_) for 0..9;
printf "%3d %15s %s\n",$_,"",subfactorial2($_) for 20,200;</lang>
printf "%3d %15s %s\n",$_,"",subfactorial2($_) for 20,200;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,703: Line 2,703:
=={{header|Phix}}==
=={{header|Phix}}==
{{libheader|Phix/mpfr}}
{{libheader|Phix/mpfr}}
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">deranged</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s1</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">s2</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">deranged</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s1</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">s2</span><span style="color: #0000FF;">)</span>
Line 2,749: Line 2,749:
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"!20=%s (mpfr)\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">mpz_sub_factorial</span><span style="color: #0000FF;">(</span><span style="color: #000000;">20</span><span style="color: #0000FF;">)})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"!20=%s (mpfr)\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">mpz_sub_factorial</span><span style="color: #0000FF;">(</span><span style="color: #000000;">20</span><span style="color: #0000FF;">)})</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,770: Line 2,770:
A more efficient method of calculating subfactorials (0 should be handled separately, or obviously prepend a 1 and extract with idx+1).<br>
A more efficient method of calculating subfactorials (0 should be handled separately, or obviously prepend a 1 and extract with idx+1).<br>
Should you instead of string results want an array of mpz for further calculations, use the mpz_init_set() call as shown:
Should you instead of string results want an array of mpz for further calculations, use the mpz_init_set() call as shown:
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
Line 2,792: Line 2,792:
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">extract</span><span style="color: #0000FF;">(</span><span style="color: #000000;">subfactorial</span><span style="color: #0000FF;">(</span><span style="color: #000000;">20</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">9</span><span style="color: #0000FF;">)&</span><span style="color: #000000;">20</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">extract</span><span style="color: #0000FF;">(</span><span style="color: #000000;">subfactorial</span><span style="color: #0000FF;">(</span><span style="color: #000000;">20</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">9</span><span style="color: #0000FF;">)&</span><span style="color: #000000;">20</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>{"0","1","2","9","44","265","1854","14833","133496","895014631192902121"}</pre>
<pre>{"0","1","2","9","44","265","1854","14833","133496","895014631192902121"}</pre>


=={{header|Picat}}==
=={{header|Picat}}==
<lang Picat>import util.
<syntaxhighlight lang="picat">import util.


go =>
go =>
Line 2,849: Line 2,849:
'!!'(N) = subfactorial(N).
'!!'(N) = subfactorial(N).


'!-!!'(N) = fact(N) - subfactorial(N).</lang>
'!-!!'(N) = fact(N) - subfactorial(N).</syntaxhighlight>


{{out}}
{{out}}
Line 2,875: Line 2,875:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(load "@lib/simul.l") # For 'permute'
<syntaxhighlight lang="picolisp">(load "@lib/simul.l") # For 'permute'


(de derangements (Lst)
(de derangements (Lst)
Line 2,887: Line 2,887:
(*
(*
(dec N)
(dec N)
(+ (subfact (dec N)) (subfact (- N 2))) ) ) )</lang>
(+ (subfact (dec N)) (subfact (- N 2))) ) ) )</syntaxhighlight>
{{out}}
{{out}}
<pre>: (derangements (range 1 4))
<pre>: (derangements (range 1 4))
Line 2,914: Line 2,914:
=={{header|PureBasic}}==
=={{header|PureBasic}}==
Brute Force
Brute Force
<syntaxhighlight lang="purebasic">
<lang PureBasic>
Procedure.q Subfactoral(n)
Procedure.q Subfactoral(n)
If n=0:ProcedureReturn 1:EndIf
If n=0:ProcedureReturn 1:EndIf
Line 3,038: Line 3,038:
DeleteFile(tempFile.s)
DeleteFile(tempFile.s)
Return
Return
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,077: Line 3,077:


{{trans|C}}
{{trans|C}}
<lang PureBasic>Procedure.i deranged(depth, lenn, Array d(1), show)
<syntaxhighlight lang="purebasic">Procedure.i deranged(depth, lenn, Array d(1), show)
Protected count, tmp, i
Protected count, tmp, i
If depth = lenn
If depth = lenn
Line 3,127: Line 3,127:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>


{{out}}
{{out}}
Line 3,168: Line 3,168:
=={{header|Python}}==
=={{header|Python}}==
Includes stretch goal.
Includes stretch goal.
<lang python>from itertools import permutations
<syntaxhighlight lang="python">from itertools import permutations
import math
import math


Line 3,208: Line 3,208:


n = 20
n = 20
print("\n!%i = %i" % (n, subfact(n)))</lang>
print("\n!%i = %i" % (n, subfact(n)))</syntaxhighlight>


{{out}}
{{out}}
Line 3,240: Line 3,240:
{{trans|FreeBASIC}}
{{trans|FreeBASIC}}
Error "Subscript out of scope" for n > 7
Error "Subscript out of scope" for n > 7
<lang qbasic>' Heap's algorithm non-recursive
<syntaxhighlight lang="qbasic">' Heap's algorithm non-recursive
FUNCTION permsderange (n!, flag!)
FUNCTION permsderange (n!, flag!)
IF n = 0 THEN permsderange = 1
IF n = 0 THEN permsderange = 1
Line 3,309: Line 3,309:
FOR i = 0 TO 7
FOR i = 0 TO 7
PRINT USING " ###: ######## ########"; i; permsderange(i, 1); subfac(i)
PRINT USING " ###: ######## ########"; i; permsderange(i, 1); subfac(i)
NEXT i</lang>
NEXT i</syntaxhighlight>


=={{header|Quackery}}==
=={{header|Quackery}}==


<syntaxhighlight lang="quackery">
<lang Quackery>
[ stack ] is deranges.num ( --> [ )
[ stack ] is deranges.num ( --> [ )


Line 3,354: Line 3,354:
i^ sub! echo cr ]
i^ sub! echo cr ]
cr
cr
20 sub! echo</lang>
20 sub! echo</syntaxhighlight>


{{out}}
{{out}}
Line 3,382: Line 3,382:


=={{header|Racket}}==
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
#lang racket


Line 3,430: Line 3,430:
(sub-fact 20)
(sub-fact 20)
;; -> 895014631192902121
;; -> 895014631192902121
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 3,445: Line 3,445:
Although not necessary for this task, I have used <code>eqv</code> instead of <code>==</code> so that the <code>derangements()</code> function also works with any set of arbitrary objects (eg. strings, lists, etc.)
Although not necessary for this task, I have used <code>eqv</code> instead of <code>==</code> so that the <code>derangements()</code> function also works with any set of arbitrary objects (eg. strings, lists, etc.)


<lang perl6>sub derangements(@l) {
<syntaxhighlight lang="raku" line>sub derangements(@l) {
@l.permutations.grep(-> @p { none(@p Zeqv @l) })
@l.permutations.grep(-> @p { none(@p Zeqv @l) })
}
}
Line 3,459: Line 3,459:
for 0 .. 9 -> $n {
for 0 .. 9 -> $n {
say "!$n == { !$n } == { derangements(^$n).elems }"
say "!$n == { !$n } == { derangements(^$n).elems }"
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,479: Line 3,479:


=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>/*REXX program generates all permutations of N derangements and subfactorial # */
<syntaxhighlight lang="rexx">/*REXX program generates all permutations of N derangements and subfactorial # */
numeric digits 1000 /*be able to handle large subfactorials*/
numeric digits 1000 /*be able to handle large subfactorials*/
parse arg N .; if N=='' | N=="," then N=4 /*Not specified? Then use the default.*/
parse arg N .; if N=='' | N=="," then N=4 /*Not specified? Then use the default.*/
Line 3,520: Line 3,520:
if i==0 then return 0
if i==0 then return 0
do m=i+1 while @.m<@.i; end /*m*/ /* [↓] swap two values. */
do m=i+1 while @.m<@.i; end /*m*/ /* [↓] swap two values. */
parse value @.m @.i with @.i @.m; return 1</lang>
parse value @.m @.i with @.i @.m; return 1</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
<pre>
Line 3,544: Line 3,544:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>def derangements(n)
<syntaxhighlight lang="ruby">def derangements(n)
ary = (1 .. n).to_a
ary = (1 .. n).to_a
ary.permutation.select do |perm|
ary.permutation.select do |perm|
Line 3,570: Line 3,570:
(10..20).each do |n|
(10..20).each do |n|
puts "#{n} : #{subfact(n)}"
puts "#{n} : #{subfact(n)}"
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 3,612: Line 3,612:
=={{header|Scala}}==
=={{header|Scala}}==
{{trans|Ruby}}
{{trans|Ruby}}
<lang Scala>def derangements(n: Int) =
<syntaxhighlight lang="scala">def derangements(n: Int) =
(1 to n).permutations.filter(_.zipWithIndex.forall{case (a, b) => a - b != 1})
(1 to n).permutations.filter(_.zipWithIndex.forall{case (a, b) => a - b != 1})


Line 3,626: Line 3,626:
println("\n%2s%10s%10s".format("n", "derange", "subfact"))
println("\n%2s%10s%10s".format("n", "derange", "subfact"))
(0 to 9).foreach(n => println("%2d%10d%10d".format(n, derangements(n).size, subfactorial(n))))
(0 to 9).foreach(n => println("%2d%10d%10d".format(n, derangements(n).size, subfactorial(n))))
(10 to 20).foreach(n => println(f"$n%2d${subfactorial(n)}%20d"))</lang>
(10 to 20).foreach(n => println(f"$n%2d${subfactorial(n)}%20d"))</syntaxhighlight>
{{out}}
{{out}}
<pre>Derangements for n = 4
<pre>Derangements for n = 4
Line 3,663: Line 3,663:


=={{header|SuperCollider}}==
=={{header|SuperCollider}}==
<syntaxhighlight lang="supercollider">(
<lang SuperCollider>(
d = { |array, n|
d = { |array, n|
Routine {
Routine {
Line 3,678: Line 3,678:
x = f.(4);
x = f.(4);
x.all.do(_.postln); "";
x.all.do(_.postln); "";
)</lang>
)</syntaxhighlight>


Answers:
Answers:
<syntaxhighlight lang="supercollider">
<lang SuperCollider>
[ 3, 2, 1, 0 ]
[ 3, 2, 1, 0 ]
[ 2, 3, 0, 1 ]
[ 2, 3, 0, 1 ]
Line 3,691: Line 3,691:
[ 2, 3, 1, 0 ]
[ 2, 3, 1, 0 ]
[ 3, 0, 1, 2 ]
[ 3, 0, 1, 2 ]
</syntaxhighlight>
</lang>


<syntaxhighlight lang="supercollider">(
<lang SuperCollider>(
z = { |n|
z = { |n|
case
case
Line 3,707: Line 3,707:
"% % %\n".postf(i, p.(derangements.size), p.(subfactorial));
"% % %\n".postf(i, p.(derangements.size), p.(subfactorial));
};
};
)</lang>
)</syntaxhighlight>


Answers:
Answers:


<syntaxhighlight lang="supercollider">
<lang SuperCollider>
n derangements subfactorial
n derangements subfactorial
0 1 1
0 1 1
Line 3,723: Line 3,723:
8 14833 14833
8 14833 14833
9 133496 133496
9 133496 133496
</syntaxhighlight>
</lang>


=={{header|Tcl}}==
=={{header|Tcl}}==
{{tcllib|struct::list}}
{{tcllib|struct::list}}
<lang tcl>package require Tcl 8.5; # for arbitrary-precision integers
<syntaxhighlight lang="tcl">package require Tcl 8.5; # for arbitrary-precision integers
package require struct::list; # for permutation enumerator
package require struct::list; # for permutation enumerator


Line 3,763: Line 3,763:
}
}
return $s
return $s
}</lang>
}</syntaxhighlight>
Demonstrating with the display parts of the task:
Demonstrating with the display parts of the task:
<lang tcl>foreach d [deranged1to 4] {
<syntaxhighlight lang="tcl">foreach d [deranged1to 4] {
puts "derangement of 1..4: $d"
puts "derangement of 1..4: $d"
}
}
Line 3,775: Line 3,775:


# Stretch goal
# Stretch goal
puts "\n!20 = [subfact 20]"</lang>
puts "\n!20 = [subfact 20]"</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,807: Line 3,807:
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
{{libheader|Wren-big}}
{{libheader|Wren-big}}
<lang ecmascript>import "/fmt" for Fmt
<syntaxhighlight lang="ecmascript">import "/fmt" for Fmt
import "/big" for BigInt
import "/big" for BigInt


Line 3,862: Line 3,862:
Fmt.print("$d $-9d $-9i", n, counted, subFactorial.call(n))
Fmt.print("$d $-9d $-9i", n, counted, subFactorial.call(n))
}
}
System.print("\n!20 = %(subFactorial.call(20))")</lang>
System.print("\n!20 = %(subFactorial.call(20))")</syntaxhighlight>


{{out}}
{{out}}
Line 3,896: Line 3,896:
=={{header|zkl}}==
=={{header|zkl}}==
{{trans|Python}} mostly
{{trans|Python}} mostly
<lang zkl>fcn subFact(n){
<syntaxhighlight lang="zkl">fcn subFact(n){
if(n==0) return(1);
if(n==0) return(1);
if(n==1) return(0);
if(n==1) return(0);
Line 3,914: Line 3,914:
sum + (perm.zipWith('==,enum).sum(0) == 0)
sum + (perm.zipWith('==,enum).sum(0) == 0)
},0);
},0);
}</lang>
}</syntaxhighlight>
<lang zkl>println("Derangements of 0,1,2,3:\n",derangements(4));
<syntaxhighlight lang="zkl">println("Derangements of 0,1,2,3:\n",derangements(4));
println("\nTable of n vs counted vs calculated derangements:");
println("\nTable of n vs counted vs calculated derangements:");
foreach n in (10){
foreach n in (10){
Line 3,921: Line 3,921:
}
}


n:=20; println("\n!%d = %d".fmt(n, subFact(n)));</lang>
n:=20; println("\n!%d = %d".fmt(n, subFact(n)));</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,943: Line 3,943:
</pre>
</pre>
Lazy/iterators version:
Lazy/iterators version:
<lang zkl>fcn derangements(n){ //-->Walker
<syntaxhighlight lang="zkl">fcn derangements(n){ //-->Walker
enum:=[0..n-1].pump(List);
enum:=[0..n-1].pump(List);
Utils.Helpers.permuteW(enum).tweak('wrap(perm){
Utils.Helpers.permuteW(enum).tweak('wrap(perm){
Line 3,952: Line 3,952:
fcn derangers(n){ // just count # of derangements, w/o saving them
fcn derangers(n){ // just count # of derangements, w/o saving them
derangements(n).reduce('+.fpM("10-",1),0); // ignore perm --> '+(1,sum)...
derangements(n).reduce('+.fpM("10-",1),0); // ignore perm --> '+(1,sum)...
}</lang>
}</syntaxhighlight>
<lang zkl>foreach d in (derangements(4)){ println(d) }
<syntaxhighlight lang="zkl">foreach d in (derangements(4)){ println(d) }
//rest of test code remains the same</lang>
//rest of test code remains the same</syntaxhighlight>