Your task is to develop a circular linked-list based simulation of the Josephus problem. The
simulation will be text based. The user should be presented with a text-based menu asking him to
enter the total number of people (n), starting point (i), direction (clockwise/anti-clockwise) and
number to be skipped (k).
Let’s take an example.
• For n =15 (i.e. number of people is 15)
• k = 2 (i.e. every 2nd person is killed)
• starting point (i) = 1
• direction = clockwise
Initial scenario: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
After 1
st iteration: 1 3 5 7 9 11 13 15
After 2
nd iteration: 3 7 11 15
After 3rd iteration: 7 15
After 4th iteration: 15 (15 remains in the end). Program stops here.
#include <stdio.h>
int josephus(int n, int k)
{
if (n == 1)
return 1;
else
return (josephus(n - 1, k) + k - 1) % n + 1;
}
int main()
{
int n ;
printf("\nEnter total number of people: ");
scanf("%d",&n);
int i;
printf("\nEnter starting point: ");
scanf("%d",&i);
int k;
printf("\nEnter number to be skipped: ");
scanf("%d",&k);
printf("The chosen place is %d", josephus(n, k));
return 0;
}
Comments
Leave a comment