Write a program to solve the Josephus problem, with the following modification:
ID: 3542685 • Letter: W
Question
Write a program to solve the Josephus problem, with the following modification: Sample Input: ./a.out n m p where n is the number of players and m is the count used for every odd turn while p is the count used for every even turn. ./a.out 5 2 3 Sample Output: Round 1: 1 -> 3 -> 4 -> 5 Round 2: 1 -> 3 -> 4 Round 3: 1 -> 4 Round 4: 1 Winner is 1.
#include <iostream> #include <cstdlib> using namespace std; struct node { int key; node *next;}; int main(int argc, char* argv[]){ if(argc >2) { int i, N = atoi(argv[1]), M = atoi(argv[2]); node *t, *x; t = new node; t->key = 1; x = t; for(i = 2; i<=N; i++){ t->next = new node; t = t->next; t->key = i; } t->next = x; while(t != t->next){ for(i = 1; i<M; i++) t = t->next; cout << t->next->key<<" has dropped out "<< endl; x = t->next; t->next = x->next; delete x; } cout << "winner is " << t->key << endl; } return 0; }
Explanation / Answer
#include #include using namespace std; struct node { int key; node *next;}; int main(int argc, char* argv[]){ if(argc >3) { int i, N = atoi(argv[1]), M = atoi(argv[2]);P=atoi(argv[3]); node *t, *x; t = new node; t->key = 1; x = t; for(i = 2; inext = new node; t = t->next; t->key = i; } t->next = x; int rounds=0; while(t != t->next){ rpounds=rounds+1; if(rounds%2==0){ for(i = 1; inext; cout keyRelated Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.