Wednesday, April 9, 2014

Generate all possible unique 4 digit numbers such that no two adjacent numbers are the same and any number starting with 4 should end with a 4 .

Generate all possible unique 4 digit numbers such that no two adjacent numbers are the same and any number starting with 4 should end with a 4 . eg 1234 , 1232 are both correct but 1223 is not .



first we never get the value which start from 4 and end with for according to this question .
try to think that type of value .

we can do this simple by adding 1 to previous value or subtract 1 from previous value .

code-->


#include<stdio.h>

void generate(int arr[],int len){

if(len == 3 && arr[0]==4){
        if(arr[len-1]==3)
        arr[len++]=4;
        else
            return ;
}

if(len > 3){
    int i=0;
    for(i=0;i<4;i++)
        printf("%d",arr[i]);
        printf("\n");
        return ;
}



if(arr[len-1]<9){
    arr[len]=arr[len-1]+1;
     generate(arr,len+1);
}

if(arr[len-1]>0){
    arr[len]=arr[len-1]-1;
     generate(arr,len+1);
}

return ;
}

void main(){

int no[]={-1,-1,-1,-1};
int i;
for(i=1;i<=9;i++){
int len=0 ;
no[len]=i;
generate(no,len+1);
}
}

No comments:

Post a Comment