Find the number of players who roll the dice when the dice output sequence is given
Given a string S and a number X. There are M players who roll the dice. A player keeps on rolling the dice until he gets a number other than X. In the string S, S[i] represents the number at ith roll of a dice. The task is to find M. Note that the last character in S will never be X.
Examples:
Input: s = “3662123”, X = 6
Output: 5
First player rolls and gets 3.
Second player rolls and gets 6, 6 and 2.
Third player rolls and gets 1.
Fourth player rolls and gets 2.
Fifth player rolls and gets 3.
Input: s = “1234223”, X = 2
Output: 4
Approach: Iterate in the string and count the characters which are not X. The number of characters which are not X will be the number of players.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findM(string s, int x)
{
int cnt = 0;
for ( int i = 0; i < s.size(); i++) {
if (s[i] - '0' != x)
cnt++;
}
return cnt;
}
int main()
{
string s = "3662123" ;
int x = 6;
cout << findM(s, x);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int findM(String s, int x)
{
int cnt = 0 ;
for ( int i = 0 ; i < s.length(); i++)
{
if (s.charAt(i) - '0' != x)
cnt++;
}
return cnt;
}
public static void main(String args[])
{
String s = "3662123" ;
int x = 6 ;
System.out.println(findM(s, x));
}
}
|
Python3
def findM(s, x):
cnt = 0
for i in range ( len (s)):
if ( ord (s[i]) - ord ( '0' ) ! = x):
cnt + = 1
return cnt
if __name__ = = '__main__' :
s = "3662123"
x = 6
print (findM(s, x))
|
C#
using System;
class GFG
{
static int findM(String s, int x)
{
int cnt = 0;
for ( int i = 0; i < s.Length; i++)
{
if (s[i] - '0' != x)
cnt++;
}
return cnt;
}
public static void Main()
{
String s = "3662123" ;
int x = 6;
Console.Write(findM(s, x));
}
}
|
PHP
<?php
function findM( $s , $x )
{
$cnt = 0;
for ( $i = 0; $i < strlen ( $s ); $i ++)
{
if (ord( $s [ $i ]) - ord( '0' ) != $x )
$cnt ++;
}
return $cnt ;
}
$s = "3662123" ;
$x = 6;
echo findM( $s , $x );
?>
|
Javascript
<script>
function findM( s , x) {
var cnt = 0;
for (i = 0; i < s.length; i++) {
if (s.charCodeAt(i) - '0' .charCodeAt(0) != x)
cnt++;
}
return cnt;
}
var s = "3662123" ;
var x = 6;
document.write(findM(s, x));
</script>
|
Time Complexity: O(N), as we are using a loop to traverse N times. Where N is the length of the string.
Auxiliary Space: O(1), as we are not using any extra.
Last Updated :
21 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...