How to count the occurrences of random instances - java

For example I have a programming assignment that wants me to make a coin class and a driver class that randomly flips a coin 40 times and then counts at the very end how many times it ends up heads and tails. Well I got the entire code so far it being:
public class driver {
public static void main(String[] args) {
coin myCoin = new coin();
System.out.println("Coin initially is " + myCoin.getSideUp());
for (int i = 0; i < 40; i++) {
myCoin.toss();
System.out.println("Coin is now " + myCoin.getSideUp());
}
}
}
public class coin {
protected String sideUp;
public coin() {
if (Math.random() < 0.5)
this.sideUp = "heads";
else
this.sideUp = "tails";
}
public void toss() {
if (Math.random() < 0.5)
this.sideUp = "heads";
else
this.sideUp = "tails";
}
public String getSideUp() {
return this.sideUp;
}
}
That's all done, but how do I count the instances of each heads or tails?

Count them as the tosses are made instead of at the end. If the assignment prohibits this, save the results to an array and count the results from the array at the end.

Just check and see if your coin is head or tail after each toss.
You could keep the counter for each status(head/tail) in an array like below:
Coin myCoin = new Coin();
System.out.println("Coin initially is " + myCoin.getSideUp());
int[] coinCount = new int[2];
for (int i = 0; i < 40; i++) {
myCoin.toss();
System.out.println("Coin is now " + myCoin.getSideUp());
if(myCoin.getSideUp().equals("heads")){
coinCount[0]++;
} else {
coinCount[1]++;
}
}
System.out.println("Heads: "+coinCount[0]);
System.out.println("Tails: "+coinCount[1]);

Related

unable to come up with a solution to use methods calls

I am working on a lab that requires me to return the number it flips it requires to get heads. I used a for loop, and a while loop but it appears that returning the method values along with the loops is not making the code runnable. I would appreciate the assistance. There are two pieces of codes, each different classes calling upon another class.
import java.util.*;
public class GVCoin {
// true for heads, false for tails
private boolean isHeads;
private int flips, heads;
private Random r;
public GVCoin() {
r = new Random();
heads = 0;
flips = 0;
isHeads = true;
}
public void flip() {
isHeads = r.nextBoolean(); // Flip the coin by randomly choosing true / false
flips++; // Increment flip count
if(isHeads){
heads++; // Increment heads count if current flip results in heads
}
}
public boolean isHeads() {
return isHeads; // Return true if coin is currently heads
}
public String toString() {
String str;
str = "Flips: " + flips + " Heads: " + heads + " isHeads: " + isHeads;
return str; // Return String representation of important values
}
public int numFlips() {
return flips; // Return number of total flips
}
public int numHeads() {
return heads; // Return number of total heads
}
public int numTails() {
return flips - heads; // Return number of total tails
}
public void setToHeads(boolean h) {
isHeads = h;
}
public GVCoin(int seed) { // Create the coin with a random seed
this();
r = new Random(seed);
}
}
public class TossingCoins {
public int flipForHeads(GVCoin coin, int goal) {
int i = 0;
do {
coin.flip();
i++;
} while (i < goal);
return i;
}
public static void main(String[] args) {
TossingCoins game = new TossingCoins();
GVCoin coin = new GVCoin(15); // Create a GVCoin object with seed value 15
int numHeads = 100; // Desire 100 heads
int totalFlips;
totalFlips = game.flipForHeads(coin, numHeads);
System.out.println("Total number of flips for 100 heads: " + totalFlips);
}
}
I suggest you not to use seed when you create Random. If you do, the outcome will be always the same.
Here some working code. I removed some code you wrote which I thought not actually needed. Cheers!
class GVCoin {
private Random r;
public GVCoin() {
r = new Random();
}
public GVCoin(int seed) {
this();
r = new Random(seed);
}
public boolean flip() {
return r.nextBoolean();
}
}
public class TossingCoins {
public int flipForHeads(GVCoin coin, int goal) {
int count = 0;
int numberOfHeads = 0;
while (numberOfHeads < goal) {
count++;
boolean isHead = coin.flip();
if (isHead) {
numberOfHeads++;
}
}
return count;
}
public static void main(String[] args) {
TossingCoins game = new TossingCoins();
GVCoin coin = new GVCoin();
int numberOfHeads = 5;
int totalFlips;
totalFlips = game.flipForHeads(coin, numberOfHeads);
System.out.println("Total number of flips for "+ numberOfHeads + " heads: " + totalFlips);
}
}
I managed to figure out the code. On the method call I simply formatted the code as follows:
int flips = 0;
while (coin.numHeads() < goal) {
coin.flip();
flips++ ;
}
return flips;

