Having issues with dice probability program - java

I am trying to make a program that calculates dice rolls using random digits and returns the probability of each sum happening for different numbers of rolls and trials. This code however only results in probabilities of zero displaying. This seems to be an issue with the establishment of the match variable in the nested for loop. Wondering what I am doing wrong. Is it establishing the match variable based on the counter?
import java.util.Random;
import java.util.Scanner;
public class DiceProbability
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
Random randNumList = new Random();
System.out.println("How many sides do the dice have: ");
int diceSides = in.nextInt();
System.out.println("How many times will the dice be rolled: ");
int diceRolls = in.nextInt();
int highestSum = diceSides * 2;
int diceRoll1 = 0;
int diceRoll2 = 0;
int match = 0;
int totalOfDiceRolls = 0;
int counter = 0;
int counter2 = 0;
System.out.println("Rolls total " + "Probability");
for(counter=2;counter<=highestSum;counter ++)
{
for(counter2=1;counter2<=diceRolls;counter2 ++)
{
diceRoll1 = (randNumList.nextInt(11)+1);
diceRoll2 = (randNumList.nextInt(11)+1);
int totalOfRolls = diceRoll1 + diceRoll2;
if(totalOfDiceRolls != counter)
{
match = match + 0;
}
else
{
match ++;
}
}
System.out.println(match);
double probabilityOfSum = (match * 100 / diceRolls);
System.out.println(counter + ": " + probabilityOfSum);
counter2 = 1;
}
}
}

If I understand this correctly you are trying to calculate the relative frequency for each sum of two dices being rolled. If it's the case please edit your question as it's not that explicit in what your asking, especially that you have always two dices.
If you have two sided dices, your mathematical probability is as per below :
P(of having 2) = 1/4
P(of having 3) = 2/4
P(of having 4) = 1/4
All others are equal to 0.
Here is the code to achieve this. You need to save the frequency in an array and output correctly in dividing by the number of experiment.
Note: if you run this for a number less than 1000 this won't be accurate mathematically so it doesn't really make sense the user input the number of experiments in this case... ( in my opinion)
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("How many sides do one dice have: ");
int diceSides = in.nextInt();
int[] results = new int[diceSides * 2 + 1];
Random rnd = new Random();
for (int i = 0; i < 10000; i++) {
int resultdice1 = rnd.nextInt(diceSides) + 1;
int resultdice2 = rnd.nextInt(diceSides) + 1;
int sum = resultdice1 + resultdice2;
results[sum] = results[sum] + 1;
}
for (int i = 0; i < results.length; i++) {
System.out.println("Probability to have sum of " + i + " is : " + (double) results[i] / 10000);
}
}
Output :

Related

Find the median of n values given by the user without using arrays or any function that uses arrays or any other collection

Only manual algorithms on variables are allowed. Collections like list, arrays etc. aren't to be used. (I Used .length() function in the program but it can be manually done by putting a space after every input and counting the number of chars till a space is found)
The problem that using arrays would solve is to store any number of values that the user inputs. This can be solved by storing the values in a string. Since we'd have to know how many characters to pick from the string to form a number, I've also stored the lengths of the numbers in a separate string(Length would generally be of only 1 digit so we'd know for sure that the length of nth number would be at the nth char in the lengthstorage string.)
The algorithm:
Take a number from the string and subtract it from every other number in the string.
If the result is positive, add 1 to the int 'pos'; if negative, to 'neg'; if zero, to 'copy'.
If odd number of numbers are inputed, then the number for which pos + copy >= n/2 and neg + copy >= n/2 is the median.
If even number of numbers are inputed, then we'd have 2 middle numbers fmedian and smedian whose average would be the median. (Refer the code for algorithm).
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input,inputstorage,lengthstorage,inputlength;
int nonrep=0;
System.out.println("Enter the number of values");
int n = sc.nextInt();
int fmedian=0,smedian=0;
System.out.println("Enter a value");
input= sc.next(); //String
inputlength = "" + (char)(input.length()+48);
inputstorage = input;
lengthstorage = inputlength;
for (int i=1; i<n; i++)
{
System.out.println("Enter a value");
input = sc.next();
inputstorage = inputstorage + input;
lengthstorage = lengthstorage + (char)(input.length()+48);
}
int mainnumpos = 0;
for(int j=0;j<n;j++)
{
int copy=0;
int mainnumlength = lengthstorage.charAt(j) - 48;
int neg=0,pos=0;
int mainnum = 0; int factor = 1;int mainnumsign = 0;
for (int m =mainnumlength-1; m >= 0; m--)
{
if(inputstorage.charAt(mainnumpos+m)=='-')
{
mainnumsign = 1;
}
else
{
mainnum += (inputstorage.charAt(mainnumpos+m) - '0') * factor;
factor *= 10;
}
}
mainnumpos = mainnumpos + mainnumlength;
if(mainnumsign==1)
{
mainnum = -mainnum;
}
int position = 0;
for (int q=0;q<n;q++)
{ int fnumsign = 0;
int fnumlength = lengthstorage.charAt(q) - 48;
int fnum = 0;
factor = 1;
for (int l =fnumlength-1; l >= 0; l--)
{
if(inputstorage.charAt(position+l)=='-')
{
fnumsign = 1;
}
else{
fnum += (inputstorage.charAt(position+l) - '0') * factor;
factor *= 10;
}
}
if(fnumsign==1)
{
fnum = -fnum;
}
if((mainnum-fnum)>0)
{
pos++;
}
else if((mainnum-fnum)<0)
{
neg++;
}
else{
copy++;
}
position = position + fnumlength;
}
if((n%2)!=0){
if((double)(pos+copy)>=((double)n)/2.0 && (double)(neg+copy)>=((double)n)/2.0)
{
if(nonrep==0)
{
System.out.println("The median is: "+ mainnum);
nonrep++;
}
}
}
else
{
if ((double)(pos+copy)==(double)n/2.0)
{
fmedian=mainnum;
}
else if((double)(neg+copy)==(double)n/2.0)
{
smedian = mainnum;
}
else if((double)(pos+copy)>=(double)n/2.0 && (double)(neg+copy)>=(double)n/2.0 )
{
fmedian = mainnum;
smedian = mainnum;
}
if(j==n-1){
double evenmedian = ((double)(smedian + fmedian))/2.0;
System.out.println("The median is: "+evenmedian);
}
}
}
}
}

Swapping Java lotto machine number input for dice roll instead to make like gambling machine

