Problem with finding reapeateted values in a string and how many are
Posted 4 minutes ago
I am writing a Coin Flip Simulation program. In this program I need it to go through the string that I have "HHTHTHTHHTHHHHTH" and find where heads repeats then show you haw many times it repeats.

HHTHTHTHHTHHHHTH

Length
1
2
3
4

Number of runs on heads
3
2
0
1

10-23-2013, 11:55 PM

Fou-Lu

Is this a homework assignment? Its easy nontheless, but it dictates whether you would loop or find another solution (for homework, it'd likely be a loop). I'd probably loop anyways since its simple with a loop.

10-24-2013, 12:00 AM

jmurphy45

Quote:

Originally Posted by Fou-Lu

Is this a homework assignment? Its easy nontheless, but it dictates whether you would loop or find another solution (for homework, it'd likely be a loop). I'd probably loop anyways since its simple with a loop.

It is Homework but I do not under stand how you would loop to find what it is asking for.
This is what I have so far:public class CoinFlip
{
public static void main ( String[] args ){

Okay, in order to do a way to track a sequence, you will need to use an array. The problem is, that arrays are pre-set sizes of memory, and resizing them is a relatively annoying process.
On the other hand, you can track just a particular run. The process here involves a simple counter. Here's what you do:

This logic. That way you don't need to dedicate any additional memory.

If you need to record at any time, I'd probably stick with the H/T string (HTHHHHTTTHTH) approach, and then loop that as needed. Its a bit easier than handling an array, but not as easy as using a collection (which I'm guessing you have not covered).
A String in Java is little more than an object wrapper for a char array (its *not*, but its little more than that). Therefore, you can convert a string to a char array, and iterate it character by character. By doing so, you can then count the H sequence, and reset the count when the T is discovered (same logic as above, but now dealing with the char[] instead of the float/double). String tokenizing is also a relatively useful methodology that's often overlooked.

Are you expected to output in a particular fashion? Do you need to store it in any way?

11-10-2013, 06:40 PM

scpatton

you could make your program much simpler if you instead just used nested for loops and limited your random to 2 meaning it could only be 0, or 1.

then..

if (flip == 0) { heads++;}
else {tails ++;}

something like that^

then all you would have to do is use a while loop saying while flip = 0, increment another value that records the consecutive heads, and the same for tails.