unable to come up with a solution to use methods calls - java

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;

Related

Can not figure out how to detect how many consecutive Heads in a Coin Flipper

I have a project I am working on in my java class and cannot figure out what a few lines of code.
The project consists of flipping a coin and using various methods to detect how many heads or tails as well as how many flips have occurred so far.
import java.util.*;
public class GVcoin{
// true for heads, false for tails
private boolean isHeads;
private int flips, heads;
private Random r;
//Create the coin
public GVcoin(){
r = new Random();
heads = 0;
flips = 0;
isHeads = true;
}
//Flip the coin by random choosing true / false
public void flip(){
isHeads = r.nextBoolean();
flips++;
if(isHeads){
heads++;
}
}
//return true if coin is currently heads
public boolean isHeads(){
return isHeads;
}
//return String representation of important values
public String toString(){
String str;
str = "Flips: " + flips + " Heads: " + heads + " isHeads: " + isHeads;
return str;
}
//return number of total flips
public int numFlips(){
return flips;
}
//return number of total heads
public int numHeads(){
return heads;
}
//return number of total tails
public int numTails(){
return flips - heads;
}
//Set the coin to heads (or tails) to start
public void setToHeads(boolean h){
isHeads = h;
}
//Create the coin with a random seed
public GVcoin(int seed){
this();
r = new Random(seed);
}
}
The problem I can not seem to figure out is in a different class called TossingCoins and is the method public int consecutiveHeads(GVcoin c, int goal)
public class TossingCoins {
public int countHeads(GVcoin c, int goal){
while(c.numHeads() != goal) {
c.flip();
}
return c.numFlips();
}
public int flipForTails(GVcoin c, int goal){
while(c.numTails() != goal) {
c.flip();
}
return c.numFlips();
}
public int consecutiveHeads(GVcoin c, int goal){
while(c.numHeads() != goal){
c.flip();
}
}
// This method creates a TossingCoins object and calls the method for testing
public static void main(String[] args) {
TossingCoins game = new TossingCoins();
GVcoin c = new GVcoin();
int numHeads = game.countHeads(c, 100);
}
}
What I have tried so far is see if the numHeads is not equal to the goal of heads. Then if it is not equal to the number of heads(goal), I would set the flip to add one. Which wold count 1, 2, 3, 4, 5 and so on till it hits the amount flips needed to hit the number of heads(goal).

Simple prisoner's dilemma genetic algorithm