Eclipse java coin toss

I need help in order for the output to also show the toss count since now it only shows the tosses showing heads. Tails heads tails and so on until it gets three heads but it is supposed to also show the toss count.
import java.util.*;
public class Coinrolling {
public static void main(String[] args) {
Random rand = new Random();
boolean noConsecutive = true;
int flipCount = 0;
int randomFlip;
while (noConsecutive) {
randomFlip = rand.nextInt(2) + 1;
if (randomFlip == 1) {
System.out.println("heads");
flipCount++;
}else {
System.out.println("tail");
flipCount= 0;
}
if (flipCount == 3) {
noConsecutive = false;
}
}
}
}
You can add tossCount variable in the same way you already have flipCount. You can also simplify the while loop condition by checking flipCount:
Random rand = new Random();
int flipCount = 0;
int tossCount = 0;
while (flipCount != 3) {
int randomFlip = rand.nextInt(2) + 1;
tossCount++;
if (randomFlip == 1) {
System.out.println("heads");
flipCount++;
} else {
System.out.println("tail");
flipCount = 0;
}
}
System.out.print("tossed " + tossCount + " times");

Mean, Median, and Mode - Newb - Java

We had a lab in Comsci I couldn't figure out. I did a lot of research on this site and others for help but they were over my head. What threw me off were the arrays. Anyway, thanks in advance. I already got my grade, just want to know how to do this :D
PS: I got mean, I just couldn't find the even numbered median and by mode I just gave up.
import java.util.Arrays;
import java.util.Random;
public class TextLab06st
{
public static void main(String args[])
{
System.out.println("\nTextLab06\n");
System.out.print("Enter the quantity of random numbers ===>> ");
int listSize = Expo.enterInt();
System.out.println();
Statistics intList = new Statistics(listSize);
intList.randomize();
intList.computeMean();
intList.computeMedian();
intList.computeMode();
intList.displayStats();
System.out.println();
}
}
class Statistics
{
private int list[]; // the actual array of integers
private int size; // user-entered number of integers in the array
private double mean;
private double median;
private int mode;
public Statistics(int s)
{
size = s;
list = new int[size];
mean = median = mode = 0;
}
public void randomize()
{
Random rand = new Random(12345);
for (int k = 0; k < size; k++)
list[k] = rand.nextInt(31) + 1; // range of 1..31
}
public void computeMean()
{
double total=0;
for (int f = 0; f < size; f++)
{
total = total + list[f];
}
mean = total / size;
}
public void computeMedian()
{
int total2 = 0;
Arrays.sort(list);
if (size / 2 == 1)
{
// total2 =
}
else
{
total2 = size / 2;
median = list[total2];
}
}
public void computeMode()
{
// precondition: The list array has exactly 1 mode.
}
public void displayStats()
{
System.out.println(Arrays.toString(list));
System.out.println();
System.out.println("Mean: " + mean);
System.out.println("Median: " + median);
System.out.println("Mode: " + mode);
}
}
Here are two implementations for your median() and mode() methods:
public void computeMedian() {
Arrays.sort(list);
if ( (list.size & 1) == 0 ) {
// even: take the average of the two middle elements
median = (list[(size/2)-1] + list[(size/2)]) / 2;
} else {
// odd: take the middle element
median = list[size/2];
}
}
public void computeMode() {
// precondition: The list array has exactly 1 mode.
Map<Integer, Integer> values = new HashMap<Integer, Integer>();
for (int i=0; i < list.size; ++i) {
if (values.get(list[i]) == null) {
values.put(list[i], 1);
} else {
values.put(list[i], values.get(list[i])+1);
}
}
int greatestTotal = 0;
// iterate over the Map and find element with greatest occurrence
Iterator it = values.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
if (pair.getValue() > greatestTotal) {
mode = pair.getKey();
greatestTotal = pair.getValue();
}
it.remove();
}
}

