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");
Related
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;
I am using this to generate a random number inside a method and return it:
int randomValue = ThreadLocalRandom.current().nextInt(0, filteredArrayList.size());
How can I make sure there are not two random numbers in a row? I don't care if I get a 3, then a 5, then a 3 again. Only if I get a 3 and then a 3.
int temp = -1; // This will be your value to be compared to random value
for(int i = 0; i < 10; i++) { // assuming your filteredArraylist is size 10
int randomValue = ThreadLocalRandom.current().nextInt(0, 10);
if(randomValue == temp) {
i--; // it will repeat the generation of random value if temp and randomValue is same
} else {
temp = randomValue; // you will put here the ne random value to be compared to next value
System.out.println(randomValue);
}
Try following sample
import java.util.Random;
public class RandomTest {
public static void main(String[] args) {
for(int i = 0; i < 10; i++) {
System.out.println("####### " + RandomUtil.getRandomInt(10));
}
}
}
class RandomUtil {
private static int lastInt = -1;
private static Random random = new Random();
public synchronized static int getRandomInt(int upperBound) {
return getRandomInt(0, upperBound);
}
public synchronized static int getRandomInt(int lowerBound, int upperBound) {
int newInt = -1;
while( (newInt = lowerBound + random.nextInt(upperBound - lowerBound)) == lastInt) {
//Keep looping
}
lastInt = newInt;
return newInt;
}
}
As Scary Wombat said, you'll want to compare the previous value to the newly randomized value in a loop (which I assume you are using, since we only see the one line.
Something like this...
int prevRandomNumber, currRandomNumber;
while (notFinished) {
currRandomNumber = getRandom(); // your random number generator
if (prevRandomNumber == currRandomNumber) { // if there would be two in a row
continue; // try again
} else { // otherwise, add to array
addNumberToArray(currRandomNumber);
prevRandomNumber = currRandomNumber;
}
}
Just remember the last generated value and if equals then reject. Here is an example:
int lastRandomValue = -1;
boolean stop = false;
int attempts = 0;
final int maxAttempts = 100_000;
while (!stop) {
int currentRandomValue = ThreadLocalRandom.current().nextInt(0, filteredArrayList.size());
if (currentRandomValue != lastRandomValue) {
// Use the value
...
// Reset the counter
attempts = 0;
...
// Stop the generation process if generated enough values
if (...) {
stop = true;
}
} else {
// Increment a counter
attempts++;
}
if (attempts >= maxAttempts) {
stop = true;
}
}
Edited:
I'd do something like this: (requires the last random value/a non-reachable number for the first time, e.g. -1)
private int notPreviousRandom(int previousRandomValue) {
int randomValue;
do {
randomValue = ThreadLocalRandom.current().nextInt(0, filteredArrayList.size());
} while (randomValue == previousRandomValue);
return randomValue;
}
Alternatively you could define previousRandomValue as an attribute:
// class
private int previousRandomValue = -1;
// ...
private int notPreviousRandom() {
int randomValue;
do {
randomValue = ThreadLocalRandom.current().nextInt(0, filteredArrayList.size());
} while (randomValue == previousRandomValue);
previousRandomValue = randomValue; // for the next time you're using the
// method
return randomValue;
}
I'm trying to solve the Popular Vote problem, but I get runtime error and have no idea why, I really appreciate the help. Basically my solution is to get the total of votes, if all candidates have the same amount of votes; then there's no winner, otherwise I calculate the percentage of votes the winner gets in order to know if he's majority or minority winner.
import java.util.Scanner;
class popular {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n, suma, mayoria;
int casos=s.nextInt();
int cont=0;
int ganador=0;
float num=0;
while(cont!=casos){
n=s.nextInt();
int votos[]= new int[n];
for (int i = 0; i < n; i++) {
votos[i] = s.nextInt();
}
suma=sumar(votos);
if(suma==-1){
System.out.println("no winner");
}
else{
ganador=ganador(votos, suma);
num=(float)votos[ganador]/(float)suma;
if( num> 0.5){
System.out.println("majority winner "+(ganador+1));
}
else{
System.out.println("minority winner "+(ganador+1));
}
}
cont++;
ganador=0;
}
}
public static int sumar(int arreglo[]){
int resp1=-1, resp=0;
int temp=arreglo[0];
boolean sol=true;
for (int i = 0; i < arreglo.length; i++) {
resp=resp+arreglo[i];
if(temp!=arreglo[i]){
sol=false;
}
}
if(sol==false){
return resp;
}
return resp1;
}
public static int ganador(int arreglo[], int suma){
int mayor=0;
int ganador=0;
for (int i = 0; i < arreglo.length; i++) {
if(arreglo[i]>mayor){
mayor=arreglo[i];
ganador=i;
}
}
return ganador;
}
}
I submitted your code to the OJ, but I didn't get a runtime error, but I got Compilation error. I have to figure out there are some problems in your code. First of all, if you want to submit a java code to OJ, you need to name the public class as Main instead of popular or something else. Second, your code logic is not correct. Suppose a test case:
4
1
1
2
2
Your program will print "minority winner 3" but it's should be "no winner".
Here is a modified source code from yours (you can get accepted with this code):
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n, suma, mayoria;
int casos = s.nextInt();
int cont = 0;
int ganador = 0;
float num = 0;
while (cont != casos) {
n = s.nextInt();
int votos[] = new int[n];
for (int i = 0; i < n; i++) {
votos[i] = s.nextInt();
}
ganador = findMaximum(votos);
if (getMaximumCount(votos, votos[ganador]) > 1) {
System.out.println("no winner");
} else {
suma = sumOf(votos);
if (votos[ganador] * 2 > suma) {
System.out.println("majority winner " + (ganador + 1));
} else {
System.out.println("minority winner " + (ganador + 1));
}
}
cont++;
ganador = 0;
}
}
private static int sumOf(int[] arreglo) {
int sum = 0;
for (int x : arreglo) {
sum += x;
}
return sum;
}
private static int getMaximumCount(int[] arreglo, int maximum) {
// Check if there are more than one items have the maximum value
int count = 0;
for (int x : arreglo) {
if (x == maximum) {
count++;
}
}
return count;
}
private static int findMaximum(int[] arreglo) {
int x = 0, pos = 0;
for (int i = 0; i < arreglo.length; i++) {
if (x < arreglo[i]) {
x = arreglo[i];
pos = i;
}
}
return pos;
}
}
Hope it could help you!
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.
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]);