I have used an existing genetic algorithm from
here
and reworked it I but don't know what I'm doing wrong
This is the error that I get
Exception in thread "main" java.lang.NullPointerException at
simpleGa.Algorithm.crossover(Algorithm.java:69) at
simpleGa.Algorithm.evolvePopulation(Algorithm.java:34) at
simpleGa.GAprisonerdilemma.main(GAprisonerdilemma.java:41)
I can't figure out exactly where the mistake is. Read a lot about NullPointerException but couldn't figure it out
package simpleGa;
public class Population {
public static Individual[] individuals;
/*
* Constructors
*/
// Create a population
public Population(int populationSize, boolean initialise) {
individuals = new Individual[populationSize];
// Initialise population
if (initialise) {
// Loop and create individuals
for (int i = 0; i < size(); i++) {
Individual newIndividual = new Individual();
newIndividual.generateIndividual();
saveIndividual(i, newIndividual);
}
for(int i=0;i<size();i++)
{
if(i%2==1){Individual individual1=individuals[i-1];
Individual individual2=individuals[i];
if(individuals[i-1].getGene(i-1)==0 && individuals[i].getGene(i)==0){
individuals[i-1].fitness=individual1.fitness+1;
individuals[i].fitness=individual2.fitness+1;
}
if(individuals[i-1].getGene(i-1)==1 && individuals[i].getGene(i)==1){
individuals[i-1].fitness=individual1.fitness+2;
individuals[i].fitness=individual2.fitness+2;
}
if(individuals[i-1].getGene(i-1)==0 && individuals[i].getGene(i)==1){
individuals[i-1].fitness=individual1.fitness+3;
individuals[i].fitness=individual2.fitness+0;
}
if(individuals[i-1].getGene(i-1)==1 && individuals[i].getGene(i)==0){
individuals[i-1].fitness=individual1.fitness+0;
individuals[i].fitness=individual2.fitness+3;
}
}}}
}
/* Getters */
public Individual getIndividual(int index) {
return individuals[index];
}
public Individual getFittest() {
Individual fittest = individuals[0];
// Loop through individuals to find fittest
for (int i = 1; i < size(); i++) {
if (fittest.getFitness() <= getIndividual(i).getFitness()) {
fittest = getIndividual(i);
}
}
return fittest;
}
/* Public methods */
// Get population size
public int size() {
return individuals.length;
}
// Save individual
public void saveIndividual(int index, Individual indiv) {
individuals[index] = indiv;
}
}
package simpleGa;
public class Individual {
static int defaultGeneLength = 1000;
private long[] genes =new long [defaultGeneLength];
// Cache
public static int fitness = 0;
// Create a random individual
public void generateIndividual() {
for (int i = 0; i < size(); i++) {
long gene = Math.round(Math.random());
genes[i] = gene;
}
}
/* Getters and setters */
// Use this if you want to create individuals with different gene lengths
public static void setDefaultGeneLength(int length) {
defaultGeneLength = length;
}
public long getGene(int i) {
return genes[i];
}
public void setGene(int index, long value) {
genes[index] = value;
fitness = 0;
}
/* Public methods */
public int size() {
return genes.length;
}
public static int getFitness() {
return fitness;
}
public void setFitness(int i) {
fitness=i;
}
#Override
public String toString() {
String geneString = "";
for (int i = 0; i < size(); i++) {
geneString += getGene(i);
}
return geneString;
}
}
package simpleGa;
public class Algorithm {
/* GA parameters */
private static final double uniformRate = 0.5;
private static final double mutationRate = 0.015;
private static final int tournamentSize = 5;
private static final boolean elitism = true;
/* Public methods */
// Evolve a population
public static Population evolvePopulation(Population pop) {
Population newPopulation = new Population(pop.size(), false);
// Keep our best individual
if (elitism) {
newPopulation.saveIndividual(0, pop.getFittest());
}
// Crossover population
int elitismOffset;
if (elitism) {
elitismOffset = 1;
} else {
elitismOffset = 0;
}
// Loop over the population size and create new individuals with
// crossover
for (int i = elitismOffset; i < pop.size(); i++) {
Individual indiv1 = tournamentSelection(pop);
Individual indiv2 = tournamentSelection(pop);
Individual newIndiv = crossover(indiv1, indiv2);
newPopulation.saveIndividual(i, newIndiv);
}
// Mutate population
for (int i = elitismOffset; i < newPopulation.size(); i++) {
mutate(newPopulation.getIndividual(i));
}
for(int i=0;i<pop.size();i++)
{for(int j=0;j<pop.getIndividual(i).size();j++)
{if(i%2==1){Individual individual1=Population.individuals[i-1];
Individual individual2=Population.individuals[i];
if(Population.individuals[i-1].getGene(i-1)==0 && Population.individuals[i].getGene(i)==0){
Population.individuals[i-1].fitness=individual1.fitness+1;
Population.individuals[i].fitness=individual2.fitness+1;
}
if(Population.individuals[i-1].getGene(i-1)==1 && Population.individuals[i].getGene(i)==1){
Population.individuals[i-1].fitness=individual1.fitness+2;
Population.individuals[i].fitness=individual2.fitness+2;
}
if(Population.individuals[i-1].getGene(i-1)==0 && Population.individuals[i].getGene(i)==1){
Population.individuals[i-1].fitness=individual1.fitness+3;
Population.individuals[i].fitness=individual2.fitness+0;
}
if(Population.individuals[i-1].getGene(i-1)==1 && Population.individuals[i].getGene(i)==0){
Population.individuals[i-1].fitness=individual1.fitness+0;
Population.individuals[i].fitness=individual2.fitness+3;
} }}}``
return newPopulation;
}
// Crossover individuals
private static Individual crossover(Individual indiv1, Individual indiv2) {
Individual newSol = new Individual();
// Loop through genes
for (int i = 0; i < indiv1.size(); i++) {
// Crossover
if (Math.random() <= uniformRate) {
newSol.setGene(i, indiv1.getGene(i));
} else {
newSol.setGene(i, indiv2.getGene(i));
}
}
return newSol;
}
// Mutate an individual
private static void mutate(Individual indiv) {
// Loop through genes
for (int i = 0; i < indiv.size(); i++) {
if (Math.random() <= mutationRate) {
// Create random gene
long gene = Math.round(Math.random());
indiv.setGene(i, gene);
}
}
}
// Select individuals for crossover
private static Individual tournamentSelection(Population pop) {
// Create a tournament population
Population tournament = new Population(tournamentSize, false);
// For each place in the tournament get a random individual
for (int i = 0; i < tournamentSize; i++) {
int randomId = (int) (Math.random() * pop.size());
tournament.saveIndividual(i, pop.getIndividual(randomId));
}
// Get the fittest
Individual fittest = tournament.getFittest();
return fittest;
}
package simpleGa;
public class FitnessCalc {
/* Public methods */
// Set a candidate solution as a byte array
// To make it easier we can use this method to set our candidate solution
// with string of 0s and 1s
// Calculate inidividuals fittness by comparing it to our candidate solution
static int getFitness(Individual individual) {
int fitness = 0;
// Loop through our individuals genes and compare them to our cadidates
fitness=Individual.fitness;
return fitness;
}
}
// Get optimum fitness
}
package simpleGa;
import java.util.Scanner;
public class GAprisonerdilemma {
public static void main(String[] args) {
// Set a candidate solution
Scanner keyboard = new Scanner(System.in);
System.out.println("Input number of games!");
int k = keyboard.nextInt();
Individual.setDefaultGeneLength(k);
// Create an initial population
System.out.println("Input number of individuals in the population!");
int p = keyboard.nextInt();
Population myPop = new Population(p, true);
System.out.println("Input acceptable number of generations!");
int l = keyboard.nextInt();
// Evolve our population until we reach an optimum solution
int generationCount = 0;
int j=l+1;
System.out.println("Input requiered fitness value !");
int f = keyboard.nextInt();
int h=0;
// Evolve our population until we reach an optimum solution
for(int i=0;i<j;i++)
{
if(i==0){}
else{
if(myPop.getFittest().getFitness()>=f){if(h==0){h++;}
else{ System.out.println("Solution found!");
System.out.println("Generation: " + generationCount);
System.out.println( "Fitness(Points): " + myPop.getFittest().getFitness());
break;}
}else {myPop = Algorithm.evolvePopulation(myPop);
generationCount++;
System.out.println("Generation: " + generationCount + " Fittest: " + myPop.getFittest().getFitness());
}
if(i==j-1){ if(myPop.getFittest().getFitness()>=f)System.out.println("Solution found !");
else System.out.println("Solution not found closest solution is!");
System.out.println("Generation: " + generationCount);
System.out.println( " Fitness(Points): " + myPop.getFittest().getFitness());}
}
}
System.out.println("0 for betrays in that turn 1 for cooperates!");
System.out.println("Turns:");
System.out.println(myPop.getFittest());
}
}

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;
}
}

Java Dice Game Trouble Generating new numbers

I am trying to learn OOP, starting with Java as I have read and been told it's the best place to start. With that said, I am trying to create a game for fun to help my learning, but I also know game programming and design can be more challenging.
So my goal here is to generate a new value from the RollDice D20 without having to reset or restart the program. You'll notice when I print out the values I print the same instance twice to demonstrate what I am avoiding, and a new instance to show that the new instance does indeed generate a new value. Perhaps, I am not approaching this in the right way, but this is a hurdle I am hoping to overcome with some help!
What I ultimately want is to figure out how to generate a new instance or at least a new roll value as many times as I want. Any and all help is greatly appreciated! I have added the code below as an example. Also any other feedback is appreciated.
import java.util.Random;
class RollDice
{// Begin RollDice Class
// Initiate method rollDice
public static int rollDice(int number, int nSides)
{
// System.out.println( "--- Welcome to the Dice Game v2! ---" ); //
// welcomes player
Random r = new Random();
// Declare class variables
int num = 0;
int roll = 0;
if (nSides >= 3)
{
for (int i = 0; i < number; i++)
{
roll = r.nextInt(nSides) + 1;
// System.out.println("Roll is: " + roll);
num = num + roll;
}
}
else
{
System.out.println("Error num needs to be from 3");
}
return num;
} // end method rollDice
int d4 = rollDice(1, 4);
int d6 = rollDice(1, 6);
int d8 = rollDice(1, 8);
int d10 = rollDice(1, 10);
int d12 = rollDice(1, 12);
int d20 = rollDice(1, 20);
public RollDice()
{
this.d4 = d4;
}
public void setD4(int D4)
{
this.d4 = D4;
}
public int getD4()
{
return d4;
}
// ////////////////
{
this.d6 = d6;
}
public void setD6(int D6)
{
this.d6 = D6;
}
public int getD6()
{
return d6;
}
// ////////////////
{
this.d8 = d8;
}
public void setD8(int D8)
{
this.d8 = D8;
}
public int getD8()
{
return d8;
}
// ////////////////
{
this.d10 = d10;
}
public void setD10(int D10)
{
this.d10 = D10;
}
public int getD10()
{
return d10;
}
// ////////////////
{
this.d12 = d12;
}
public void setD12(int D12)
{
this.d12 = D12;
}
public int getD12()
{
return d12;
}
// ////////////////
{
this.d20 = d20;
}
public void setD20(int D20)
{
this.d20 = D20;
}
public int getD20()
{
return d20;
}
// ////////////////
}// End RollDice Class
class Champion
{// Begin Champion Class
RollDice champDice = new RollDice();
int champroll = champDice.getD20();
public Champion()
{
this.champroll = champroll;
}
public void setChampRoll(int ChampRoll)
{
this.champroll = ChampRoll;
}
public int getChampRoll()
{
return champroll;
}
}// End Champion Class
public class DiceRollTest
{
public static void main(String ars[])
{
Champion tChampion = new Champion();
Champion pChampion = new Champion();
System.out.println("Your Champion defends with a " + tChampion.getChampRoll() + "\n");
System.out.println("Your Champion defends with a " + tChampion.getChampRoll() + "\n");
System.out.println("Your Champion defends with a " + pChampion.getChampRoll() + "\n");
}
}
Your RollDice class is not accomplishing what you want. All it's doing is storing a single dice roll result for each type of dice you have. Therefore, when you go an call getChampRoll() on your Champion object, all it's doing is returning the roll that already took place when you constructed your RollDice class.
Instead, you should make rollDice() a member function of your RollDice class. RollDice should then take in its constructor an argument indicating which dice should be rolled when rollDice() is called. That way, when you call getD20(), it will roll the D20 and give you the result.
I'll leave you with this as a starting point:
import java.util.Random;
public class Die {
private int mSides;
private Random mRandom;
public Die(int sides) {
this.mSides = sides;
mRandom = new Random(System.currentTimeMillis());
}
public int roll() {
return mRandom.nextInt(mSides + 1);
}
public int roll(int times) {
int sum = 0;
for (int i = 0; i < times; i++) {
sum += roll();
}
return sum;
}
}
This class can be inherited/subclassed for each dice you want to create. Then you can toss a few of these in your champion's pockets :)
First, you should create new Constructor. In this constructor you should inicialize Random object, and probably how many sides will dice have
class RollDice{
Random rand;
int sides;
public RollDice(int x){
sides = x;
rand = new Random()
}
}
then, in that class you can add method which will generate new value
public int roll(){
return rand.nextInt(x);
}
you may as well don,t generate RollDice object with fixed value of dice's sides and make the method like:
public int roll(int x){
return rand.nextInt(x);
}
if you want java to generate new value after you enter something on console just use loop with System.in.read() and if or switch statement (for example if someone enters 1 - generate new value, if 0, end program)

How to count the occurrences of random instances

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]);

Categories

Resources