Question: In this array implementation of josephus election, add a function to access and display the list of numbers before it reaches the last element. //Josephus

In this array implementation of josephus election, add a function to access and display the list of numbers before it reaches the last element.

//Josephus Problem

#include

#include

using namespace std;

//continue around the circle eliminating every nth soldier until

// all of the soldiers have been eliminated

int main(int argc, char *argv[])

{

//delcaring i,N,M as int

int i;

int N;

int M;

//getting N and M from the user/keyboard

// get the initial number of soldiers

//enter the element to be deleted(which soldier should be killed)

cout << "Enter the number of elements: ";

cin >> N ;

cout << "Enter the element to be deleted: ";

cin >> M;

//number of elements in the array is N

//load the initial list of soldiers

int count = N;

int array[N];

for(int i = 0; i < N; i++)

array[i] = i+1;

int current = 0;

int temp = 0;

//after delcaring number of elements

//remove every nth element until the list is empty

//the while loop below counts and eliminate every 5th element

while(count != 1)

{

if(array[current] != 0)

temp++;

current++;

if(current == N)

current = 0;

if(temp >= M-1 && array[current] != 0)

{

temp = 0;

array[current] = 0;

count--;

}

}

for(int i = 0; i < N; i++)

if(array[i] != 0)

{

cout << "Last element left is: ";

cout << array[i] << endl;

break;

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!