How to resolve the algorithm Permutations/Derangements step by step in the zkl programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Permutations/Derangements step by step in the zkl programming language
Table of Contents
Problem Statement
A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n. There are various ways to calculate !n.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Permutations/Derangements step by step in the zkl programming language
Source code in the zkl programming language
fcn subFact(n){
if(n==0) return(1);
if(n==1) return(0);
(n-1)*(self.fcn(n-1) + self.fcn(n-2));
}
fcn derangements(n){
// All deranged permutations of the integers 0..n-1 inclusive
enum:=[0..n-1].pump(List);
Utils.Helpers.permuteW(enum).filter('wrap(perm){
perm.zipWith('==,enum).sum(0) == 0
});
}
fcn derangers(n){ // just count # of derangements
enum:=[0..n-1].pump(List);
Utils.Helpers.permuteW(enum).reduce('wrap(sum,perm){
sum + (perm.zipWith('==,enum).sum(0) == 0)
},0);
}
println("Derangements of 0,1,2,3:\n",derangements(4));
println("\nTable of n vs counted vs calculated derangements:");
foreach n in (10){
println("%2d %-6d %-6d".fmt(n, derangers(n), subFact(n)));
}
n:=20; println("\n!%d = %d".fmt(n, subFact(n)));
fcn derangements(n){ //-->Walker
enum:=[0..n-1].pump(List);
Utils.Helpers.permuteW(enum).tweak('wrap(perm){
if(perm.zipWith('==,enum).sum(0)) Void.Skip
else perm
});
}
fcn derangers(n){ // just count # of derangements, w/o saving them
derangements(n).reduce('+.fpM("10-",1),0); // ignore perm --> '+(1,sum)...
}
foreach d in (derangements(4)){ println(d) }
//rest of test code remains the same
You may also check:How to resolve the algorithm Loops/Foreach step by step in the Kotlin programming language
You may also check:How to resolve the algorithm Colour bars/Display step by step in the Factor programming language
You may also check:How to resolve the algorithm Evaluate binomial coefficients step by step in the FunL programming language
You may also check:How to resolve the algorithm Higher-order functions step by step in the Smalltalk programming language
You may also check:How to resolve the algorithm Singleton step by step in the BASIC programming language