Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

164 Define a recursive function vector<string > flip(int n); that returns a vect

ID: 3763653 • Letter: 1

Question

164

Define a recursive function

vector<string > flip(int n);

that returns a vector containing all possible strings of length n made out of H's and T's.

These strings represent the possible outcomes when we flip a coin n times.

For example, flip(3) would return a vector containing the eight strings TTT, HTT, HHT, THT, THH, HHH, HTH and TTH (not necessarily in that order) .

The driver takes input n and outputs the elements of flip(n), sorted in alphabetical order.

Your version of flip() may produce the elements in any order, as long as it contains the correct strings .

Suggested algorithm: If n is zero, return a vector containing just the empty string . Otherwise call the function recursively with input n-1 and save the result in variable temp1. Copy temp1 into temp2. Append 'H' to the end of allelements in temp1 and 'T' to the end of all element in temp2. Add the elements of temp2 to the end of temp1 and return temp1.

You may call the functions appendAll() and addElements() from other exercises. (They are available, you don't need to code them here.)

Explanation / Answer

Answer :

import java.util.Scanner;

public class HeadTailFlip{

public void flip(){

int headCounter = 0;
int tailCounter = 0;
int hCounter = 0;
int tCounter = 0;


Scanner input = new Scanner(System.in);

System.out.println("Enter the number of runs (1 - 100,000): ");
int r = input.nextInt();

System.out.println("Enter the number of flips per run (1 - 20): ");
int f = input.nextInt();

if(r>0 && f>0) {
if(r<=100000 && f<=20) {
for (int run = 0; run < r; run++) {
for (int flip = 0; flip < f; flip++)

if(Math.random() < 0.5) {
System.out.print("H ");
tCounter = 0;
hCounter++;
}
else {
System.out.print("T ");
hCounter = 0;
tCounter++;
}


if(hCounter == f) {
//System.out.print(" << ALL HEADS >>");
headCounter++;
}
else if(tCounter == f) {
//System.out.print(" << ALL TAILS >>");
tailCounter++;
}

System.out.println();
hCounter = 0;
tCounter = 0;

}
}
else
{
System.out.println("Please check your entry and try again.");
return;
}
}
else
{
System.out.println(" Runs and flips must be greater than 0!");
return;
}

System.out.println();
  
}

public static void main(String[] args) {

HeadTailCounter coin = new HeadTailCounter();

coin.flip();
}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote