I need to create a coin tossing java application.
Ok it must have an instance variable boolean.
and when it's true, the side of the coin will heads.
if false, then tails.
how do I go about it?
then after that, head will be = 1 while tails will be 0.
the purpose is to be able to count the number of times each side has.
Thanks!
import java.lang.Math;
class Coin {
boolean coinSide;
Coin() {
coinSide = true;
}
getCoinside() {
if(num = 1) {
}
}
public static void main(String [] args) {
int num = (int)(Math.random() *2); //returns an integer
System.out.println(num);
}
}
Ok I think i better put the requirements document over here so everyone can understand. cheers
(a) Design, write and test class that will represent a coin, with a method to toss the coin.
A coin has an instance variable that indicates whether a result was heads or tails. What type should this instance variable be?
The constructor for a coin should initialise the face of the coin to heads. The constructor has no parameters.
The coin has two methods:
• A method to return the result of the toss (i.e. returns the instance variable indicating heads or tails).
• A method to toss the coin
The method to toss the coin requires a random number, either 0 or 1.
We can get a random number using a method of the Math class. Math.random() returns a double value between 0 and 1. To convert this value to an integer, either 0 or 1, the following code is used
int num = (int)(Math.random() *2); //returns an integer
(b) When you have written your coin class, write a test class, with a main method, which will create a Coin object, and toss it. Each time it is tossed, print out the result (heads or tails).
(c) Now alter the main method to toss the coin 100 times, and count the number of times the coin toss results in heads and the number of time it result in tails. You will need a loop for this, iterating 100 times. Display the heads count and tails count.
You could write a simple app such as
import java.util.Random;
//This is for flipping the "coin"
public class coins{
private static Random random=new Random();
//This is the coin
private int amountOfHead=0;
//This is the int for amount of heads flipped
private int amountOfTails=0;
//This is the int for the amount of tails flipped
private static int a1;
//This is also the coin
public void flip(){
a1=random.nextInt(1);
//This "flips the coin" making it a 1 or 0
if(a1==0){
amountOfTails+=1;
//If the "coin" is 0 tails increases by 1
}else{
amountOfHeads+=1;
//If anything else happens(such as a 1) heads increases by 1
}
System.out.println(amountOfHeads+", "+amountOfTails)
//This prints the results out
}
}
To run this program you just call flip().
Related
Currently, I am looking for a recursive solution to predict the outcome of a game with both players playing optimally. The game is played between two players.
I am given a sequence of numbers in the form of an array and always want to draw a number from one of the edge sides (i.e. start or end of the array). Depending on which player's turn it is, the points are credited and it is the next player's turn. This player now also chooses a number, which is at the edge of the number array. At the end the player with the larger sum has won.
In the graphic all possible game courses for four starting numbers are visualized in a binary tree. I am now wondering how to design a recursive algorithm that takes all these possible combinations into account and finally returns the score of the winning player if both players play optimally.
When you talk about optimal game results I assume that the player always chooses the highest number.
You will need to add deque pakages
import java.util.ArrayDeque;
import java.util.Deque;
Here you have a method that gives an array with the player A and player B results.
private static int[] optimalGameResults(int[] board) {
boolean turnA=true;
int sumA=0,sumB=0;
Deque<Integer> deque = new ArrayDeque<>();
for (int n: board) {
deque.offer(n);
}
while (deque.size()>0){
if(turnA){
sumA = sumOptimal(sumA, deque);
turnA=false;
}else{
sumB = sumOptimal(sumB, deque);
turnA=true;
}
}
int[] abResults={sumA,sumB};
return abResults;
}
It also needs an additional method to know which value remove (optimization)
private static int sumOptimal(int sum, Deque<Integer> deque) {
if(deque.getFirst()> deque.getLast()){
sum += deque.removeFirst();
}else {
sum += deque.removeLast();
}
return sum;
}
I'm in the process of writing a very simple quiz-style boardgame that moves players around the board based on if they answer the question correctly and what they roll on the dice. I'm attempting to create and pass an array mehtod that stores the scores of player 1 and player 2, but the array doesn't seem to actually keep track of the score. For example, a fragment of some of the code is as follows:
public static int[] scorearray
{
int scoreplayer1 = 0;
int scoreplayer2 = 0;
return new int[] = {scoreplayer1, scoreplayer2};
}
public static int questions(int diceroll, int[] score)
{
String textinput = input("What's 9+10?");
int ans = Integer.parseInt(textinput);
if (ans == 19)
{
output("Fantastic answer, that's correct!");
diceroll = dicethrow(diceroll); // rolls the dice
output("Move forward " + diceroll + " squares. You are on square " + score[0]);
//I need the output above to print position 0 in the above array
score[0] = score[0] + diceroll; //array stores the cumulative score
}
else
{
output("Sorry, the answer was 19. Next player's turn.")
//This is where I need the loop to switch between players
}
In addition, I need to come up with a way of switching between player 1 and 2 while also switching to the position 1 in the above array, that is, I need to add to player two's score instead of player one's. I've been combing through this code for ages now trying to figure out how to do this but I can only come up with the idea of using a for/while loop. Other than that I'm truly stumped.
Thanks.
EDIT: It appears that my array apparently still does not store the score when being used in the method questions.
Also I have now realised I can control whose turn it is by creating another method, for example public static void activePlayer() but I'm still not sure how to use a loop (or anything else for that matter) to switch between the two. Also my concern is where I use score[0] = score[0] + diceroll; in my questions method only keeps the score (or at least attempts to; see above problem) for player one. How would I switch it to keep score for score[1]? Please.
your options here seem to be either have your questions function output the score or change your score object to be a static object instead of a static function.
public static int[] scorearray = [0,0];
or
public static int[] questions(int diceroll, int[] score)
My assignment is to find a way to display all possible ways of giving back change for a predetermined value, the values being scanned in from a txt file. This must be accomplished by Recursive Backtracking otherwise my solution will not be given credit. I will be honest in saying I am completely lost on how to code in the appropriate algorithm. All I know is that the algorithm works something like this:
start with empty sets.
add a dime to one set.
subtract '10' from my amount.
This is a negative number, so I discard that set: it is invalid.
add a nickel to another (empty) set.
subtract '5' from my amount.
This equals 2; so I'll have to keep working on this set.
Now I'm working with sets that already include one nickel.
add a dime to one set.
subtract '10' from my amount.
This is a negative number, so I discard that set: it is invalid.
repeat this with a nickel; I discard this possibility because (2 - 5) is also negative.
repeat this with a penny; this is valid but I still have 1 left.
repeat this whole process again with a starting set of one nickel and one penny,
again discarding a dime and nickel,
and finally adding a penny to reach an amount of 0: this is a valid set.
Now I go back to empty sets and repeat starting with a nickel, then pennies.
The issue is I haven't the slightest clue on how or where to begin, only that that has to be accomplished, or if any other solutions are apparent.
This is my code thus far:
UPDATED
import java.io.*;
import java.util.*;
import java.lang.*;
public class homework5 {
public static int penny = 1;
public static int nickle = 5;
public static int dime = 10;
public static int quarter = 25;
public static int halfDollar = 50;
public static int dollar = 100;
public static int change;
public static void main(String[] args) throws FileNotFoundException {
ArrayList<Integer> coinTypes = new ArrayList<Integer>();
Integer i;
File f = new File (args[0]);
Scanner input = new Scanner(f);
input.nextLine();
while(input.hasNextInt()) {
i = input.nextInt();
coinTypes.add(i);
}
change = coinTypes.get(coinTypes.size()-1);
coinTypes.remove(coinTypes.size()-1);
System.out.println("Found change"); //used for debugging
System.out.println("Change: " + change);
System.out.println(coinTypes);
}
boolean findChange(int change, List<Integer> coinTypes,
List<Integer> answerCoins) {
if(change == 0) {
return true;
}
if(change < 0) {
return false;
} else {
for(Integer coin : coinTypes) {
if(findChange(change - coin, coinTypes, answerCoins)){
answerCoins.add(coin);
return true;
}
}
List<Integer> answer = new ArrayList<Integer>();
boolean canFindChange = findChange(change, coinTypes, answer);
if(canFindChange) {
System.out.println(answer);
} else { System.out.println("No change found");
}
return false;
}
}
Here is the input file that I scan in
java homework5 hwk5sample1.txt
// Coins available in the USA, given in cents. Change for $1.43?
1 5 10 25 50 100
143
OUTPUT
Found change
Change: 143
[1, 5, 10, 25, 50, 100]
So using the numbers in my coinTypes ArrayList, I need a generic code algorithm to show all possible ways of receiving, for example, 143 ($1.43) back in change using the coins in the file with all pennies being the last way to show it.
Please do not think I want you to write me the algorithm, I am simply wanting help writing one otherwise I will learn nothing. Thank you all for any answers or help you can give it means a lot to me! Please let me know if i missed anything or you need more info
The example that you walk through seems to be mostly correct. The only error is this: again discarding a dime and nickel, which should be again discarding a *penny* and nickel (but I think that's just a typo.)
To write a recursive backtracking algorithm, it is useful to think of the recursive call as solving a subproblem of the original problem. In one possible implementation of the solution, the pseudocode looks like this:
/**
* findChange returns true if it is possible to make *change* cents of change
* using the coins in coinTypes. It adds the solution to answerCoins.
* If it's impossible to make this amount of change, then it returns false.
*/
boolean findChange(int change, List<Integer> coinTypes, List<Integer> answerCoins) {
if change is exactly 0: then we're done making change for 0 cents! return true
if change is negative: we cannot make change for negative cents; return false
otherwise, for each coin in coinTypes {
// we solve the subproblem of finding change for (change - coin) cents
// using the recursive call.
if we can findChange(change - coin, coinTypes, answerCoins) {
// then we have a solution to the subproblem of
// making (change - coins) cents of change, so:
- we add coin to answerCoins, the list of coins that we have used
- we return true // because this is a solution for the original problem
}
}
//if we get to the next line, then we can't find change for any of our subproblems
return false
}
We would call this method with:
List<Integer> answer = new ArrayList<Integer>();
boolean canFindChange = findChange(change, coinTypes, answer);
if(canFindChange) {
System.out.println(answer); // your desired output.
}
else {
System.out.println("Can't find change!");
}
I am a noob to java, as well as programming, and I am having large difficulties picturing how to actually execute each method in order to create the Connect Four game. There are 4 methods, main, printBoard, checkWinner, and playerMove. I may add more methods if necessary. I am overwhelmed and need a ton of guidance. how to approach each method? Sorry if this is a mammoth question, I am throughly confused.
import java.util.Scanner;
public class ConnectFour{
// We will represent the game board using a 2 dimensional integer array.
// Each entry of the array will contain a 0, 1, or -1.
// A 0 entry in the array represents an empty slot.
// A 1 entry represents Player 1's piece.
// A -1 entry represents Player 2's piece.
// Since most methods will need to access this board, we have decided to
// make it a global class variable.
import java.util.Scanner;
public class ConnectFour{
public static int[][] board = new int[6][7];
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
// initializing board
for(int i = 0; i < 6; i++){
for(int j = 0; j < 7; j++){
board[i][j] = 0;
}
}
// WRITE CODE HERE
if (j < 7 && j >= 0)
f[i][j] =".";
else f[i][j] = " ";
return board;
}
}
// This method prints the board on the screen.
// To represent Player 1's pieces, print 'X'.
// To represent Player 2's pieces, print 'O'.
// To represent an empty slot, print '.'.
public static void printBoard(){
// WRITE CODE HERE
for (int i = 0; i < 6; i++)
{
for (int j = 0;j < 7; j++)
{
System.out.print(f[i][j]);
}
System.out.println();
}
}
// This method scans the current board and checks if there is a winner.
// The method should return 1 if Player 1 has connected 4 pieces.
// It should return -1 if Player 2 has connected 4 pieces.
// It should return 0 if no player has connected 4 pieces.
public static int checkWinner(){
// WRITE CODE HERE
return;}
// This method implements a player's move and updates the board accordingly.
// The method has two integer inputs.
// The first input indicates the player (1 for Player 1, -1 for Player 2).
// The second input indicates the column number that the player has
// chosen to play.
// If the column number is out of range or the column is currently full,
// the method should return false.
// Otherwise, the board should be updated and the method should return true.
public static boolean playerMove(int player, int columnNum){
// WRITE CODE HERE
}
}
Think about how your program should work, logically. I would personally put your board in a separate class, but it's not too important, especially since the program is pretty small. This isn't really as much as a code problem as much as a logic one, so we'll walk through how the game works.
First off, what does each function do? We have checkWinner(), playerMove(), and printBoard(). So we'll have a loop until the game ends, which should be controlled by checkWinner(), like so
while !checkWinner
So the game will loop until a winner is found, and any code executed after the while loop is end game code. Inside our while loop should go all of code executed every frame while there is no winner, since that is how our while loop is setup now. So let's think about what should execute every frame of your game.
printBoard()? Yeah, probably, since we want to update the display every frame right?
playerMove()? Yeah, since if the game hasn't ended, we want the players to execute a move. However, you need to make sure that the code is functional for switching between players. If you do that, the basic game loop should be finished. Here's some psuedocode for that
//setup board here
while !checkWinner
printBoard
playerMove
//since checkwinner did not return 0, a player won. so we put in endgame code here
The main issue here is thinking out how your program should work, logically. So plan out which functions do what, and try to write it out.
Hope that helps.
Hello I have the following tasks:
First, I am given this code that uses a method to generate random numbers 100 times:
public class Q3 {
public static void printDiceRolls(Random randGenerator) {
for (int i = 0; i < 100; i++) {
System.out.println(randGenerator.nextInt(6) + 1);
}
}
public static void main(String[] args) {
Random man = new Random();
printDiceRolls(man);
}
}
Second, I am asked to make a class LoadedDice that extends the Random class:
public class LoadedDice extends Random {
// instance variables - replace the example below with your own
public int nextInt(int num) {
// code right here
return 3;
}
}
Then I am asked to override the public int nextInt ( int num ) and do the following
Override the public int nextInt(int num) method such that with a 50%
chance, the new method always returns the largest number possible
(i.e., num-1), and with a 50% chance, it returns what the Random's
nextInt method would return
I do not quite understand what my overridden method should do in this case.
Suggestions?
Use another Random instance to give you a 50% chance (e.g. nextInt(100) >= 50) then based on that return a constant or a real random.
I guess one way to do this is to use (another?) random number generator with a uniform distribution and set it to return 0 or 1. The 0/1 would be the 50% for you to make your decision upon.... either returning super.nextInt or the max number.
To me, it looks like the nextInt(int) function comes up with a number between 1 and the input. In the root Random class, this function finds a random number within that range. What they want you to do is change that so that half the time it will return a random number in the range, but the other half the time it will give the maximum number.
In the example they gave, you're rolling a dice, so the range is 1-6. Normally, nextInt will find a random number between 1 and 6. But your new function will only do that half the time. The other half the time, it will return 6.
I have an idea on how you can implement that, but it seems like it would be cheating to go that far. ^^;
if(super.nextBoolean())
return num-1;
return super.nextInt(num);
if num<Integer.MAX/2, we can
int x = super.nextInt(num*2);
return Math.min(x, num-1);