Java lottery repeat program

I need this lottery program to repeat itself a certain number of times and then stop, but I am having trouble on where to place the for loop (if that's what I should use). How can I display the percentage of times 0, 1, 2, 3, 4 or 5 numbers matched out of all the runs?
package assignment5;
import javax.swing.JOptionPane;
import java.util.Random;
public class assignment5
{
public static void main(String[] args)
{
lottery pic=new lottery();
pic.Get_player_numbers();
pic.Get_jackpot_number();
pic.Check_winner ();
pic.Write_data();
}
}
class lottery
{
int[] picks= new int[5];
int[] cpick=new int[5];
int i;
int j,c;
int match=0;
void Get_player_numbers ()
{
int ctemp,cdupflag=0;
for(j=0;j<=4;++j)
{
//YOU DO NOT NEED THE CNUMBERFLAG
//IF YOU GENERATED THE NUMBERS CORRECLTY, THE COMPUTER WILL NOT GENERATE ONE ABOVE 99 OR LESS THAN 1
cdupflag=0;
while(cdupflag==0)
{
ctemp = (int)Math.round(Math.random()*99)+1;
cdupflag=1;
for(c=0;c<=j;++c)
{
if(ctemp==cpick[c])
{
cdupflag=0;
}
}//inner for loop
if(cdupflag==1)
cpick[j]=ctemp;
}
}
String Jackpot="User Lottery numbers are: "+"\n";
//String computer = "";
for(j=0;j<=4;++j)
{
if(j==4)
Jackpot=Jackpot+cpick[j];
else
Jackpot=Jackpot+cpick[j]+"-";
}
JOptionPane.showMessageDialog(null,Jackpot,"Output:",JOptionPane.INFORMATION_MESSAGE);
}
//void jackpot()
void Get_jackpot_number()
{
int ctemp,cdupflag=0;
for(j=0;j<=4;++j)
{
//YOU DO NOT NEED THE CNUMBERFLAG
//IF YOU GENERATED THE NUMBERS CORRECLTY, THE COMPUTER WILL NOT GENERATE ONE ABOVE 99 OR LESS THAN 1
cdupflag=0;
while(cdupflag==0)
{
ctemp = (int)Math.round(Math.random()*99)+1;
cdupflag=1;
for(c=0;c<=j;++c)
{
if(ctemp==cpick[c])
{
cdupflag=0;
}
}//inner for loop
if(cdupflag==1)
cpick[j]=ctemp;
}
}
String Jackpot="Computer Lottery numbers are: "+"\n";
//String computer = "";
for(j=0;j<=4;++j)
{
if(j==4)
Jackpot=Jackpot+cpick[j];
else
Jackpot=Jackpot+cpick[j]+"-";
}
JOptionPane.showMessageDialog(null,Jackpot,"Output:",JOptionPane.INFORMATION_MESSAGE);
}
void Check_winner ()
{
for(int i=0;i<=4;++i)
{
for(int j=0;j<=4;++j)
{
if(picks[i]==cpick[j])
{
match=match+1;
}
}
}
}
void Write_data ()
{
String print = "";
if(match==0)
{
print=print+"There is no match"+"\n";
print=print+"please try again "+"\n";
}
else
if(match==1)
{
print=print+"There is one match"+"\n";
print=print+"You won 100 Dollars "+"\n";
}
else
if(match==2)
{
print=print+"There are two matches"+"\n";
print=print+"You won 1,000 Dollars"+"\n";
}
else
if(match==3)
{
print=print+"There are three matches"+"\n";
print=print+"You won 10,000 Dollars "+"\n";
}
else
if(match==4)
{
print=print+"There are four matches"+"\n";
print=print+"You won 100,000 Dollars "+"\n";
}
else
if(match==5)
{
print=print+"There are five matches"+"\n";
print=print+"You won 1,000,000 Dollars"+"\n";
}
JOptionPane.showMessageDialog(null,print,"Output:",JOptionPane.INFORMATION_MESSAGE);
}}
//end of class lottery
As for the loop: It should go in main around the things you're doing for lottery
public static void main(String[] args)
{
for(int i = 0; i < [NumberOfRepeats]; i++)
{
lottery pic=new lottery();
pic.Get_player_numbers();
pic.Get_jackpot_number();
pic.Check_winner ();
pic.Write_data();
}
}
As for counting the percentages you'll need to modify the code for 'write_data()' to store or return the number of matches (probably in an array), then divide by the total number of runs for each.
To figure out how much those numbers have come up in relation to the rest, keep counters for each number and one for the total amount then just do some simple division.
package loop;
//import javax.swing.JOptionPane;
import java.io.*;
public class loop
{
public static void main(String[] args)
{
Lottery pic=new Lottery();
for(int i = 0; i < 500; i++) {
pic.getPlayerNumbers();
pic.getJackpotNumbers();
pic.checkWinner();
pic.assignPayout();
pic.stringBuilderOne();
}
pic.stringBuilderTwo();
pic.writeData();
}
}//end loop
class Lottery
{
private final int[] ppick= new int[5];
private final int[] cpick=new int[5];
private int match=0;
private int i;
private double matchcount0=0;
private double matchcount1=0;
private double matchcount2=0;
private double matchcount3=0;
private double matchcount4=0;
private double matchcount5=0;
private int jackpot = 25000000;
private int payout;
private final StringBuilder builderOne = new StringBuilder();
private final StringBuilder builderTwo = new StringBuilder();
void getPlayerNumbers ()
{
int ptemp,pdupflag;
for(i =0; i <=4;++i)
{
pdupflag=0;
while(pdupflag==0)
{
ptemp = (int)Math.round(Math.random()*99)+1;
pdupflag=1;
int p;
for(p =0; p<= i;++p)
{
if(ptemp==ppick[p])
{
pdupflag=0;
}
}//inner for loop
if(pdupflag==1)
ppick[i]=ptemp;
}
}
}//end getPlayerNumbers
void getJackpotNumbers()
{
int ctemp,cdupflag;
int j;
for(j =0; j <=4;++j)
{
cdupflag=0;
while(cdupflag==0)
{
ctemp = (int)Math.round(Math.random()*99)+1;
cdupflag=1;
int c;
for(c =0; c <= j;++c)
{
if(ctemp==cpick[c])
{
cdupflag=0;
}
}//inner for loop
if(cdupflag==1)
cpick[j]=ctemp;
}
}
String Jackpot="Computer Lottery numbers are: "+"\n";
//String computer = "";
for(j =0; j <=4;++j)
{
if(j ==4)
Jackpot=Jackpot+cpick[j];
else
Jackpot=Jackpot+cpick[j]+"-";
}
}//end getJackpot numbers
void checkWinner ()
{
match=0;
for(int i=0;i<=4;++i)
{
for(int j=0;j<=4;++j)
{
if(ppick[i]==cpick[j])
{
match=match+1;
}
}
}
}//end checkWinner
void assignPayout () {
if (match == 0) {
matchcount0 = matchcount0 + 1;
payout = 0;
jackpot = jackpot + 25000;
} else if (match == 1) {
matchcount1 = matchcount1 + 1;
payout = 100;
jackpot = jackpot + 100000;
} else if (match == 2) {
matchcount2 = matchcount2 + 1;
jackpot = jackpot + 250000;
payout = 1000;
} else if (match == 3) {
matchcount3 = matchcount3 + 1;
jackpot = jackpot + 500000;
payout = 10000;
} else if (match == 4) {
matchcount4 = matchcount4 + 1;
jackpot = jackpot + 1000000;
payout = 100000;
} else if (match == 5) {
matchcount5 = matchcount5 + 1;
payout = jackpot;
jackpot = 2500000;
}
}//end assignPayout
void stringBuilderOne ()
{
builderOne.append(System.getProperty("line.separator"))
.append("Current Jackpot Player# Winner# #Matched Payout\n")
.append(jackpot).append(" ")
.append(ppick[0]).append(" ")
.append(ppick[1]).append(" ")
.append(ppick[2]).append(" ")
.append(ppick[3]).append(" ")
.append(ppick[4]).append(" ")
.append(cpick[0]).append(" ")
.append(cpick[1]).append(" ")
.append(cpick[2]).append(" ")
.append(cpick[3]).append(" ")
.append(cpick[4]).append(" ")
.append(match).append(" ")
.append(payout);
}//end stringBuilderOne
void stringBuilderTwo ()
{
builderTwo.append(System.getProperty("line.separator"))
.append("\nThe percent of plays where 0 numbers matched = ")
.append(matchcount0 / i * 100).append("%\nThe percent of plays where 1 numbers matched = ")
.append(matchcount1 / 10).append("%\nThe percent of plays where 2 numbers matched = ")
.append(matchcount2 / 10).append("%\nThe percent of plays where 3 numbers matched = ")
.append(matchcount3 / 10).append("%\nThe percent of plays where 4 numbers matched = ")
.append(matchcount4 / 10).append("%\nThe percent of plays where 5 numbers matched = ")
.append(matchcount5 / 10).append("%\n");
}//End stringBuilderTwo
void writeData ()
{
try
{
BufferedWriter lotteryOutput = new BufferedWriter(new FileWriter("output.dat"));
lotteryOutput.write(builderOne.toString());
lotteryOutput.write(builderTwo.toString());
lotteryOutput.close();
}//end try
catch (IOException error)
{
//there was an error on the write to the file
System.out.println("Error on file write " + error);
}//end error
}//end writeData
}//end of class lottery
This accomplishes all of the requirements you have mentioned.

Java Program (Coin Flip simulation)

This is the code for FlipRace program which initiates a race between two coins. GOAL is a globally declared variable. Whichever coin reaches GOAL number of heads fastest wins. Below it is the code for the Coin class.
My problem is that if I put GOAL = 3 , that is whichever coin gets 3 heads fastest wins, it works ok. When I set GOAL = 4 , still it works ok. But something weird starts happening once I put GOAL > 4. Say I put GOAL = 7, still the final result comes only when one coin has registered 4 heads NOT 7.
// FlipRace.java
package nisarg;
public class FlipRace {
public static void main(String[] args){
final int GOAL = 6;
int count1=0,count2=0;
Coin myCoin1 = new Coin();
Coin myCoin2 = new Coin();
while(count1 < GOAL && count2 < GOAL){
myCoin1.Flip();
myCoin2.Flip();
System.out.print("Coin1 : " +myCoin1 +"\t");
System.out.println("Coin2 :"+myCoin2);
count1 = (myCoin1.isHeads())? count1+1 : 0;
count2 = (myCoin2.isHeads())? count2+1 : 0;
}
if(count2 < GOAL) {
System.out.println("Coin1 wins!!");
} else if(count1 < GOAL){
System.out.println("Coin2 wins!!");
}
else {
System.out.println("Its a tie!!");
}
}
}
// Coin.java
package nisarg;
import java.util.Random;
public class Coin {
private final int HEADS = 1;
private final int TAILS = 0;
private int face;
public Coin(){
Flip();
}
public void Flip(){
face = (int)(Math.random()*2);
}
public boolean isHeads(){
return(face == HEADS);
}
public String toString(){
String faceName;
if(face == HEADS){
faceName = "H";
}
else {
faceName = "T";
}
return faceName;
}
}

Categories

Resources