Permutations: Difference between revisions
Content added Content deleted
(→{{header|Erlang}}: Replace algorithm with more efficient one.) |
(→{{header|C}}: simplify) |
||
Line 272: | Line 272: | ||
=={{header|C}}== |
=={{header|C}}== |
||
See [[wp:Permutation#Systematic_generation_of_all_permutations|lexicographic generation]] of permutations. |
|||
Iterative method. Given a permutation, find the next in lexicographic order. Iterate until the last one. |
|||
Here the main program shows letters and is thus limited to permutations of 26 objects. The function computing |
|||
next permutation is not limited. |
|||
<lang c>#include <stdio.h> |
<lang c>#include <stdio.h> |
||
#include <stdlib.h> |
#include <stdlib.h> |
||
⚫ | |||
/* Find next permutation in lexicographic order. |
|||
# define swap(i, j) {t = a[i]; a[i] = a[j]; a[j] = t;} |
|||
Return -1 if already the last, otherwise 0. |
|||
⚫ | |||
A permutation is an array[n] of value between 0 and n-1. */ |
|||
⚫ | |||
/* 1. Find the largest index k such that a[k] < a[k + 1]. If no such |
|||
⚫ | |||
index exists, the permutation is the last permutation. */ |
|||
⚫ | |||
for (k = n - 1; k && a[k - 1] >= a[k]; k--); |
|||
t = 0; |
|||
⚫ | |||
⚫ | |||
if(perm[i] < perm[i+1]) { |
|||
t = 1; |
|||
break; |
|||
} |
|||
} |
|||
/* last permutation if decreasing sequence */ |
|||
if(!t) { |
|||
⚫ | |||
} |
|||
/* swap tail decreasing to get a tail increasing */ |
|||
for(j=i+1; j<n+i-j; j++) { |
|||
t = perm[j]; |
|||
perm[j] = perm[n+i-j]; |
|||
perm[n+i-j] = t; |
|||
} |
|||
/* find min acceptable value in tail */ |
|||
k = n-1; |
|||
⚫ | |||
if((perm[j] < perm[k]) && (perm[j] > perm[i])) { |
|||
k = j; |
|||
} |
|||
} |
|||
/* swap with ith element (head) */ |
|||
t = perm[i]; |
|||
perm[i] = perm[k]; |
|||
perm[k] = t; |
|||
/* 2. Find the largest index l such that a[k] < a[l]. Since k + 1 is |
|||
⚫ | |||
such an index, l is well defined */ |
|||
⚫ | |||
/* 3. Swap a[k] with a[l] */ |
|||
swap(k, l); |
|||
/* 4. Reverse the sequence from a[k + 1] to the end */ |
|||
⚫ | |||
swap(k, l); |
|||
⚫ | |||
} |
} |
||
⚫ | |||
int main(int argc, char **argv) { |
|||
char a[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; |
|||
if (argc < 2) { |
|||
⚫ | |||
int i, n, *perm; |
|||
⚫ | |||
⚫ | |||
⚫ | |||
return 1; |
|||
} |
} |
||
⚫ | |||
perm = (int *)calloc(n, sizeof(int)); |
|||
for(i=0; i<n; i++) { |
|||
perm[i] = i; |
|||
} |
|||
do { |
|||
for(i=0; i<n; i++) { |
|||
printf("%c", perm[i] + 'A'); |
|||
} |
|||
printf("\n"); |
|||
} while(!nextperm(n, perm)); |
|||
free(perm); |
|||
⚫ | |||
}</lang> |
|||
⚫ | |||
Sample result : |
|||
⚫ | |||
if (n > 26) n = 26; |
|||
do { printf("%.*s\n", n, a); } while(next_perm(n, a)); |
|||
perm 3 |
|||
⚫ | |||
}</lang>output<lang>% ./a.out 3 |
|||
ABC |
ABC |
||
ACB |
ACB |
||
Line 352: | Line 319: | ||
BCA |
BCA |
||
CAB |
CAB |
||
CBA |
CBA</lang> |
||
=={{header|C++}}== |
=={{header|C++}}== |