Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Find the number of players who roll the dice when the dice output sequence is given in C++
Suppose we have a string S and a number X. There are M different players who roll the dice. one player keeps on rolling the dice until he gets a number other than X. Here in the string S, S[i] represents the number at ith roll of a dice. We have to find the value of M. One constraint is that the last character in S will never be X. So for example, if string is “3662123” and X = 6, the output will be 5. This can be described as follows −
- First player rolls and got 3
- Second player rolls, and got 6, 6 and 2
- Third player rolls, and got 1
- Fourth player rolls, and got 2
- Fifth player rolls, and got 3
The task is simple, we will traverse the string, and count the number of characters, that are not X, the count will be the answer.
Example
#include<iostream>
using namespace std;
int countPlayers(string str, int x) {
int count = 0;
for (int i = 0; i < str.size(); i++) {
if (str[i] - '0' != x)
count++;
}
return count;
}
int main() {
string s = "3662123";
int x = 6;
cout << "Number of players: " << countPlayers(s, x);
}
Output
Number of players: 5
Advertisements
