Anonymous user
Permutations: Difference between revisions
→{{header|C}}: simplify
(→{{header|Erlang}}: Replace algorithm with more efficient one.) |
(→{{header|C}}: simplify) |
||
Line 272:
=={{header|C}}==
See [[wp:Permutation#Systematic_generation_of_all_permutations|lexicographic generation]] of permutations.
<lang c>#include <stdio.h>
#include <stdlib.h>
# define swap(i, j) {t = a[i]; a[i] = a[j]; a[j] = t;}
▲int nextperm(int n, int *perm) {
/* 1. Find the largest index k such that a[k] < a[k + 1]. If no such
▲ int i,j,k,t;
index exists, the permutation is the last permutation. */
for (k = n - 1; k && a[k - 1] >= a[k]; k--);
if (!k--) return 0;▼
for(i=n-2; i>=0; i--) {▼
return -1;▼
for(j=n-2; j>i; j--) {▼
/* 2. Find the largest index l such that a[k] < a[l]. Since k + 1 is
▲ return 0;
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) {▼
▲ printf("perm n (1 <= n <= 26\n");
}
n = strtol(argv[1], NULL, 0);▼
▲ return 0;
if (n > 26) n = 26;
do { printf("%.*s\n", n, a); } while(next_perm(n, a));
}</lang>output<lang>% ./a.out 3
ABC
ACB
Line 352 ⟶ 319:
BCA
CAB
CBA</lang>
=={{header|C++}}==
|