Monday, November 5, 2012

Find the string in sequence/set 1 for corresponding index in set 2

Problem Statement:

Two sets S1 and S2 exists .
S1 represent a set of string such that
S1 = { a,b,c, ..., z, aa,ab,ac,..,az,ba,bb,bc,..,bz,...,yz,aaa,aab,... }

Now S2 represents an array of index, such that:
S2 = { 0,1,2,3,... }

Find the corresponding entry in S1 for corresponding index in S2.

Ex:

S2       S1
0   ---> a
1   ---> b
:
:
:
25 ---> z
26 ---> aa

Solution in C :

<ankzcode> 

#include <stdio.h>

#define SIZE 1000

int main()
{
    int N=26,n=1255;
    char stack[SIZE];
    int top=-1;

    scanf("%d", &n);

    short flag=0;

    // As the characters are received in reverse orde
    // Store the values in Stack (LIFO)
    do{
        // Need to subtract -1 from only the last
        stack[++top] = 'a' + ((n%N)+(flag?-1:0));
        n /= N;
        if(n<N)flag = 1;
    }while(n);

    while(top>=0) {
        printf("%c",stack[top--]);
    }
    printf("\n");
    return 0;
}

</ankzcode> 

No comments:

Post a Comment