
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- C++ code to find minimum number starting from n in a game
- C++ Program to find out if a person has won lottery
- C++ code to find who cannot give sufficient candies
- C++ code to find final number after min max removal game
- C++ code to find out if an image is B/W or color
- C++ code to find out number of battery combos
- C++ code to find out which number can be greater
- C++ code to count who have declined invitation
- C++ code to find tree height after n days
- C++ code to find screen size with n pixels
- C++ code to find out if a grid is fully accessible
- C++ code to find out if everyone will get ice cream
- C++ code to find minimum different digits to represent n
- C++ code to find out the sum of the special matrix elements
- C++ code to find out the total amount of sales we made

Advertisements