Introduction
You will see how to solve Josephus problem using pointer in C program. So, I am going to use C program as well as pointer to solve Josephus problem.
The Josephus problem (or Josephus permutation) is a theoretical problem related to a certain counting-out game. The problem is described as below.
People are standing in a circle waiting to be executed. Counting begins at a specified point in the circle and proceeds around the circle in a specified direction. After a specified number of people are skipped, the next person is executed.
The procedure is repeated with the remaining people, starting with the next person, going in the same direction and skipping the same number of people, until only one person remains, and is freed.
Related Posts:
- Solving Josephus problem using PHP
- Solving Josephus problem using Java
- Solving Josephus Problem using Pythonc
Implementation of Josephus Problem
The implementation of Josephus problem is given below using C program and pointer.
The n
is the number of persons or people in the circle and k
is the start position of execution.
#include <stdio.h>
#include <stdlib.h>
typedef struct person {
int position;
struct person *next;
}person;
int main() {
int w = findWinner(5, 3);
printf("Winner: %d", w);
w = findWinner(10, 3);
printf("\nWinner: %d", w);
w = findWinner(5, 2);
printf("\nWinner: %d", w);
w = findWinner(7, 3);
printf("\nWinner: %d", w);
return 0;
}
int findWinner(int n, int k) {
int i, counter;
person *p, *q, *r;
p = (person*) malloc(sizeof(person));
p->position = 1;
p->next = p;
q = p;
for(i=2; i<=n; i++) {
r = (person*) malloc(sizeof(person));
r->position = i;
r->next = p;
q->next = r;
q = r;
}
while(p->next != p) {
q = p;
r = q;
for(counter = 1; counter<k; counter++) {
r = q;
q = q->next;
}
r->next = q->next;
p = r->next;
q->next = NULL;
free(q);
q = NULL;
}
return p->position;
}
Testing the Program
By executing the above C program you will get the following output:
Winner: 4
Winner: 4
Winner: 3
Winner: 4
Ananlysis of the Logic
Let’s take an example of there are 5 people in a circle and execution starts clockwise at position 3, so I will find out the winner of the game.
So there are five people – 1 2 3 4 5 and execution starts clockwise at position 3. Therefore if you kill 3 then are left with the list something like – 1 2 4 5.
Now again, you want to kill the person at position 3 clockwise counting from the last killed person.
Now, you need to execute the person at position 1. So executing the person at 1, you are left with the list 2 4 5. After executing another person, you get list 2 4.
Now, you are left with 2 persons in the list. So, you have to calculate the position wisely to execute the person.
So finally the winner is 4.