Sunday, August 7, 2011

Program to Flip a Coin (until you get 3 "heads" in a row):

"Write a program that simpulates flipping a coin repeatedly and continues until three consecutive heads are tossed. At that point your program should display the total number of times the coin was flipped." (Roberts ch 6, problem 2).

What it looks like:



/*
/* File: FlipThreeHeads.java
 * ----------------------------
 * This program simulates flipping coin repeatedly until you get 3 heads in a row, at which point you
 * print how many flips it took to get those 3. It uses an instance of the RandomGenerator class and keeps count using a local variable 'count.'
 */

import acm.program.*;
import acm.util.*;
public class FlipThreeHeads extends ConsoleProgram{
 
    public void run() {
     
        // Placeholders X, Y and Z to store the most recent flip and the past 2 flips (when they happen):
        String flipX = flipCoin(); 
        println(flipX);
        String flipY = null;
        String flipZ = null;
        
        // Local variable to keep track of how many flips we've done so far:
        int count = 1;
  
       //"As long as X, Y and Z aren't equal to each other and aren't 'heads'..."
        while ((flipX != flipY) || (flipX != flipZ) || (flipZ != "heads")){
            count += 1;
            String nextCoin = flipCoin();
            println(nextCoin);
            //Shove down the values of the placeholders to make flipX the most recent result  
            flipZ = flipY;
            flipY = flipX;
            flipX = nextCoin;
        }
        println("It took " + count + " tries to get 3 consecutive heads.");  
    }
 
    private RandomGenerator rgen = RandomGenerator.getInstance();

    private String flipCoin() {
        boolean booleanResult = rgen.nextBoolean();
  
        String flipResult;
        if (booleanResult == true) {
            flipResult =  "heads";
        } else {
            flipResult = "tails";
        }
        return flipResult;
    }
}

What made this hard/interesting:

Naming things is hard! Because this program requires that you keep track of the 3 most recent flips so that you can compare them and see if there were 3 heads in a row, you have to create a lot of variables. However, I kept being tempted to use variable names like "flipCoin" and "nextFlip" since they all do similar things related to the actual coin flip. If there's a way to make this program more spartan and not use as many variables that would be great.

Here's how a run of the program works and each step needs its own variable or set of variables:

1) You establish 3 local variables "flipX," "flipY" and "flipZ." As we keep flipping our programmatic coin these will keep track of the 3 latest flips. We will build a shove-over mechanism so that with each new coin flip, we'll turn flipX into the latest result, turn flipY into the old value for flipX, and turn flipZ into the old value for flipY.

Also, you create flipX with an initial value by calling the flipCoin() method.

2) The flipCoin() method is a private method that we call that just simulates flipping a coin. It works by pulling a random boolean out of our RandomGenerator instance and translating the returned "true" or "false" into "heads" or "tails."

3) booleanResult is a local variable inside the flipCoin() method that stores the "true" or "false" that gets returned from calling nextBoolean(). flipResult is a local variable that takes the boolean and stores the "head" or "tail" translation.