I asked this last night, but didn't get any answers most likely due to my poor formatting of the question so here I am reposting it in a more understandable context;
I made the Java Lotto program for my Java course, and then I was playing with the dice program I made from my Java book, and I was thinking I could make a gambling machine out of the lotto machine by replacing the number input with a dice roll instead. How would I go about swapping the number input for a dice roll? If the question doesn't make sense, let me know. Sorry for posting it twice in a short period of time.
import java.util.Random;
import java.util.Scanner;
class Lottery {
private final int lotteryNumbers[];
public Lottery() {
Random rand = new Random(System.currentTimeMillis());
lotteryNumbers = new int[2];
for (int i = 0; i < lotteryNumbers.length; i++) {
lotteryNumbers[i] = Math.abs(rand.nextInt()) % 90;
}
}
public class Dice {
int die1;
int die2;
Scanner keyboard = new Scanner(System.in);
Random rand = new Random();
}
public int compareNumbers(int[] usersNumbers) {
int match = 0;
if (usersNumbers.length == lotteryNumbers.length) {
for (int i = 0; i < lotteryNumbers.length; i++) {
if (usersNumbers[i] == lotteryNumbers[i]) {
match++;
}
}
}
return match;
}
public int[] getLotteryNumbers() {
return lotteryNumbers;
}
}
public class LottoMachine11 {
public static void main(String[] args) {
String again = "y";
Lottery lottery = new Lottery();
int lotteryNumbersCount = lottery.getLotteryNumbers().length;
while (again.equalsIgnoreCase("y")) {
System.out.println("Lottery application\n");
System.out.println("There are " + lotteryNumbersCount
+ " numbers in range of 0 through 9. "
+ "Try to guess all of them\n");
Scanner keyboard = new Scanner(System.in);
Scanner kb = new Scanner(System.in);
int numbers[] = new int[lotteryNumbersCount];
for (int i = 0; i < numbers.length; i++) {
System.out.print(String.format("Enter number %d: ", i + 1));
numbers[i] = kb.nextInt();
}
int match = lottery.compareNumbers(numbers);
if (match == lotteryNumbersCount) {
System.out.println("\nYou got all the numbers correct. You won the grand prize!");
} else {
System.out.println("Uh oh, you only got " + match + " number(s).");
System.out.print("Play again? (y = yes)? ");
again = keyboard.nextLine();
}
}
}
Well, for starters you're gonna want to generate random dice values between 1 and 6, so you're Dice class should like something like this:
Dice {
int die1;
int die2;
Random rand = new Random();
//Generates random value between 1 and 6 for dice1 and dice2
dice1 = rand.nextInt(6) + 1;
dice2 = rand.nextInt(6) + 1;
}
followed by your getter methods to access the values for dice1 and dice2
Then ask the user to guess the dice values and compare the users input to the dice rolls. I'm not gonna code the whole thing for you, but I hope this pushes you in the right direction!

How do I get the sum of the first two sequences when the user enters "2" as "n"?

The sequence is: sum = 1 + 1/2 + 1/4 + 1/9 + 1/16 + 1/25+...
When I enter "2" it just gives me the sum of 1.25. How do you get it so when "2" is entered, it is adding 1 + 1/2?
Oh and I'm in an entry level java course so I we cant use arrays or anything that advance yet.
Thanks in advance!
import java.util.Scanner;
public class Sum
{
public static void main(String[] args)
{
//declarations
Scanner scan = new Scanner(System.in);
double sum = 0;
int n;
//input
System.out.println("Enter n: ");
n = scan.nextInt();
//process
for(int counter = 1; counter <= n; counter += 1)
{
sum += 1.0 / (counter*counter);
}
System.out.println("The sum is: " + sum);
}
}
Since you say that 1/2 must be part of the sequence, so be it. (But that's a bizarre sequence and I strongly suggest that you double check this with your professor.) I'll assume that the remainder of the sequence is defined by 1/i2. Note that with these assumptions, the sequence terminates at 1/(n-1)2 rather than 1/n2.
You'll need special handling for the cases n == 1 and n > 1. One possibility is to initialize sum to 1 if n == 1; initialize it to 1.5 if n > 1; and otherwise initialize it to 0. Then start the loop at counter = 2 and change the loop termination condition to counter < n (instead of <=).
You need to manage "1" and "2" as special cases.
import java.util.Scanner;
public class Sum
{
public static void main(String[] args)
{
//declarations
Scanner scan = new Scanner(System.in);
double sum = 0;
int n;
//input
System.out.println("Enter n: ");
n = scan.nextInt();
//process
for(int counter = 1; counter <= n; counter += 1)
{
if (counter == 1)
sum = 1;
else if (counter == 2 )
sum += 1.0/((counter-1)+(counter-1));
else
sum += 1.0 / ((counter-1)*(counter-1));
}
System.out.println("The sum is: " + sum);
}
}
If that's your sequence then you should really start by setting the sum equal to 1.5 and then rest of it will work. Your sequence should be a geometric sequence 1/n^2 I think it's a mistake.
public static void main(String[]args) {
Scanner scan = new Scanner(System.in);
double sum = 1.5;
int n;
//input
System.out.println("Enter n: ");
n = scan.nextInt();
if(n==1)
System.out.println("The sum is: " + 1);
//process
for(int counter = 2; counter <n; counter++) {
double mul = counter*counter;
sum += 1.0/mul ;
}
System.out.println("The sum is: " + sum);
}
Output :
Enter n:
2
The sum is: 1.5
Enter n:
3
The sum is: 1.75
The following code will solve your problem, i have used Math.pow() to get the sequence running and not multiplying it twice.
public static void main(String[] args) throws UnknownHostException {
//declarations
Scanner scan = new Scanner(System.in);
//to generate this sequence we take the first two as constants and start generating from the third onwards
double first = 1;//first number in the sequence
double second = 0.5;//second number in the sequence
double sum = first+second;//adding first and second
int n;
//input
System.out.println("Enter n: ");
n = scan.nextInt();
if(n==1){
System.out.println("The sum is: " + first);
return;
}
if(n==2){
System.out.println("The sum is: " + sum);
return;
}
//process
for(int counter = 2; counter <n; counter += 1)
{
sum += 1.0 / Math.pow(counter, 2);//will be computed when you enter values when n is more than 3
}
System.out.println("The sum is: " + sum);
}
As per your for loop, the sequence generated will be 1 + 1/(2*2) + 1/(3*3)+ ......
So, when you enter 2 => 1+1/(2*2) = 1+0.25=1.25.
Otherwise, your logic is Good. you can implement few exceptions, but as you mentioned that you re new to Java, you ll slowly encounter them.
Happy Learning Java :)

How to sum powers of 2 with while loop

I need to calculate the sum of 2^0+2^1+2^2+...+2^n, where n is a number entered by the user. The main problem is that I don't know how to use the while loop to sum the different result of 2^n up.
Here is what I've tried:
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
int number = 2;
int i = 0;
double sum = 0;
while(power <= i) {
Math.pow(number, i);
sum = sum + Math.pow(number, i);
i = i + 1;
}
int result = (int)Math.pow(number, i);
System.out.println("The sum is: " + result);
}
}
Only you have to do is:
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
double sum = Math.pow(2,power+ 1 ) - 1;
System.out.println("The sum is: " + sum);
}
}
In this link explains the math expresion
All fine, just a few changes.
Change the parts code to
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
int number = 2;
int i = 0;
double sum = 0;
/*Remove this --------> while(power <= i) {*/
while (i <= power) {//it should be this
/*Remove this -------> Math.pow(number, i);*/
sum = sum + Math.pow(number, i);
i = i + 1;
}
System.out.println("The sum is: " + sum);
Your conditional is backwards, it should read:
while (i <= power)
You compute the sum of powers, then completely ignore it, just printing out the result of 2^i. you should be printing out sum, something like:
while (i <= power) {
sum += Math.pow(number, i);
i++;
}
System.out.println("The sum is: " + sum);
For style points this won't handle a negative power, so you'll need to test for that.
Dont understand why do you want to loop in this case. You can do it like :
System.out.println("The sum is: "+(Math.pow(2, power+1)-1 ));
But if you really want to use loop try this :
Scanner reader = new Scanner(System.in);
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
int number = 2;
int i = 0;
double sum = 0;
while(i<=power) {
sum = sum + Math.pow(number, i);
i = i + 1;
}
int result = (int)Math.pow(number, i);
System.out.println("The sum is: " + sum);
Here is a solution with comments to explain the logic. While loops need some kind of variable to control the number of iterations. That variable of course needs to be updated somewhere inside the loop.
You can compute the sum of the powers with the Math.pow() function, obviously. No import statement is needed to use it. I hope this helps. Good luck.
/* Scanner and variable to get and hold user input */
Scanner scan = new Scanner( System.in );
int userInput = 0;
/* Variable to hold the sum, initialized to 0.0 */
double sum = 0.0;
/* Prompt the user, and obtain the reply */
System.out.print( "Enter the exponent: ");
userInput = scan.nextInt();
/* The while loop and it's initialized counter */
int counter = 0;
while( counter <= userInput ){
/* Add each power to sum using Math.pow() */
sum = sum + Math.pow( 2, counter );
/* Watch the output as the loop runs */
System.out.println( "Sum: " + sum );
counter++; // Increment counter, so the loop exits properly
} // End while loop
public class SumofSquare {
public static void main(String[] args) {
// TODO Auto-generated method stub
String c = "123";
char d[] = c.toCharArray();
int a[] = new int[d.length + 1];
for (int i = 0; i < d.length; i++)
a[i] = d[i] - 48;
int r = 0;
for (int i = 0; i < c.length(); i++)
r = r + (int) Math.pow(a[i], a[i + 1]);
System.out.println(r);
}
}
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a number:");
int power=Integer.parseInt(reader.nextLine());
int number=2;
int i=0;
int result=0;
while (power>=i) {
result += (int)Math.pow(number, i);
i++;
}
System.out.println("The result is "+result);
}
}
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a number:");
double power=Double.parseDouble(reader.nextLine());
int number=2;
int i=0;
double sum=0;
while (power>=i) {
sum=sum+Math.pow(number, i);
i++;
}
System.out.println("The sum is "+sum);
}

