r/codehs • • May 19 '21

THIS IS SO ANNOYING

So my code works and counts the head streaks EXCEPT for when it reaches "Longest streak of heads: 3" instead my code prints out "Longest streak of heads: 6" HELP ME please help me HELP

var NUM_FLIPS = 40;

var Heads = "Heads";

var Tails = "Tails";

function start(){

var flips = flipCoins();

printArray(flips);

longestHeadsStreak(flips);

}

// This function should flip a coin NUM_FLIPS

// times, and add the result to an array. We

// return the result to the caller.

function flipCoins(){

var flips = \[\];

for(var i = 0; i < NUM_FLIPS; i++){

	if(Randomizer.nextBoolean()){

		flips.push("Heads");

	}else{

		flips.push("Tails");

	}

}

return flips;

}

function printArray(arr){

for(var i = 0; i < arr.length; i++){

	println(i + ": " + arr\[i\]);

}

}

function longestHeadsStreak(flips){

var countHeads = 0;

var countTails = 0;

for(var i = 0; i < flips.length; i++){

if(flips[i]=="Heads"){

countHeads+=1;

}else{

countTails+=1;

}

}

println("Longest Streak of Heads: " + countHeads);

}

5 Upvotes

6 comments sorted by

3

u/_andy_andy_andy_ May 19 '21

you’re not counting a streak, just the total number of heads. you need to count the number of heads in a row

1

u/nathan_burbu May 19 '21

But how

1

u/_andy_andy_andy_ May 19 '21

any time you find a coin that’s not heads the length of your streak should go back to 0

1

u/fortpro87 Aug 16 '22

Then what happens when you pull 99 heads then the last is tails

Your streak should be 99 but it resets down to zero

1

u/Particular-Metal-655 Jun 28 '24

okay. i'll show you longeststreak.java:

public class LongestStreak extends ConsoleProgram

{

public static final int FLIPS = 100;

public void run()

{

int Streak = 0;

int Longest_Streak = 0;

for (int i = 0; i < FLIPS; i++)

{

if (Randomizer.nextBoolean())

{

System.out.println("Heads");

Streak++;

}

else // false -> tails

{

System.out.println("Tails");

Streak = 0;

}

if (Streak > Longest_Streak)

{

Longest_Streak = Streak;

}

}

System.out.println("Longest streak of heads: " + Longest_Streak);

}

}