Permutations/Derangements: Difference between revisions

m
syntax highlighting fixup automation
(Added solution for Pascal.)
m (syntax highlighting fixup automation)
Line 32:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F derangements(n)
[[Int]] r
V perm = Array(0 .< n)
Line 55:
 
n = 20
print("\n!#. = #.".format(n, subfact(n)))</langsyntaxhighlight>
 
{{out}}
Line 88:
{{trans|BBC BASIC}}
Due to 32 bit integers !12 is the limit.
<langsyntaxhighlight lang="360asm">* Permutations/Derangements 01/04/2017
DERANGE CSECT
USING DERANGE,R13 base register
Line 339:
PG DC CL80' ' buffer
YREGS
END DERANGE</langsyntaxhighlight>
{{out}}
<pre>
Line 369:
=={{header|Ada}}==
{{trans|C}}
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
procedure DePermute is
type U64 is mod 2**64;
Line 422:
end loop;
Put_Line ("!20 = " & U64'Image (sub_fact (20)));
end DePermute;</langsyntaxhighlight>
{{out}}
<pre>Deranged 4:
Line 449:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">isClean?: function [s,o][
loop.with:'i s 'a [
if a = o\[i] -> return false
Line 481:
]
 
print ~"\n!20 = |subfactorial 20|"</langsyntaxhighlight>
 
{{out}}
Line 515:
{{works with|AutoHotkey_L}}
Note that the permutations are generated in lexicographic order, from http://www.autohotkey.com/forum/topic77959.html
<langsyntaxhighlight AHKlang="ahk">#NoEnv
SetBatchLines -1
Process, Priority,, high
Line 610:
a *= A_Index
return a
}</langsyntaxhighlight>
{{out}}
<pre>Derangements for 1, 2, 3, 4:
Line 639:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight BBClang="bbc BASICbasic"> PRINT"Derangements for the numbers 0,1,2,3 are:"
Count% = FN_Derangement_Generate(4,TRUE)
Line 713:
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))</langsyntaxhighlight>
 
{{out}}
Line 752:
Also the counter <code>count</code> is a global variable.
<langsyntaxhighlight lang="bracmat">( ( calculated-!n
= memo answ
. (memo==)
Line 803:
& out$("!20 =" calculated-!n$20)
& lst$calculated-!n
)</langsyntaxhighlight>
{{out}}
<pre>Derangements of 1 2 3 4
Line 862:
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <stdio.h>
typedef unsigned long long LONG;
 
Line 918:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>Deranged Four:
Line 959:
Recursive version
 
<langsyntaxhighlight lang="csharp">
using System;
class Derangements
Line 988:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
Generating functions with no fixed point
 
<langsyntaxhighlight Clojurelang="clojure">(ns derangements.core
(:require [clojure.set :as s]))
 
Line 1,032:
(range 10)))
(println (subfactorial 20))))
</syntaxhighlight>
</lang>
{{Out}}
<pre>[1 0 3 2]
Line 1,057:
=={{header|D}}==
===Iterative Version===
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.typecons, std.conv,
std.range, std.traits;
 
Line 1,121:
 
writefln("\n!20 = %s", 20L.subfact);
}</langsyntaxhighlight>
{{out}}
<pre>Derangements for n = 4:
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.
Same output.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.typecons, std.conv, std.range;
 
