/* A program to implement josephus problem */
#include<stdlib.h>
#include<stdio.h>
#define MAX 20
typedef struct Q
{
int R,F;
int data[MAX];
}Q;
void initialise(Q *P);
int empty(Q *P);
int full(Q *P);
void enqueue(Q *P,int x);
int dequeue(Q *P);
int main()
{
Q q;
int m,n,i,j,x;
initialise(&q);
printf("\nEnter No. of children : ");
scanf("%d",&n);
printf("\nEnter Lucky Number : ");
scanf("%d",&m);
//create a queue of n children
for(i=1;i<=n;i++)
{
if(!full(&q))
enqueue(&q,i);
else
{
printf("\nQueue is full...");
exit(0);
}
}
//iterations to eliminate n-1 children
for(j=1;j<n;j++)
{
for(i=1;i<m;i++)//skip m-1 children
{
x=dequeue(&q);
enqueue(&q,x);
}
x=dequeue(&q);//remove mth child
}
x=dequeue(&q);//remove the winner
printf("\nWinner is child No. : %d",x);
}
void initialise(Q *P)
{
P->R=-1;
P->F=-1;
}
int empty(Q *P)
{
if(P->R==-1)
return(1);
return(0);
}
int full(Q *P)
{
if((P->R+1)%MAX==P->F)
return(1);
return(0);
}
void enqueue(Q *P,int x)
{
if(P->R==-1)
{
P->R=P->F=0;
P->data[P->R]=x;
}
else
{
P->R=(P->R+1)%MAX;
P->data[P->R]=x;
}
}
int dequeue(Q *P)
{
int x;
x=P->data[P->F];
if(P->R==P->F)
{
P->R=-1;
P->F=-1;
}
else
P->F=(P->F+1)%MAX;
return(x);
}
No comments:
Post a Comment