Wednesday, December 25, 2013

Q. N persons are standing in a circle and play a game which starts from 1. In this game we are passing each other baton and after count of D which ever person holds that baton is out from the game and then the game begins from the next person in the circle. Print the order in which the people gets out.

INPUT  N=5,  D=2;

OUTPUT:  2,4,1,5,3

First  2  gets  out  then  4  so  we  left  with  1  3  5
Game  starts  with  5  and  hence  1  gets  out  and  game  goes  like  that.........



Solution:-  We  are  initializing  an  array  with  size  N  with  a[i]=i;

Now  we  are  counting  (prevIndex+D)%length;  length--;  is  the  next  element  to  be  removed

length  is  updated  dynamically

And  the  element  removed  is  printed...

#include<stdio.h>

void remove(int*,int,int);

void remove(int *arr,int k,int n)
{
for(int i=k+1;i<n;i++)
    arr[i-1]=arr[i];
}


int main()
{
        int n=12;
        int d=2;
        int arr[n];
        int length=n;
        int v=0;
     
        for(int k=0;k<n;k++)
        arr[k]=k+1;  
     
     
        while(1)
        {
                if(length==1)
                break;
         
             if(v!=0)
                v=v+d-1;
                else
                v=v+d;
             
                if(v%length!=0 || v==0)
                v=v%length;
                else
                v=length;
     
     
        printf("%d\n",arr[v-1]);
     
        if(v!=0)
        remove(arr,v-1,length);
        else
        remove(arr,v,length);
     
        length--;
     
        if(v>length)
        v=0;
     
        }
        printf("%d",arr[0]);  
        return 0;
}

If  you  fell  asking  anything  please  tell  me  anytime....


No comments:

Post a Comment