Hi Guys,
Here is the code to find the next permutation of given string. I used the algorithm mentioned by
Career Cup and this is solution to
IARCS.
So Here is the solution
#include
void
nextPermutation(
char
a[],
int
size);
main()
{
int
Size;
int
length;
char
size[5];
char
string[2000];
int
i=0;
int
j=0;
int
k =0;
int
temp = 0;
char
tempstring[1000];
fgets
(size,5,stdin);
Size = size[2] -
'0'
;
length = size[0] -
'0'
;
for
(i=0;i < Size; i++)
{
fgets
(string,2000,stdin);
j = k = 0;
while
(j<2000 amp="" code="" j="" string="">'\0'
)
2000>
{
if
(string[j] != 32)
{
tempstring[k] = string[j];
tempstring[++k] =
'\0'
;
}
++j;
}
nextPermutation(tempstring,--k);
}
}
void
nextPermutation(
char
arr[],
int
length)
{
int
i=0;
int
temp = 0;
int
pos, maxpos;
pos = maxpos = -1;
for
(i=0; i
{
if
(arr[i] < arr[i+1])
{
pos = i;
}
}
if
(pos == -1)
{
printf
(
"No next Permutation exist\n"
);
return
;
}
for
(i=pos+1;i < length;i++)
{
if
(arr[pos] < arr[i])
maxpos = i;
}
temp = arr[pos];
arr[pos] = arr[maxpos];
arr[maxpos] = temp;
for
(i=pos+1;i
{
temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
printf
(
"So the next string is \n"
);
for
(i=0;i
printf
(
"%d "
,arr[i]-
'0'
);
printf
(
"\n"
);
}