Prolog Operators

Prolog Lists

Built-In Predicates

Miscellaneous

Prolog - Permutation Operations



Permutation

Permutation refers to arrangments of elements in specific order and each combination should be unique order wise. For example, in case of a List, [a, b, c], the possible permutations are as following −

[a, b, c], 
[a, c, b], 
[b, a, c], 
[b, c, a], 
[c, a, b], 
[c, b, a]

Prolog provides an inbuilt function permutation to get all the permuation on a list. Following shows the usage of permutation predicate.

Get all permuatations.

| ?- permutation([a, b, c], P).

P = [a,b,c] ? a

P = [a,c,b]

P = [b,a,c]

P = [b,c,a]

P = [c,a,b]

P = [c,b,a]

no
| ?- 

Check a valid permutation.

| ?- permutation([a, b, c], [b, c, a]).

true ? a

no
| ?- 

Check a invalid permutation as length differs.

| ?- 
permutation([a, b, c], [b, c]).

no
| ?- 

Defining a Custom Permuation Predicate

As a permutation operation changes the list item positions and generate all possible outcomes. So we will create one predicate as list_perm(L1,L2), This will generate all permutation of L1, and store them into L2. To do this we need list_delete() clause to help.

To design this predicate, we can follow few observations as given below −

X is member of L if either −

  • If the first list is empty, then the second list must also be empty.

  • If the first list is not empty then it has the form [X | L], and a permutation of such a list can be constructed as, first permute L obtaining L1 and then insert X at any position into L1.

Program (list_repos.pl)

list_delete(X,[X|L1], L1).
list_delete(X, [Y|L2], [Y|L1]) :- list_delete(X,L2,L1).
list_perm([],[]).
list_perm(L,[X|P]) :- list_delete(X,L,L1),list_perm(L1,P).

Output

| ?- consult('D:/TP Prolog/Sample Codes/list_repos.pl').
compiling D:/TP Prolog/Sample Codes/list_repos.pl for byte code...
D:/TP Prolog/Sample Codes/list_repos.pl compiled, 3 lines read - 1062 bytes written, 3 ms

(16 ms) yes
| ?- list_perm([a,b,c],X).

X = [a,b,c] ? a

X = [a,c,b]

X = [b,a,c]

X = [b,c,a]

X = [c,a,b]

X = [c,b,a]

no
| ?- 

Explanation

  • list_delete(X,[X|L1], L1) covers the case where X is head of the list

  • list_delete(X, [Y|L2], [Y|L1]) :- list_delete(X,L2,L1) is recursive call where X is not head element of the list.

  • list_perm([],[]) is base of permutation.

  • list_perm(L,[X|P]) :- list_delete(X,L,L1),list_perm(L1,P) is a recursive call to list_delete() method to remove X from L and provide L1 as a sub List and then construct the permutation of L1 and insert P at any position in L1.

Advertisements