Advertisement
Guest User

Untitled

a guest
Dec 18th, 2018
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. import java.util.Random;
  2. import java.util.Scanner;
  3.  
  4. public class CoinFlip {
  5.  
  6. public static void main(String[] args) {
  7.  
  8. // create needed instances
  9. Scanner keyboard = new Scanner(System.in);
  10. Random rand = new Random();
  11.  
  12. int count;
  13.  
  14. System.out.println("How many times would you like to flip a coin? ");
  15. count = keyboard.nextInt();
  16.  
  17. int lastSide = -1;
  18. int consecutive = 1;
  19. int longestRunHeads = 0;
  20. int longestRunTails = 0;
  21. int oddsHeads = 2;
  22. int oddsTails = 2;
  23.  
  24. for (int i = 0; i < count; i++) {
  25.  
  26. int coin = rand.nextInt(2);
  27.  
  28. System.out.println(headsOrTails(coin));
  29.  
  30. if (coin == lastSide) {
  31.  
  32. consecutive++;
  33.  
  34. if (consecutive > longestRunHeads && coin == 0) {
  35.  
  36. longestRunHeads = consecutive;
  37. oddsHeads = longestRunHeads * 2;
  38. } else if (consecutive > longestRunTails && coin == 1) {
  39.  
  40. longestRunTails = consecutive;
  41. oddsTails = longestRunTails * 2;
  42. }
  43.  
  44. } else {
  45.  
  46. // reset the consecutive count if the
  47. // chain is broken.
  48. consecutive = 1;
  49. }
  50.  
  51. lastSide = coin;
  52. }
  53.  
  54. System.out.println("The longest run of heads was " +longestRunHeads + " The odds of that are 1 in " + oddsHeads +".\n" +
  55. "The longest run of tails was " + longestRunTails + " The odds of that are 1 in " + oddsTails + ".\n");
  56. }
  57.  
  58. private static String headsOrTails(int i) {
  59.  
  60. if (i == 0) {
  61.  
  62. return "heads";
  63. } else {
  64.  
  65. return "tails";
  66. }
  67. }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement