Permutations: Difference between revisions

Line 1,063:
(u+z ] a 2.)
(u+z ] 2 a.)</pre>
 
=={{header|C}}==
Full non-recursive algorithm generating permutation in reversed lexicographical order. Taken from here: [https://habrahabr.ru/post/310574/]. It's a little bit modified algorythm of Narayana Pandit [3]. It reveres a string and works until a and b are not equal. It searches a new permutation directly (first internal cycle) as we do it on a sheet of paper. You can use English alphabet instead of digits. Author: I. Gavryushin aka dcc0. Run it from console with a parametr like "program.o 12345" or "program.o abcd":
<lang c>
 
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
 
//This reverse x. Переворачиваем х
char revstring(char * x) {
int i = strlen(x);
int k=0;
char c;
while( i > k ) {
i--;
c=x[k];
x[k]=x[i];
x[i]=c;
k++;
}
}
//This cut x
char subb (char * x, int i) {
x[i]='\0';
}
//This cut y
char subb2 (char * y, int i) {
int k = 0;
while (k != strlen(y)+1) {
y[k]=y[i];
i++;
k++;
}
}
//It gets an argumet like 1234 or abcd. All symbols must be uniqe
int main (int argc, char *argv[]) {
if (argc < 2) {
printf("Enter an argument. Example 1234");
return 0;
}
char b[strlen(argv[1])];
char a[strlen(argv[1])];
int ij=0;
while (ij!=strlen(argv[1])) {
a[ij]=argv[1][ij];
b[ij]=argv[1][ij];
ij++;
}
a[ij]='\0';
b[ij]='\0';
revstring(a);
printf("%s\n", a);
int i;
int j;
char c;
while (strcmp (a, b) !=0 ) {
i=1;
while(a[i] > a[i-1]) {
i++;
}
j=0;
while(a[j] < a[i]) {
j++;
}
c=a[j];
a[j]=a[i];
a[i]=c;
char x[strlen(a)+1];
char y[strlen(a)+1];
strcpy(x,a);
strcpy(y,a);
subb(x, i);
revstring(x);
subb2(y, i);
sprintf(a, "%s%s", x,y);
printf("%s\n", a);
}
}
</lang>
 
=={{header|C}}==
Anonymous user