Archive for category Algorithm
The next higher permutation problem
We start with a problem : Given an integer find the next highest integer having the same digits.
Or, in essence – find the next highest permutation. How to do so?
We note that the whole notion of permutation acts this way.
You need to traverse the integer from the least significant digit to the highest.
If you can see that anywhere you can have a number (digit ) at place (C-1) smaller than the current number ( digit ) (C) – you know you can create a higher permutation.
But which one? Now take a look around the right side of that current number.
Can we see find a smallest number which is bigger than the number at C-1 place?
If we can find, then we swap that number with the number at C-1, and then from location C sort the right side of the number treating it as array of digits.
That is all there is.
/*************************
Big mystery of the universe is next highest permutation
We solve it here. Just for the sake of fun.
I do not care if this is un-optimal - it does the work
The sorting can be easily improved by counting sort,
but let's not get there
**************************/
#include <stdio.h>
#include <string.h>
// pointless to malloc?
char buf[64];
// We all know what it is
void swap(char* ptr, int i, int j){
char c = ptr[i];
ptr[i] = ptr[j];
ptr[j] = c;
}
// Also we know what this does - sort from position from
void sort ( char* ptr, int from , int len ){
for ( int i = from ; i < len; i++ ){
for ( int j = i + 1; j < len; j++ ){
if ( ptr[i] > ptr[j] ){
swap(ptr,i,j);
}
}
}
}
// This is interesting, finds the next highest digit of 'gt' from position 'me'.
int find_next_highest(char* ptr, char gt , int me, int len){
int index = me;
char nh = ptr[me];
for ( int i = me+1; i < len; i++){
if ( gt < ptr[i] && nh > ptr[i] ){
nh = ptr[i];
index = i ;
}
}
return index;
}
char* get_next_permutation(const char* sn){
sprintf(buf, "%s",sn);
int len = strlen(buf);
for ( int i = len -1 ; i >0 ; i--){
if ( buf[i] > buf[i-1] ){ // Now we need to do something
// find the one which needs to be swapped
int index = find_next_highest( buf, buf[i-1], i, len);
// swap it
swap( buf, i-1, index );
// now sort the right side to generate the absolute min on that
sort( buf , i, len );
// I am done after this
break;
}
}
return buf;
}
int main(int argc, const char** argv){
char* ptr = get_next_permutation(argv[1]);
printf("%s\n", ptr);
return 0;
}