I am trying to replicate a type of elimination game where the user types in how many players there are in the game. The user will then decide who is the winner between two players. If one player loses twice, he/she is eliminated. To make it more clear, this is how it should look in the terminal:
Test case 1:
Enter the number of players: 4
Who won of players 1 and 2? 1
Who won of players 2 and 3? 3
Who won of players 3 and 4? 3
Who won of players 4 and 1? 1
2 players were eliminated!
Test case 2:
Enter the number of players: 6
Who won of players 1 and 2? 2
Who won of players 2 and 3? 3
Who won of players 3 and 4? 4
Who won of players 4 and 5? 5
Who won of players 5 and 6? 6
Who won of players 6 and 1? 1
0 players were eliminated!
The thing I am having trouble with is deciding how many players were eliminated. If a number is repeated twice then a variable, for instance counter, should be increased. How can I know how many times every number is repeated? I know how to do it with an array, but not like this. I also know how to check if a SPECIFIC number is repeated. But now I have to check every number that's inputted.
This is my code:
#include <iostream>
using namespace std;
void tumkrigare (int const num)
{
int winner {};
int counter {};
for (int i = 1; i <= num; i)
{
cout << "Who won of player "
<< i << " and ";
if (i == num)
{
cout << '1';
}
else
{
cout << i 1;
}
cout << "? ";
cin >> winner;
}
}
int main ()
{
int num {};
cout << "Enter players: ";
cin >> num;
tumkrigare(num);
return 0;
}
CodePudding user response:
Without giving too much away, consider that you can extend the approach of just having one counter to keep track of one variable to having multiple counters to keep track of multiple variables.
CodePudding user response:
A vector<bool> called failed_last_game initialized to a false for each player will work like you suggested. For each round, if a player loses and failed_last_game[player_number - 1] is true, you increment the number of eliminated players. Otherwise, you set failed_last_game[player_number - 1] to true. If a player wins, you set failed_last_game[player_number - 1] to false. This is quite a fast solution as it uses an index into a vector, but it is O(n) memory where n is the number of players. For such a small program, it should work well.
This works, because each player only plays 2 games each. You could get the wrong result if players played more than 2 times, losing 3 or more times in a row.
However, since you find out the results right after each other (except for player 1), you only need to remember recent results and the results for player 1 and can increment number_eliminated whenever a player is eliminated.