T factorial(T)(in T n) pure nothrow {
Line 1,197:
 
writefln("\n!20 = %s", 20L.subfact);
}</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(lib 'list) ;; in-permutations
(lib 'bigint)
Line 1,221:
(remember '!n #(1 0))
 
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="scheme">
(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))
Line 1,244:
(!n 20)
→ 895014631192902121
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule Permutation do
def derangements(n) do
list = Enum.to_list(1..n)
Line 1,276:
Enum.each(10..20, fn n ->
:io.format "~2w :~19w~n", [n, Permutation.subfact(n)]
end)</langsyntaxhighlight>
 
{{out}}
Line 1,318:
=={{header|F_Sharp|F#}}==
===The Function===
<langsyntaxhighlight lang="fsharp">
// Generate derangements. Nigel Galloway: July 9th., 2019
let derange n=
Line 1,329:
|_->()}
derange 0 [|1..n|] (n-1)
</syntaxhighlight>
</lang>
===The Task===
<langsyntaxhighlight lang="fsharp">
derange 4 |> Seq.iter(printfn "%A")
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,346:
[|4; 1; 2; 3|]
</pre>
<langsyntaxhighlight 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
[1..9] |> Seq.iter(fun n->printfn "items=%d !n=%d derangements=%d" n (subFact n) (derange n|>Seq.length))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,365:
=={{header|Factor}}==
{{works with|Factor|0.98}}
<langsyntaxhighlight lang="factor">USING: combinators formatting io kernel math math.combinatorics
prettyprint sequences ;
IN: rosetta-code.derangements
Line 1,386:
"%d%8d%8d\n" printf
] each nl
"!20 = " write 20 !n .</langsyntaxhighlight>
{{out}}
<pre>
Line 1,419:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 08-04-2017
' compile with: fbc -s console
 
Line 1,512:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>permutations derangements for n = 4
Line 1,543:
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># All of this is built-in
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 ],
Line 1,577:
# [ 7, 1854, 1854, 1854 ],
# [ 8, 14833, 14833, 14833 ],
# [ 9, 133496, 133496, 133496 ] ]</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,650:
// stretch (sic)
fmt.Println("\n!20 =", subFact(20))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,682:
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def fact = { n -> [1,(1..<(n+1)).inject(1) { prod, i -> prod * i }].max() }
def subfact
subfact = { BigInteger n -> (n == 0) ? 1 : (n == 1) ? 0 : ((n-1) * (subfact(n-1) + subfact(n-2))) }
Line 1,690:
if (l) l.eachPermutation { p -> if ([p,l].transpose().every{ pp, ll -> pp != ll }) d << p }
d
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">def d = derangement([1,2,3,4])
assert d.size() == subfact(4)
d.each { println it }
Line 1,708:
println """
!20 == ${subfact(20)}
"""</langsyntaxhighlight>
 
{{out}}
Line 1,738:
=={{header|Haskell}}==
 
<langsyntaxhighlight Haskelllang="haskell">import Control.Monad (forM_)
 
import Data.List (permutations)
Line 1,770:
putStrLn ""
-- Print the number of derangements in a list of 20 items
print $ subfactorial 20</langsyntaxhighlight>
{{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]]
Line 1,788:
Alternatively, this is a backtracking method:
 
<langsyntaxhighlight lang="haskell">derangements xs = loop xs xs
where loop [] [] = [[]]
loop (h:hs) xs = [x:ys | x <- xs, x /= h, ys <- loop hs (delete x xs)]</langsyntaxhighlight>
 
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:
Note: <code>!n</code> in J denotes factorial (or gamma n+1), and not subfactorial.
 
<langsyntaxhighlight lang="j">derangement=: (A.&i.~ !)~ (*/ .~: # [) i. NB. task item 1
subfactorial=: ! * +/@(_1&^ % !)@i.@>: NB. task item 3</langsyntaxhighlight>
 
Requested examples:
 
<langsyntaxhighlight lang="j"> derangement 4 NB. task item 2
1 0 3 2
1 2 3 0
Line 1,826:
8.95015e17
subfactorial 20x NB. using extended precision
895014631192902121</langsyntaxhighlight>
 
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:
=={{header|Java}}==
{{trans|D}}
<langsyntaxhighlight lang="java">import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
Line 1,926:
return r;
}
}</langsyntaxhighlight>
 