4) nextCoin is part of our main method and always stores the most recent flip. We keep resetting it as we keep on flipping coins (and resetting flipX to equal it and going on with the shove-down mechanism described in step (1).

The "flipCoin" method was particularly hard to make up names for inside because there are 3 variables that mean essentially the same thing (those that turned out to be called "flipResult," "booleanResult" and "flipCoin." I kept on being tempted to name them "flipResult", but all the distinct variables are necessary in order to return the desired result.

57 comments:

  1. There is an interesting similarity between this problem and the Fibonacci one.. Thanks for the solution.. I could not get the right while loop conditions, but thanks to your answer... i see the light

    ReplyDelete
  2. Everything is very open with a very clear clarification of the challenges.
    It was definitely informative. Your site is very useful. Thanks for sharing!


    Feel free to surf to my blog post - theme pro wordpress
    my webpage :: purchase wordpress theme

    ReplyDelete
  3. Hey there! I understand this is somewhat off-topic but I needed to ask.
    Does managing a well-established website such as yours take a lot of work?

    I am brand new to blogging but I do write in my diary everyday.
    I'd like to start a blog so I will be able to share my experience and views online. Please let me know if you have any recommendations or tips for new aspiring bloggers. Appreciate it!
    My web blog :: smoking drug

    ReplyDelete
  4. Thanks , I have just been looking for info about
    this subject for a long time and yours is the greatest I've found out so far. But, what about the conclusion? Are you certain in regards to the supply?

    Here is my website :: low carb brot rezept

    ReplyDelete
  5. I always used to read paragraph in news papers but now as I am a user of net therefore from
    now I am using net for articles or reviews, thanks to web.



    Also visit my website; rezept low carb brot

    ReplyDelete
  6. WOW just what I was searching for. Came here by searching for olivia

    my webpage ... paleo ernährung
    My page :: diät rezepte frühstück

    ReplyDelete
  7. I do not even know how I ended up here, but I thought this post was great.
    I don't know who you are but definitely you're going to a famous blogger if
    you are not already ;) Cheers!

    My homepage :: Low Carb Diät Erfahrungen

    ReplyDelete
  8. It's going to be finish of mine day, but before finish I am reading this impressive post to increase my know-how.

    Also visit my homepage :: carb diät

    ReplyDelete
  9. It's very effortless to find out any topic on web as compared to textbooks, as I found this paragraph at this web site.

    Here is my web-site: low calorie foods

    ReplyDelete
  10. A fascinating discussion is definitely worth comment. I do believe that you need to publish
    more on this subject matter, it might not be a taboo matter but generally people do
    not talk about these issues. To the next! All the best!
    !

    Look at my web-site ... dieting

    ReplyDelete
  11. I love reading a post that can make men and women think. Also, thanks for allowing for me to comment!


    Also visit my blog ... Glutenunverträglichkeit

    ReplyDelete
  12. I'm amazed, I must say. Rarely do I come across a blog that's equally educative and amusing, and let me
    tell you, you have hit the nail on the head.
    The issue is an issue that too few people are speaking intelligently
    about. Now i'm very happy that I found this in my hunt for something concerning this.

    Here is my web site - steuberater in wiesbaden
    My site > umschulung bilanzbuchhalter

    ReplyDelete
  13. With havin so much written content do you ever run into any problems of plagorism or copyright infringement?
    My site has a lot of exclusive content I've either authored myself or outsourced but it appears a lot of it is popping it up all over the internet without my permission. Do you know any techniques to help protect against content from being ripped off? I'd genuinely
    appreciate it.

    Take a look at my web blog: Fußreflexzone
    Also see my web page :: Wirkung

    ReplyDelete
  14. Have you ever considered creating an e-book or
    guest authoring on other websites? I have a blog based upon
    on the same topics you discuss and would really like to have
    you share some stories/information. I know my viewers would enjoy
    your work. If you're even remotely interested, feel free to shoot me an email.

    My page :: wordpress admin url
    my web page: wordpress themes 2011

    ReplyDelete
  15. I like the helpful info you provide for your articles.
    I'll bookmark your blog and test again here regularly. I'm fairly sure I
    will be informed many new stuff right here! Good
    luck for the following!

    my page; opel corsa radio

    ReplyDelete
  16. I simply couldn't go away your site before suggesting that I actually enjoyed the usual information an individual supply in your guests? Is gonna be back steadily to check out new posts

    Here is my website - erfahrungen mit der paleo diät

    ReplyDelete
  17. I think the admin of this web page is really working hard in favor of his web site, for
    the reason that here every information is quality based information.


    My page :: cheap social bookmarks

    ReplyDelete
  18. WOW just what I was searching for. Came here by searching for World Of Tanks Hack

    ReplyDelete
  19. Howdy! I simply would like to give you a huge thumbs up
    for your excellent info you've got right here on this post. I am coming back to your blog for more soon.

    Visit my site :: Starcraft 2 key Generator

    ReplyDelete
  20. It's appropriate time to make some plans for the long run and it is time to be happy. I have read this publish and if I may I desire to counsel you few fascinating things or tips. Perhaps you could write next articles regarding this article. I want to learn more things approximately it!

    Also visit my web page; permanent hair straightening

    ReplyDelete
  21. Today, I went to the beachfront with my children.
    I found a sea shell and gave it to my 4 year old daughter and said "You can hear the ocean if you put this to your ear." She put
    the shell to her ear and screamed. There
    was a hermit crab inside and it pinched her
    ear. She never wants to go back! LoL I know this is entirely off topic but I had
    to tell someone!

    my weblog; unknown

    ReplyDelete
  22. hello there and thank you for your information – I've definitely picked up anything new from right here. I did however expertise several technical issues using this website, since I experienced to reload the site lots of times previous to I could get it to load properly. I had been wondering if your web hosting is OK? Not that I am complaining, but slow loading instances times will sometimes affect your placement in google and could damage your quality score if ads and marketing with Adwords. Well I am adding this RSS to my email and can look out for a lot more of your respective intriguing content. Ensure that you update this again very soon.

    Feel free to surf to my blog Microsoft points

    ReplyDelete
  23. Hello to all, the contents existing at this website are actually amazing for people knowledge, well, keep up the nice work fellows.


    My site; Modcloth Coupon

    ReplyDelete
  24. Its such as you learn my mind! You appear to understand
    so much approximately this, like you wrote the book in it or something.
    I believe that you simply could do with a few p.c.
    to drive the message house a little bit, but
    other than that, this is great blog. A great read. I will certainly be back.


    Here is my page ... Unknown

    ReplyDelete
  25. This piece of writing is truly a good one it assists new net people, who are wishing for blogging.


    Here is my site: Unknown

    ReplyDelete
  26. hello!,I love your writing very so much!
    percentage we keep in touch extra approximately your post on AOL?
    I need a specialist on this area to solve my problem.

    Maybe that's you! Taking a look ahead to see you.

    Check out my blog - Mon Jervois

    ReplyDelete
  27. Way cool! Some very valid points! I appreciate
    you penning this write-up and the rest of the site is also really good.


    Here is my homepage - Stretch marks

    ReplyDelete
  28. Hey there would you mind sharing which blog platform you're working with? I'm looking to start my own blog soon but I'm having a tough time choosing between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design seems different then most blogs and I'm looking for something unique.

    P.S Sorry for being off-topic but I had to ask!


    My web page; Unknown

    ReplyDelete
  29. Magnificent beat ! I would like to apprentice whilst you
    amend your web site, how could i subscribe for a weblog
    web site? The account helped me a appropriate
    deal. I have been a little bit acquainted of this your broadcast offered
    bright transparent idea

    Also visit my page ... unknown

    ReplyDelete
  30. Attractive section of content. I just stumbled upon your web site and in accession capital to assert that I acquire actually enjoyed account your blog posts.
    Any way I'll be subscribing to your feeds and even I achievement you access consistently quickly.

    My blog post; unknown

    ReplyDelete
  31. Hello great blog! Does running a blog like this require
    a lot of work? I've absolutely no expertise in computer programming however I was hoping to start my own blog in the near future. Anyhow, if you have any ideas or techniques for new blog owners please share. I know this is off topic nevertheless I simply needed to ask. Thanks a lot!

    My web blog Unknown

    ReplyDelete
  32. You really make it appear so easy along with your presentation but I to
    find this topic to be really something that I feel I
    would by no means understand. It seems too complicated and extremely huge
    for me. I am taking a look ahead on your subsequent put
    up, I'll try to get the hang of it!

    Check out my blog :: Psn Code Generator

    ReplyDelete
  33. I am really thankful to the holder of this web page who has shared this enormous paragraph at at this time.



    Visit my web-site ... unknown

    ReplyDelete
  34. I always used to study post in news papers but now as
    I am a user of net therefore from now I am using net for posts, thanks to web.


    Also visit my weblog Psn Code Generator

    ReplyDelete
  35. Excellent post. I used to be checking constantly this weblog and
    I'm inspired! Very helpful information specially the ultimate phase :) I take care of such info a lot. I used to be seeking this particular info for a very long time. Thanks and good luck.

    My blog - tattoo removal cream reviews

    ReplyDelete
  36. Hi there mates, how is everything, and what you desire to say concerning this piece of writing,
    in my view its truly amazing in support of me.

    Take a look at my homepage; Recycling Facts

    ReplyDelete
  37. I think this is one of the most vital information for me.
    And i am glad reading your article. But want to remark
    on some general things, The website style is ideal, the articles is really nice : D.
    Good job, cheers

    Visit my web-site :: World Of Tanks Hack

    ReplyDelete
  38. I am genuinely thankful to the holder of this website who has shared this impressive article at at this place.


    Also visit my site Microsoft Office Gratuit

    ReplyDelete
  39. Why people still use to read news papers when in this technological
    globe the whole thing is presented on web?

    Also visit my web site: permanent hair straightening

    ReplyDelete
  40. You really make it seem so easy with your presentation
    but I find this matter to be actually something that I think I would never understand.

    It seems too complicated and very broad for me.
    I'm looking forward for your next post, I will try to get the hang of it!

    Also visit my web page: diaper Rash home Remedies

    ReplyDelete
  41. I'd like to find out more? I'd like to find out some additional information.


    Feel free to surf to my blog Ps3 jailbreak

    ReplyDelete
  42. Hello there, I discovered your blog by means of Google whilst searching
    for a related matter, your website got here up, it appears good.
    I have bookmarked it in my google bookmarks.
    Hello there, simply was aware of your blog thru
    Google, and located that it is really informative. I'm going to watch out for brussels. I will appreciate in case you proceed this in future. Lots of people will be benefited from your writing. Cheers!

    Look at my web-site: Unknown

    ReplyDelete
  43. Good post. I learn something totally new and
    challenging on sites I stumbleupon everyday. It will always be
    helpful to read articles from other writers and practice something from other websites.



    my page - The Interlace

    ReplyDelete
  44. Good post. I learn something totally new and challenging on blogs I stumbleupon
    on a daily basis. It will always be exciting to read through
    articles from other writers and use a little something from their web
    sites.

    Look at my weblog - candy crush Saga Hack

    ReplyDelete
  45. Do you have any video of that? I'd like to find out more details.

    Feel free to surf to my site: Dragon City Cheat Engine

    ReplyDelete
  46. It's hard to find educated people for this subject, however, you sound like you know what you're talking about!
    Thanks

    My web site pirater un compte facebook

    ReplyDelete
  47. I was suggested this web site by my cousin.
    I am not positive whether this publish is written via him as nobody else know such specific approximately my trouble.

    You're wonderful! Thank you!

    Feel free to visit my web page :: Unknown

    ReplyDelete
  48. Incredible story there. What occurred after? Thanks!

    My blog; world Of tanks hack

    ReplyDelete
  49. I know this if off topic but I'm looking into starting my own weblog and was curious what all is required to get setup? I'm assuming having
    a blog like yours would cost a pretty penny? I'm not very internet smart so I'm not 100% sure.
    Any tips or advice would be greatly appreciated.

    Many thanks

    Visit my web page Free Psn Codes

    ReplyDelete
  50. Wonderful, what a webpage it is! This website presents useful information to
    us, keep it up.

    My blog post: Code Psn Gratuit ()

    ReplyDelete
  51. Hi there, I wish for to subscribe for this website to take newest updates, therefore where can i do it please
    assist.

    Also visit my web-site; psn code generator (Youtube.Com)

    ReplyDelete
  52. Thanks for ones marvelous posting! I seriously enjoyed reading it, you're a great author. I will be sure to bookmark your blog and will often come back sometime soon. I want to encourage you continue your great job, have a nice weekend!

    my web page; Code Psn Gratuit

    ReplyDelete
  53. I am not sure where you are getting your information, but great topic.
    I needs to spend some time learning more or understanding more.

    Thanks for excellent info I was looking for this information for my mission.


    my blog; Psn Code Generator []

    ReplyDelete
  54. Hi there, its fastidious article about media print, we all be familiar
    with media is a great source of information.


    my website download 7zip (http://www.youtube.com/watch?v=rah5gn8r8m4)

    ReplyDelete
  55. Wow! At last I got a webpage from where I know
    how to actually take helpful information concerning my study and knowledge.


    My blog post - Minecraft Gift Code Generator

    ReplyDelete
  56. hello there and thank you for your info – I've definitely picked up something new from right here. I did however expertise a few technical issues using this site, as I experienced to reload the web site a lot of times previous to I could get it to load correctly. I had been wondering if your web host is OK? Not that I'm complaining, but slow loading instances
    times will sometimes affect your placement in google and could damage
    your quality score if ads and marketing with Adwords.
    Well I'm adding this RSS to my e-mail and can look out for a lot more of your respective interesting content. Make sure you update this again very soon.

    Here is my web page Minecraft Crack

    ReplyDelete