In: Computer Science
In an effort to find something to do during self-quarantine,
your friend flips a coin many times and carefully records the
result of each flip in a character vector using either H or T.
Write a function named greatestRun that receives this character
array and then analyzes it to find the largest number of
consecutive heads or tails. It must return two values: (1) the
number corresponding to how many heads or tails were thrown in a
row and (2) the character H or T depending upon whether it was
Heads or Tails that was thrown the most times. In the event of a
tie for the longest run, return the character B for both
Please solve the Heads-or-Tails problem in C or C++ using either
Windows or Linux. Read the H-or-T data from
a below file or from STDIN. Report the result and related
statistics to STDOUT. Report any errors to
STDERR:
File: HTHHTTTHHTHHHTHTHTHHHHHTTHHHHHHHHHHHHTTTTTTTTTH
Code for the following question:-
#include <bits/stdc++.h>
using namespace std;
struct finalAns
{
std::string maxchar,count;
};
finalAns greatestRun(ifstream & point) //function asked in
question
{char ch;
struct finalAns a;
char prev;
int maxH=0,maxT=0;
int count=0;
while (point>>ch) //reading characters from text file into
char variable
{
if(count==0&&maxH==0&&maxT==0) //first
character
{
prev=ch;
count++;
continue;
}
if(prev==ch)
count++;
else // check for maxH and maxT each time the value changes from H
to or vice versa
{
if(prev=='H'&&count>maxH)
maxH=count;
if(prev=='T'&&count>maxT)
maxT=count;
count=1;
}
prev=ch;
}
if(prev=='H'&&count>maxH)
maxH=count;
if(prev=='T'&&count>maxT)
maxT=count;
//saving the final ans to struct variable a
std::string s ;
if(maxT>maxH) //T>H
{
a.maxchar='T';
s = std::to_string(maxT);
a.count=s;
}
else if(maxT<maxH) //H>T
{
a.maxchar='H';
s = std::to_string(maxH);
a.count=s;
}
else //draw
{
a.maxchar='B';
a.count='B';
}
return a;
}
int main()
{ ifstream point;
point.open("toss.txt");
struct finalAns x=greatestRun(point);
cout<<x.maxchar<<" "<<x.count;
return 0;
}
Screenshot of IDE:-
Screenshot of sample input file and output:-
*********************IN CASE OF ANY DOUBT FEEL FREE TO LEAVE A COMMENT*****************************