<pre>derangements for n = 4
Line 1,958:
{{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.
<langsyntaxhighlight lang="jq">def derangements:
 
# In order to reference the original array conveniently, define _derangements(ary):
Line 1,981:
 
# Avoid creating an array just to count the items in a stream:
def count(g): reduce g as $i (0; . + 1);</langsyntaxhighlight>
'''Tasks''':
<langsyntaxhighlight lang="jq"> "Derangements:",
([range(1;5)] | derangements),
"",
Line 1,989:
(range(1;10) as $i | "\($i): \(count( [range(0;$i)] | derangements)) vs \($i|subfact)"),
"",
"Computed approximation to !20 (15 significant digits): \(20|subfact)"</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight lang="sh">$ jq -n -c -r -f derangements.jq
jq -n -c -r -f derangements.jq
 
Line 2,016:
9: 133496 vs 133496
 
Computed approximation to !20 (15 significant digits): 895014631192902000</langsyntaxhighlight>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using Printf, Combinatorics
 
derangements(n::Int) = (perm for perm in permutations(1:n)
Line 2,050:
end
 
println("\n!20 = ", subfact(20))</langsyntaxhighlight>
 
{{out}}
Line 2,079:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun <T> permute(input: List<T>): List<List<T>> {
Line 2,124:
}
println("\n!20 = ${subFactorial(20)}")
}</langsyntaxhighlight>
 
{{out}}
Line 2,157:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">-- Return an iterator to produce every permutation of list
function permute (list)
local function perm (list, n)
Line 2,225:
print("\t| " .. #derangements(listOneTo(i)))
end
print("\n\nThe subfactorial of 20 is " .. subFact(20))</langsyntaxhighlight>
{{out}}
<pre>Derangements of [1,2,3,4]
Line 2,258:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">
<lang Mathematica>
Needs["Combinatorica`"]
derangements[n_] := Derangements[Range[n]]
derangements[4]
Table[{NumberOfDerangements[i], Subfactorial[i]}, {i, 9}] // TableForm
Subfactorial[20]</langsyntaxhighlight>
{{out}}
<pre>
Line 2,282:
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import algorithm, sequtils, strformat, strutils, tables
 
iterator derangements[T](a: openArray[T]): seq[T] =
Line 2,308:
echo &"{n} {toSeq(derangements(toSeq(1..n))).len:>6} {!n:>6}"
 
echo "\n!20 = ", !20</langsyntaxhighlight>
 
{{out}}
Line 2,339:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">derangements(n)=if(n,round(n!/exp(1)),1);
derange(n)={
my(v=[[]],tmp);
Line 2,357:
derange(4)
for(n=0,9,print("!"n" = "#derange(n)" = "derangements(n)))
derangements(20)</langsyntaxhighlight>
{{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]]
Line 2,375:
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">
program Derangements_RC;
(*
Line 2,500:
WriteLn( 'Subfactorial(20) = ', Subfactorial(20));
end.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,533:
=={{header|Perl}}==
===Traditional verbose version===
<langsyntaxhighlight Perllang="perl">sub d {
# compare this with the deranged() sub to see how to turn procedural
# code into functional one ('functional' as not in 'understandable')
Line 2,598:
 
print "\nNumber of derangements:\n";
print "$_:\t", sub_factorial($_), "\n" for 1 .. 20;</langsyntaxhighlight>
 
{{out}}
Line 2,648:
===Using a module===
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use ntheory ":all";
 
# Count derangements using derangement iterator
Line 2,672:
printf "\n%3s %15s %15s\n","N","List count","!N";
printf "%3d %15d %15d %15d\n",$_,countderange($_),subfactorial1($_),subfactorial2($_) for 0..9;
printf "%3d %15s %s\n",$_,"",subfactorial2($_) for 20,200;</langsyntaxhighlight>
{{out}}
<pre>
Line 2,703:
=={{header|Phix}}==
{{libheader|Phix/mpfr}}
<!--<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;">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:
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
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>
Should you instead of string results want an array of mpz for further calculations, use the mpz_init_set() call as shown:
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>{"0","1","2","9","44","265","1854","14833","133496","895014631192902121"}</pre>
 
=={{header|Picat}}==
<langsyntaxhighlight Picatlang="picat">import util.
 
go =>
Line 2,849:
'!!'(N) = subfactorial(N).
 
'!-!!'(N) = fact(N) - subfactorial(N).</langsyntaxhighlight>
 
{{out}}
Line 2,875:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/simul.l") # For 'permute'
 
(de derangements (Lst)
Line 2,887:
(*
(dec N)
(+ (subfact (dec N)) (subfact (- N 2))) ) ) )</langsyntaxhighlight>
{{out}}
<pre>: (derangements (range 1 4))
Line 2,914:
=={{header|PureBasic}}==
Brute Force
<syntaxhighlight lang="purebasic">
<lang PureBasic>
Procedure.q Subfactoral(n)
If n=0:ProcedureReturn 1:EndIf
Line 3,038:
DeleteFile(tempFile.s)
Return
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,077:
 
{{trans|C}}
<langsyntaxhighlight PureBasiclang="purebasic">Procedure.i deranged(depth, lenn, Array d(1), show)
Protected count, tmp, i
If depth = lenn
Line 3,127:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
 
{{out}}
Line 3,168:
=={{header|Python}}==
Includes stretch goal.
<langsyntaxhighlight lang="python">from itertools import permutations
import math
 
Line 3,208:
 
n = 20
print("\n!%i = %i" % (n, subfact(n)))</langsyntaxhighlight>
 
{{out}}
Line 3,240:
{{trans|FreeBASIC}}
Error "Subscript out of scope" for n > 7
<langsyntaxhighlight lang="qbasic">' Heap's algorithm non-recursive
FUNCTION permsderange (n!, flag!)
IF n = 0 THEN permsderange = 1
Line 3,309:
FOR i = 0 TO 7
PRINT USING " ###: ######## ########"; i; permsderange(i, 1); subfac(i)
NEXT i</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery">
<lang Quackery>
[ stack ] is deranges.num ( --> [ )
 
Line 3,354:
i^ sub! echo cr ]
cr
20 sub! echo</langsyntaxhighlight>
 
{{out}}
Line 3,382:
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 3,430:
(sub-fact 20)
;; -> 895014631192902121
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
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.)
 
<syntaxhighlight lang="raku" perl6line>sub derangements(@l) {
@l.permutations.grep(-> @p { none(@p Zeqv @l) })
}
Line 3,459:
for 0 .. 9 -> $n {
say "!$n == { !$n } == { derangements(^$n).elems }"
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,479:
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program generates all permutations of N derangements and subfactorial # */
numeric digits 1000 /*be able to handle large subfactorials*/
parse arg N .; if N=='' | N=="," then N=4 /*Not specified? Then use the default.*/
Line 3,520:
if i==0 then return 0
do m=i+1 while @.m<@.i; end /*m*/ /* [↓] swap two values. */
parse value @.m @.i with @.i @.m; return 1</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 3,544:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def derangements(n)
ary = (1 .. n).to_a
ary.permutation.select do |perm|
Line 3,570:
(10..20).each do |n|
puts "#{n} : #{subfact(n)}"
end</langsyntaxhighlight>
 
{{out}}
Line 3,612:
=={{header|Scala}}==
{{trans|Ruby}}
<langsyntaxhighlight Scalalang="scala">def derangements(n: Int) =
(1 to n).permutations.filter(_.zipWithIndex.forall{case (a, b) => a - b != 1})
 
Line 3,626:
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))))
(10 to 20).foreach(n => println(f"$n%2d${subfactorial(n)}%20d"))</langsyntaxhighlight>
{{out}}
<pre>Derangements for n = 4
Line 3,663:
 
=={{header|SuperCollider}}==
<syntaxhighlight lang="supercollider">(
<lang SuperCollider>(
d = { |array, n|
Routine {
Line 3,678:
x = f.(4);
x.all.do(_.postln); "";
)</langsyntaxhighlight>
 
Answers:
<syntaxhighlight lang="supercollider">
<lang SuperCollider>
[ 3, 2, 1, 0 ]
[ 2, 3, 0, 1 ]
Line 3,691:
[ 2, 3, 1, 0 ]
[ 3, 0, 1, 2 ]
</syntaxhighlight>
</lang>
 
<syntaxhighlight lang="supercollider">(
<lang SuperCollider>(
z = { |n|
case
Line 3,707:
"% % %\n".postf(i, p.(derangements.size), p.(subfactorial));
};
)</langsyntaxhighlight>
 
Answers:
 
<syntaxhighlight lang="supercollider">
<lang SuperCollider>
n derangements subfactorial
0 1 1
Line 3,723:
8 14833 14833
9 133496 133496
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
{{tcllib|struct::list}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5; # for arbitrary-precision integers
package require struct::list; # for permutation enumerator
 
Line 3,763:
}
return $s
}</langsyntaxhighlight>
Demonstrating with the display parts of the task:
<langsyntaxhighlight lang="tcl">foreach d [deranged1to 4] {
puts "derangement of 1..4: $d"
}
Line 3,775:
 
# Stretch goal
puts "\n!20 = [subfact 20]"</langsyntaxhighlight>
{{out}}
<pre>
Line 3,807:
{{libheader|Wren-fmt}}
{{libheader|Wren-big}}
<langsyntaxhighlight lang="ecmascript">import "/fmt" for Fmt
import "/big" for BigInt
 
Line 3,862:
Fmt.print("$d $-9d $-9i", n, counted, subFactorial.call(n))
}
System.print("\n!20 = %(subFactorial.call(20))")</langsyntaxhighlight>
 
{{out}}
Line 3,896:
=={{header|zkl}}==
{{trans|Python}} mostly
<langsyntaxhighlight lang="zkl">fcn subFact(n){
if(n==0) return(1);
if(n==1) return(0);
Line 3,914:
sum + (perm.zipWith('==,enum).sum(0) == 0)
},0);
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">println("Derangements of 0,1,2,3:\n",derangements(4));
println("\nTable of n vs counted vs calculated derangements:");
foreach n in (10){
Line 3,921:
}
 
n:=20; println("\n!%d = %d".fmt(n, subFact(n)));</langsyntaxhighlight>
{{out}}
<pre>
Line 3,943:
</pre>
Lazy/iterators version:
<langsyntaxhighlight lang="zkl">fcn derangements(n){ //-->Walker
enum:=[0..n-1].pump(List);
Utils.Helpers.permuteW(enum).tweak('wrap(perm){
Line 3,952:
fcn derangers(n){ // just count # of derangements, w/o saving them
derangements(n).reduce('+.fpM("10-",1),0); // ignore perm --> '+(1,sum)...
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">foreach d in (derangements(4)){ println(d) }
//rest of test code remains the same</langsyntaxhighlight>
10,327

edits