The beautiful princess Eve had many suitors. She decided on the following proced
ID: 641337 • Letter: T
Question
The beautiful princess Eve had many suitors. She decided on the following procedure to determine which suitor she would marry. First, all of the suitors would be lined up on after the other and assigned numbers. The first suitor would be number 1, the second number 2, and so on up to the last suitor, number n. starting at the first suitor she would then count three suitors down the line (because of the three letters in her name) and the third suitor would be eliminated from winning her hand and removed from the line. Eve would then continue, counting three more suitors, and eliminating every third suitor. When she reached the end of the line she would continue counting from the beginning.
For example, if there were six suitors then the elimination process would proceed as follows:
123456 initial list of suitors, start counting from 1
12456 suitor 3 eliminated, continue counting from 4
1245 suitor 6 eliminated, continue counting 1
125 suitor 4 eliminated, continue from 5
15 suitor 2 eliminated, continue from 5
1 suitor 5 eliminated, 1 is the lucky winner.
Write a program in C++ that creates a circular linked list of nodes to determine which position you should stand in to marry the princess if there are n suitors. Your program should simulate the elimination process by deleting the node that corresponds to the suitor that is eliminated for each step in the process.
Explanation / Answer
#include <iostream>
using namespace std;
struct node{
int val;
node *next;
};
node *newNode(int val){
node *newone = new node;
newone->val = val;
newone->next = NULL;
return newone;
}
int getWinPosition(node *head, int n){
int count = 1;
node *temp = head;
while(temp->next != temp){
count++;
if(count % n == 0){
temp->next = temp->next->next;
}
else{
temp = temp->next;
}
}
return temp->val;
}
int main(){
int n;
cout << "Number of suitors: ";
cin >> n;
if(n < 1){
cout << "Invalid Input: ";
return 0;
}
node *head = newNode(1);
node *temp = head;
for(int i = 1; i < n; ++i){
temp->next = newNode(i + 1);
if(i == n - 1){
temp->next->next = head;
}
temp = temp->next;
}
cout << "Winning position is " << getWinPosition(head, 3) << endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.