## Josephus Algorithm

The problem is described as, “If there are n persons standing in a circle.  Beginning from any person, the others are numbered in a particular direction (clockwise or anti-clockwise).  Then a random number, n is generated.  The counting begins from the person numbered as one upto n.  The nth person is removed from the game so that total number of persons in the circle gets reduced by one.  The same process is continued until one person remains in the circle, who is declared to be the winner.  Circular linked list may be used for representing this problem, which is codified below:

/*Josephus algorithm*/

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>

struct clist
{
int id;
char name[45];
struct clist *next;

void create()
{
ptr=(struct clist *)malloc(sizeof(struct clist));
if(ptr==NULL)
{
printf(“Memory Allocation Error!”);
exit(1);
}
}

void makenode(int pid,char nm[])
{
create();
ptr->id=pid;
strcpy(ptr->name,nm);
ptr->next=NULL;
}

void insertend()
{
{
}
else
temp=temp->next;
temp->next=ptr;
}
}

void display()
{
{
printf(“List is empty.”);
return;
}

{
return;
}
printf(“(%d,%s)->”,temp->id,temp->name);
temp=temp->next;
{
printf(“(%d,%s)->”,temp->id,temp->name);
temp=temp->next;
}
printf(“bb “);
}

void playgame()
{
int m,i;
struct clist *tmp;
printf(“Enter the value of counter m?”);
scanf(“%d”,&m);
while(temp!=temp->next)
{
for(i=0;i<m-1;i++)
temp=temp->next;
tmp=temp->next;
temp->next=tmp->next;
free(tmp);
}
printf(“Winner of the Game is: (%d,%s)”,temp->id,temp->name);
getch();
}

void main()
{
int choice,id;
char name[45];
while(1)
{
clrscr();
printf(“ntWhat to do”);
printf(“nnt1. Generate Circular list of persons”);
printf(“nt2. Display List of persons”);
printf(“nt3. Play the Game”);
printf(“nt4. Exit”);
scanf(“%d”,&choice);
switch(choice)
{
case 1:
printf(“nEnter person id?”);
scanf(“%d”,&id);
printf(“nEnter person name?”);
scanf(“%s”,name);
makenode(id,name);
insertend();
break;
case 2:
display();
getch();
break;
case 3:
playgame();
break;
case 4:
exit(0);
default:
printf(“nInvalid choice.”);
}
}
}