How to resolve the algorithm Permutations/Derangements step by step in the PARI/GP programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Permutations/Derangements step by step in the PARI/GP 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 PARI/GP programming language

Source code in the pari/gp programming language

derangements(n)=if(n,round(n!/exp(1)),1);
derange(n)={
	my(v=[[]],tmp);
	for(level=1,n,
		tmp=List();
		for(i=1,#v,
			for(k=1,n,
				if(k==level, next);
				for(j=1,level-1,if(v[i][j]==k, next(2)));
				listput(tmp, concat(v[i],k))
			)
		);
		v=Vec(tmp)
	);
	v
};
derange(4)
for(n=0,9,print("!"n" = "#derange(n)" = "derangements(n)))
derangements(20)

  

You may also check:How to resolve the algorithm Dot product step by step in the CLU programming language
You may also check:How to resolve the algorithm Comments step by step in the PicoLisp programming language
You may also check:How to resolve the algorithm Aliquot sequence classifications step by step in the D programming language
You may also check:How to resolve the algorithm Van der Corput sequence step by step in the Scala programming language
You may also check:How to resolve the algorithm CSV data manipulation step by step in the Go programming language