How to count the number of time sum is = 7? - java

I have to make program to roll 2 dice 100 times, and count the # of time the sum equals 7.
I tried doing a count for loop to count the sums = 7, but think I'm getting off base somewhere in the logic of that.
// int i = 0; No. of rolls
// int count = 0; No. of rolls = to 7
for (int i = 0; i <= 100; i++){
int dice1 = randomGenerator.nextInt(7);
int dice2 = randomGenerator.nextInt(7);
int sum = (dice1 + dice2);
System.out.println(dice1 + ", " + dice2 + ", total: " + sum + " roll: " + i);
}
for (int count = 0; count++) {
System.out.println(count);
}
System.out.println("Total number of time sum equaled 7 was " + count);
I'm getting the random rolls, roll count, and sum of dice correctly, Just need to figure out how to add a sum = 7 count and I'm getting stuck.

Here's another answer using streams
public static void main(String[] args){
Random rng = new Random();
long result = IntStream
.generate(() -> rng.nextInt(6) + rng.nextInt(6) + 2)
.limit(100)
.filter(x -> x == 7)
.count();
System.out.println("Total number of time sum equaled 7 was " + result);
}

Just replace your for (int count = 0; count++) { ... } with if (sum==7) count++ and put it after int sum = (dice1 + dice2);
This increases count if the sum is 7 within the loop of your 100 double dice rolls.
To remove the wrong dice range (0-7, see comment #Robby Cornelissen) just do a randomGenerator.nextInt(6)+1.
int count = 0; // No. of rolls = to 7
for (int i = 0; i <= 100; i++){
int dice1 = randomGenerator.nextInt(6)+1;
int dice2 = randomGenerator.nextInt(6)+1;
int sum = (dice1 + dice2);
if (sum==7) count++;
System.out.println(dice1 + ", " + dice2 + ", total: " + sum + " roll: " + i);
}
System.out.println("Total number of time sum equaled 7 was " + count);

Using Java 8, program would look like this :
public class Dice
{
static int count = 0;
static Random ran = new Random();
public static void main(String[] args)
{
IntStream.rangeClosed(1, 100). // iterates 1 to 100
parallel().// converts to parallel stream
forEach(i -> {
rollDiceAndCheckIfSumIs7();
});// prints to the console
System.out.println("Out of 100 times, total number of times, sum was 7 is :" + count);
}
private static void rollDiceAndCheckIfSumIs7()
{
int dice1 = ran.nextInt(7);
int dice2 = ran.nextInt(7);
count += (dice1 + dice2 == 7) ? 1 : 0;
}
}

Related

Dividing until a certain number is reached and storing how many times the loop divided

If you divide 1 by 2, you get 0.5. If you divide it again by 2, you get 0.25. Write a program that calculates and outputs the number of times you have to divide 1 by 2 to get a value less than one ten-thousandth (0.0001).
I have a for loop that should be working but its not returning any results
public class Main {
public static void main(String[] args) {
double count ;
for(double i = 1; i<= 0.0001; count++){
count = i/2;
System.out.println("You have to divide 1 " + count + "times to get 0.0001");
}
The program runs it just doesn't return anything.
Try this
int count = 0;
double i = 1;
while(i >= 0.0001){
i = i/2;
count++;
System.out.println("You have to divide 1 " + count + " times to get 0.0001");
}
Probably you only want to print out after the loop
Before the value of count was never being used to evaluate the loop. Try having two variables.
Ok I got it just had to switch some things around
public class Main {
public static void main(String[] args) {
int count = 0;
for (double i = 1; i >= 0.0001; count++ ) {
i = i / 2;
}
System.out.println("You have to divide 1 " + count + " times to get 0.0001");
You could use below code .
int count = 0;
for(double i = 1; i>= 0.0001; ){
i = i/2;
count++;
System.out.println("You have to divide 1 " + count + " times to get " + i);
}
You can translate your equation:
x / y^n <= z
to
n >= log(x/z) / log(y)
And therefore it's simply:
public static void main(String[] args) {
System.out.println("You have to divide 1 " + Math.ceil(Math.log(1.0 / 0.0001) / Math.log(2)) + " times by 2 to get 0.0001");
}

Calculate the number of pyramid

I'm trying to calculate the sum of the numbers in my pyramid in java. For this, mathematical rule is 2+5+8+9. I mean first row+first number of second row+ second number of third row like that.
int[] numbers = { 2,5,7,1,8,3,6,0,9,4 };
System.out.println(" " + numbers[0]);
System.out.println(" " + numbers[1] + " " + numbers[2]);
System.out.println(" " + numbers[3] + " " + numbers[4] + " " + numbers[5]);
System.out.println("" + numbers[6] + " " + numbers[7] + " " + numbers[8] + " " + numbers[9]);
For example:
2
5 7
1 8 3
6 0 9 4
How can I calculate 2+5+8+9 in Java?
The simplest way of calculating 2+5+8+9 is using Java build-in feature:
int result = 2+5+8+9;
You should construct your pyramid as a 2D array.
int[] numbers = { 2,5,7,1,8,3,6,0,9,4 };
int addedElements = 0;
int nextSize = 1;
ArrayList<int[]> pyramid = new ArrayList<>();
while(addedElements< numbers.size()) {
int[] level = new int[nextSize++];
for (int i = 0; i < nextSize - 1; i++) {
level[i] = numbers[addedElements++];
}
}
int result = 0;
//add maximum of each `int[]` in pyramid.
for (int[] array : pyramid) {
int currentMax = array[0];
for (int i = 0; i < array.size(); i++) {
if (array[i] > currentMax) {
currentMax = array[i];
}
result+=currentMax;
}
System.out.println(result);
Try the follwoing code :
int[] numbers = { 2,5,7,1,8,3,6,0,9,4 };
int index = 1;
int number = 2;
int result = numbers[0];
while (index < numbers.length) {
result += numbers[index + number -2];
index += number;
number += 1;
}
System.out.println(result);
But the whole whing would be much easier and clearer if you just put your pyramide into a 2 dimensional array.
int[][] numbers = { {2},
{5,7},
{1,8,3},
{6,0,9,4} };
int result = numbers[0][0];
for (int i = 1; i < numbers.length; i++) {
result += numbers[i][i-1];
}
System.out.println(result);

Generate a random number and sort odd and even numbers using JOptionPane

my first question here. My assignment is to generate a random number between 1 and 10, 20 times. After that I'm supposed to somehow write the numbers into two separated strings for Odd and Even numbers. We're also supposed to count how many total numbers we had for each group of numbers. This is what I have so far, I need help on how to display the separated numbers. I would like to use JOptionPane as well please, but any help is appreciated!
package lab5arudy;
import javax.swing.JOptionPane;
public class Lab5ARudy
{
public static void main(String[] args)
{
int randomNumber = 0;
int evenNumbers = 0;
int oddNumbers = 0;
String evenNums;
String oddNums;
for (int i = 0; i < 20; i++)
{
randomNumber = 1 + (int) (Math.random() * 10);
if (randomNumber % 2 ==0)
{
evenNumbers++;
}
else
oddNumbers++;
}
JOptionPane.showMessageDialog(null,"Even Numbers: " + evenNumbers);
JOptionPane.showMessageDialog(null,"Even Numbers: " + oddNumbers );
}
}
It sounds as though you just need to add all your random numbers to lists so that you can print them afterwards. Something like the following:
Random rand = new Random();
List<Integer> odds = new ArrayList<>();
List<Integer> evens = new ArrayList<>();
for (int i = 0; i < 20; i++) {
int next = rand.nextInt(10) + 1;
if (next % 2 == 0)
evens.add(next);
else
odds.add(next);
}
showMessageDialog("Even :" + evens + " (" + evens.size() + ")");
showMessageDialog("Odds :" + odds + " (" + odds.size() + ")");
You can do it like this.
public static void main(String[] args) {
int randomNumber;
int evenNumbers = 0;
int oddNumbers = 0;
String evenNums = "";//initialize empty strings
String oddNums = "";//initialize empty strings
for (int i = 0; i < 20; i++) {
randomNumber = 1 + (int) (Math.random() * 10);
if (randomNumber % 2 == 0) {
evenNumbers++;
if (evenNums.equals("")) {//if the evenNums is empty, append the number
evenNums = evenNums + randomNumber;
} else {
evenNums = evenNums + "," + randomNumber;//if the evenNums is not empty, append the number with a , in between
}
} else {
oddNumbers++;
if (oddNums.equals("")) {
oddNums = oddNums + randomNumber;//if the oddNums is empty, append the number
} else {
oddNums = oddNums + "," + randomNumber;//if the oddNums is not empty, append the number with a , in between
}
}
}
JOptionPane.showMessageDialog(null, "Even Numbers: " + evenNumbers+"\n"+evenNums);//Show the even numbers
JOptionPane.showMessageDialog(null, "Odd Numbers: " + oddNumbers+"\n"+oddNums);//Show the odd numbers
}

Passing array through average method, resulting in low percent

For some reason the average is being populated wrong when I pass the array to the method I get a really low percent. It almost seems like since the Array shotsMade is only recording integers for made shots and not misses it is not calculating off the right base.
import java.util.*;
public class Test {
public static void main(String[] args) {
int myGameCounter = 1;
int shotCount = 0;
int shotCount1 = 0;
int [] shotsMade = new int [5];
int sum = 0;
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
//Game #1
System.out.println("Game " + myGameCounter + ":");
Random r = new Random();
myGameCounter++;
shotCount = 0;
for (int i = 0; i < 10; ++i){
boolean in = tryFreeThrow(percent);
if (in) {
shotCount++;
System.out.print("In" + " ");
}
else {
System.out.print("Out" + " ");
}
}
System.out.println("");
System.out.println("Free throws made: " + shotCount + " out of 10");
shotsMade[0]= shotCount;
//Game #2
System.out.println("");
System.out.println("Game" + myGameCounter + ":");
myGameCounter++;
shotCount1 = 0;
for (int i = 0; i < 10; ++i){
boolean in = tryFreeThrow(percent);
if (in) {
shotCount1++;
System.out.print("In" + " ");
}
else {
System.out.print("Out" + " ");
}
}
System.out.println("");
System.out.println("Free throws made: " + shotCount1 + " out of 10");
shotsMade[1]= shotCount1;
System.out.println("");
System.out.println("Summary:");
System.out.println("Best game: " + max(shotsMade));
System.out.println("Total Free Throws Made: " + sum(shotsMade) + " " + "out of 20");
System.out.println("Average Free Throw Percentage: " + average(shotsMade) +"%");
}//main
public static boolean tryFreeThrow(int percent) {
Random r = new Random();
int number = r.nextInt(100);
if (number > percent){
return false;
}
return true;
}
public static float average(int nums[]) {
int total = 0;
for (int i=0; i<nums.length; i++) {
total = total + nums[i];
}
float f = (total / nums.length);
return (float)total /(float)nums.length;
}
public static int sum(int nums[]) {
int sum = 0;
for (int i=0; i<nums.length; ++i) {
sum += nums[i];
}
return (int)sum;
}
public static int max(int nums[]) {
int max=nums[0];
for (int i=1; i<nums.length; i++) {
if (nums[i] > max)
max = nums[i];
}
return max;
}
}//class
You are calculating the avarage of 5 numbers but you only set 2. So if all shots hit your array will look like this: 10, 10, 0, 0, 0 and the avarage will be 4.
Old issue, you are using integer arithmetic total / nums.length with returns you an int value. You later assign it to a float, but the value already has been truncated.
Just change one of the values to float before the division, v.g. ((float) total) / num
Among others, your expression
float f = (total / nums.length);
will yield an inaccurate result.
Both total and nums.length are integers, and any operation between integers always results in an integer.
Example: if total=10 and nums.length=3, you'd expect the result to be 3.333... but actually the result is just 3. Only after that do you cast it to a float, resulting in 3.0.
To get the required result, you need to cast both integers to floats before dividing:
float f = (float) total / (float) nums.length;

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