 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ code to find out who won an n-round game
Suppose, there is a two-player game that has n rounds. The scores of the rounds are given in an array 'scores' where each element is of the format {P1 Score, P2 Score}. The player with the higher score wins a round, and a player wins the game if they have won more rounds; otherwise, it is declared as a draw. So, given the scores, we have to find out who has won the game.
So, if the input is like n = 4, scores = {{4, 3}, {3, 2}, {5, 6}, {2, 5}}, then the output will be Draw.
Steps
To solve this, we will follow these steps −
res := 0 while n is non-zero, do: a := first value of scores[n] b := second value of scores[n] res := res + ((if a > b, then 1, otherwise (if a < b, then -1, otherwise 0))) n := n - 1 return (if res > 0, then "P1", otherwise (if res < 0, then "P2", otherwise "Draw"))
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; #define N 100 string solve(int n, vector<pair<int, int>> scores) {    int res = 0;    while(n--){       int a = scores[n].first;       int b = scores[n].second;       res += (a > b ? 1 : (a < b ? -1 : 0));    }    return res > 0 ? "P1" : (res < 0 ? "P2" : "Draw"); } int main() {    int n = 4;    vector<pair<int, int>> scores = {{4, 3}, {3, 2}, {5, 6}, {2,5}};    cout<< solve(n, scores);    return 0; } Input
4, {{4, 3}, {3, 2}, {5, 6}, {2, 5}}  Output
Draw
Advertisements
 