Finding probability using nested for loops in Java

My problem is that whenever I try to compile and run my program, it says one of my arithmetic problems closer to the end of my code is dividing by zero. Now there is another problem. Whenever the user is prompted to enter the number of rolls, you can input a number and hit enter, but it just skips to the next line and nothing happens. Nothing else in the code happens.
* NOTE *
I can't use arrays in this assignment because it is not covered until the next section.
Here is my assignment here. This is what i'm supposed to be doing. I can't figure out what is going wrong here. My math seems to be correct but something is going wrong.
In short my assignment wants me to find the probability of two 11 sided dice being "rolled" the amount of times the user inputs. For example:
If the user says the dice it to be rolled 100 times it would output it something like this
2s: (insert Probability of having the sum of the 2 dice being 2 after 100 rolls)
3s: (insert Probability of having the sum of the 2 dice being 3 after 100 rolls)
4s: (insert Probability of having the sum of the 2 dice being 4 after 100 rolls)
5s: (insert Probability of having the sum of the 2 dice being 5 after 100 rolls)
and so on.
Here is my code so far:
public static void main(String[] args)
{
//Declare and initialize variables and objects
Scanner in = new Scanner(System.in);
Random randNum = new Random();
int match = 0; //Number of times sum of dice matches the current sum
int die1 = 0; //Random generated numbers
int die2 = 0;
int diceTotal2 = 0;
int diceTotal3 = 0;
int diceTotal4 = 0;
int diceTotal5 = 0;
int diceTotal6 = 0;
int diceTotal7 = 0;
int diceTotal8 = 0;
int diceTotal9 = 0;
int diceTotal10 = 0;
int diceTotal11 = 0;
int diceTotal12 = 0;
int sumOfDice = 0;
double probability2 = 0.0;
double probability3 = 0.0;
double probability4 = 0.0;
double probability5 = 0.0;
double probability6 = 0.0;
double probability7 = 0.0;
double probability8 = 0.0;
double probability9 = 0.0;
double probability10 = 0.0;
double probability11 = 0.0;
double probability12 = 0.0;
//Input: ask user for number of rolls and number of sides on a die
System.out.println("Number of Rolls: ");
int rolls = in.nextInt();
//***************************************************************************************
//Using nested loops, cycle through the possible sums of the dice.
//Roll the dice the given number of times for each sum.
//Count how many times the sum of the dice match the current sum being looked for.
//***************************************************************************************
//Loop to increment through the possible sums of the dice
//Loop to throw dice given number of times
for( int numberOfRolls = 1; numberOfRolls < rolls; numberOfRolls++)
{
die1 = randNum.nextInt(6);
die2 = randNum.nextInt(6);
sumOfDice = die1 + die2;
for( ; ; )
{
//Check if the sum of dice is equal to the given sum
if(sumOfDice == 2)
{
diceTotal2++;
probability2 = diceTotal2 / numberOfRolls;
}
else if(sumOfDice ==3)
{
diceTotal3++;
probability3 = diceTotal3 / numberOfRolls;
}
else if(sumOfDice ==4)
{
diceTotal4++;
probability4 = diceTotal4 / numberOfRolls;
}
else if(sumOfDice ==5)
{
diceTotal5++;
probability5 = diceTotal5 / numberOfRolls;
}
else if(sumOfDice ==6)
{
diceTotal6++;
probability6 = diceTotal6 / numberOfRolls;
}
else if(sumOfDice ==7)
{
diceTotal7++;
probability7 = diceTotal7 / numberOfRolls;
}
else if(sumOfDice ==8)
{
diceTotal8++;
probability8 = diceTotal8 / numberOfRolls;
}
else if(sumOfDice ==9)
{
diceTotal9++;
probability9 = diceTotal9 / numberOfRolls;
}
else if(sumOfDice ==10)
{
diceTotal10++;
probability10 = diceTotal10 / numberOfRolls;
}
else if(sumOfDice ==11)
{
diceTotal11++;
probability11 = diceTotal11 / numberOfRolls;
}
else if(sumOfDice ==12)
{
diceTotal12++;
probability12 = diceTotal12 / numberOfRolls;
}
}
}
System.out.println("Sum of Dice" + " " + "Probability");
System.out.println("2s: \t\t" + probability2 + "%");
System.out.println("3s: \t\t" + probability3 + "%");
System.out.println("4s: \t\t" + probability4 + "%");
System.out.println("5s: \t\t" + probability5 + "%");
System.out.println("6s: \t\t" + probability6 + "%");
System.out.println("7s: \t\t" + probability7 + "%");
System.out.println("8s: \t\t" + probability8 + "%");
System.out.println("9s: \t\t" + probability9 + "%");
System.out.println("10s: \t\t" + probability10 + "%");
System.out.println("11s: \t\t" + probability11 + "%");
System.out.println("12s: \t\t" + probability12 + "%");
//After all throws, calculate percentage of throws that resulted in the given sum
} //end main
As you already have a solution, I would present you with another one:
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int nRolls = 100, nDice = 6; // default values
Scanner in = new Scanner(System.in);
System.out.print("Number of throws: ");
nRolls = in.nextInt();
System.out.print("Number of sides on the dices: ");
nDice = in.nextInt();
int minSum = 2, maxSum = 2 * nDice;
int[] hist = new int[maxSum - minSum + 1];
Random rand = new Random();
for (int iter = 1; iter <= nRolls; iter++) {
int throw1 = 1 + rand.nextInt(nDice), throw2 = 1 + rand.nextInt(nDice);
int sum = throw1 + throw2;
hist[sum - minSum]++;
}
System.out.println("Number of rolls: " + nRolls);
System.out.println("Number of sides of the dice: " + nDice);
System.out.println("Sum of Dice Percentage");
for (int i = 0; i < hist.length; i++) {
System.out.println(String.format(" %2d %5.2f%%", i + minSum, hist[i] * 100.0 / nRolls));
// System.out.println(" " + (i+minSum) + " " + (hist[i]*100.0/nRolls);
}
in.close();
}
}
It shows you how to use arrays to solve this task. Each entry in the array holds the number of throws that came up with the corresponding sum. You always have 2*nDice - 1 possible sums (you can not reach 1 with two dices), so the size of the array is dependent on the number of sides on the dice.
Then you just iterate through all throws and add 1 to the corresponding histogram entry (note that I offset the histogram, so hist[0] corresponds to a sum of 2, hist[1] to a sum of 3, etc).
At the end, you can just calculate the percentage. (It's not a probability, it's the percentage that this sum occured in our simulation. If you make the number of rolls larger, this percentage will be an approximation of the probability.)
At the end, you just print it out. The String.format stuff is just for alignment of the values. If you are confused about it, just use
System.out.println(" " + (i+minSum) + " " + (hist[i]*100.0/nRolls);
instead.
Change numberOfRolls initiation to 1 instead of 0.
for( int numberOfRolls = 1; numberOfRolls <= rolls; numberOfRolls++) {
If numberOfRolls is 0, all your division operations results in divide by ZERO.
probability2 = diceTotal2 / numberOfRolls;

Categories