i searched this site and found similar codes but a little different. For my lab in class the instructions say that I need to roll N die , M times and display the number of times a roll occurs in a frequency table. so I'm having a bit of trouble setting up the data in my frequency table. The frequency table prints right but my numbers are wrong. I feel like I'm missing something either and array or an increment? Please Help
my input:
import javax.swing.*;
import java.awt.*;
import java.util.*;
public class Lab1
{
public static void main(String[] arg)
{
Random ran = new Random();
String n = JOptionPane.showInputDialog(null,"How many dice?: ");
String m = JOptionPane.showInputDialog(null,"How many rolls?: ");
int die = Integer.parseInt(n);
int roll = Integer.parseInt(m);
int count = 0;
int[] rollArr = new int[die*6+1];
for(int i=0;i<rollArr.length;i++)
{
rollArr[i] = 0;
}
for( int i=0; i<roll;i++)
{
count = die*1 + ran.nextInt ( 6 );
++rollArr[count];
}
for(int r=1;r<rollArr.length;r++)
System.out.println(r + ":" + rollArr[r]);
}
}
The example says to roll 4 dice 1,000,000 times to get a bell curve but my curve has alot of zeroes.
my output:
1:0
2:0
3:0
4:166309
5:166424
6:166523
7:166984
8:167286
9:166474
10:0
11:0
12:0
13:0
14:0
15:0
16:0
17:0
18:0
19:0
20:0
21:0
22:0
23:0
24:0
I'll just give a hint since this is a lab assignment.
I believe your instructor wants to see the distribution of sums of the die rolls, since that's what will show up as a bell curve. So your array would have to capture and count the possible sums. For example, if you rolled four dice, then the possible sums are 4-24, and you would tally those up.
Related
I have ran into a bit of trouble with some code i had to write for my course.
I had to write a random number generator which run's through the numbers one to fifty, ten thousand times and then only print out the top 15 highest occurring numbers. I have managed to do everything correctly except printing out the top 15 highest.
Here is my full block of code
package section4;
import java.util.Random;
public class Lottery {
public static void main(String[] args) {
Random rand = new Random();
int freq[] = new int[51];
for(int roll = 1; roll<1000000;roll++){
++freq[1+rand.nextInt(50)];
}
System.out.println("Lottery Number\tFrequency");
for(int face = 0; face<freq.length ;face++){
System.out.println(face+"\t"+freq[face]);
}
}
}
I have tried using an ArrayList.
I first created the ArrayList and then added face and freq[face] to the arraylist and then printed the elements of the ArrayList. I tired it on a slim chance and as I thought I was wrong.
package section4;
import java.util.ArrayList;
import java.util.Random;
public class Lottery {
public static void main(String[] args) {
Random rand = new Random();
int freq[] = new int[51];
ArrayList<Integer> top = new ArrayList<Integer>(15);
for(int roll = 1; roll<1000000;roll++){
++freq[1+rand.nextInt(50)];
}
System.out.println("Lottery Number\tFrequency");
for(int face = 0; face<freq.length ;face++){
top.add(face);
top.add(freq[face]);
System.out.println(top);
}
}
}
And I have also tried to change the "For Statement" but I also knew that changing it to what I did only tells the compiler to run from 0 - 15 and not the full 50.
for(int face = 0; face< 15 ;face++){}
Can anyone help, as to how I can print out only the 15 highest, as I have been stuck on this for days.
int[] b =Arrays.copyOf(freq, 5);
Arrays.sort(b);
for(int i = 0 ; i < 15 ; i++){
System.out.println(b[50 - i]);
}
You may use a SortedMap to store the frequency as Key and number as the Value. Then just iterate over the map in the order you want.
The Question:
Write a program that rolls two dice and adds their sum 36,000,000 times and prints how many times each sum was calculated.
So obviously I need to get a rand for 6 numbers twice and add them - in a loop for 36 million times, and then get a frequency counter for however many times each sum was found (which ranges from 2 to 12).
Now given the fact that I'm not very experienced in Java, I ran into a couple of problems.
This is the code that I've got so far:
package twodice;
import java.util.Random;
public class TwoDice
{
public static void main(String[] args)
{
int sum;
Random randomNumbers = new Random();
int[] frequency = new int[13];
for (int roll = 2; roll <= 36000000; roll++)
{
++frequency[(1 + randomNumbers.nextInt(6)) + (1 + randomNumbers.nextInt(6))];
}
System.out.printf("%s%10s\n", "Face", "Frequency");
for(int face = 1; face < frequency.length; face++)
{
System.out.printf("%4d%10d\n", face, frequency[face]);
}
}
}
Output:
run:
Face Frequency
1 6001537
2 6003025
3 5997753
4 5997647
5 6000769
6 5999269
7 0
8 0
9 0
10 0
BUILD SUCCESSFUL (total time: 0 seconds)
The problems are that:
1. The sums that are displaying are not 2-12, they're 1-10 (The right number of sums, just not the right sums...
2. The frequencies are only being found for 1-6, not 1-6 + 1-6.
Thanks for all of your help!
EDIT: Solved by Oscar Lopez! Thanks so much man!
For the first problem, the array has the wrong size, this should fix it:
int[] frequency = new int[13];
Also the values at indexes 0 and 1 will always be 0, so the loop should start at face = 2. For the second problem, the program should simulate throwing two dice, not just one as it currently is. Try this:
++frequency[(1 + randomNumbers.nextInt(6)) + (1 + randomNumbers.nextInt(6))];
Also change your for loop. Final code looks like this:
import java.util.Random;
public class TwoDice
{
public static void main(String[] args)
{
Random randomNumbers = new Random();
int[] frequency = new int[13];
for (int roll = 1; roll <= 36000000; roll++)
{
++frequency[1 + (randomNumbers.nextInt(6)) + (1 + randomNumbers.nextInt(6))];
}
System.out.printf("%s%10s\n", "Face", "Frequency");
for(int face = 2; face < frequency.length; face++)
{
System.out.printf("%4d%10d\n", face, frequency[face]);
}
}
}
I ran this, and it works as you might expect.
My previous question was similar to this, except I did not mention my ending goal,
In this code I have one die, and I print out the number of times it rolls a 4. Now I want to know if I have two dice, both six sided, how many times both would roll 2 and thus add to 4.
However, I would need to use arrays because it is mandatory in this assignment. I have tried adding another exception in the if statement, except I keep realizing that I need to be actually using arrays in the program. 1000 arrays should be stored, since the dice has to roll 1000 times, and thus check how many times it added to 4 from the rolls, then print the amount of times.
import java.io.*;
public class dont {
public static void main(String[] args) throws Exception {
// System.out.println(input());
int[] counts = new int[13];
System.out.print("The number of times it rolls 4 on two 6 sided dice :" + counts);
}
public static int input () throws IOException {
BufferedReader myInput = new BufferedReader (new InputStreamReader
System.out.println("Hello and welcome to the program");
System.out.println("In this program two six sided dices will be rolled and one eleven
sided dice will be rolled (1000 times each");
int sum;
int[] counts = new int[13];
System.out.println("The dices will be rolled to determine the odds of how many times the roll 2 comes up on both dies(Press any key to con't) ");
myInput.readLine();
//int count2=0;
int Sixside;
for (int i = 0; i < 1000; i++)
{
// two dice that add to 4, after being rolled one thousand times
Sixside = (int)(Math.random ()*6+1)+(int)(Math.random ()*6+1) == 4;
//print the number of times they add to 4
counts[sum]++;
}
counts[i] = Sixside;
{
//return array to main
return counts [13];
}
}
}
Your example produces reasonable answers for two dice that sum to 4. I suspect you're supposed to create an array that can hold sums for any pair with a sum between 2 and 12, for example:
int[] counts = new int[13];
Then you don't need an if statement in your loop; you can just increment the count for that sum, for example:
counts[sum]++;
This table can help you decide if your other counts are reasonable.
Addendum: Here's a simplified version of your method:
public static int[] input() {
int[] counts = new int[13];
for (int i = 0; i < 1000; i++) {
int sum = // your expression for the sum of two dice
counts[sum]++;
}
return counts;
}
You can call it like this and examine any particular total, e.g. counts[4].
int[] counts = input();
I am trying to make a program that takes an input for #players and #dice and rolls the dice whatever number of times for each player. It then outputs the rolls and the total.
So far I've managed to develop a program that can roll as many dice as inputted and store these values in an array, which it then sums and outputs.
Unfortunately, I'm stuck as of now because I don't really have any clue what to do when trying to make the program do this again each time for a new player. I understand it would probably be with an incrementer, but I'm just really overwhelmed by the complexity and don't even know what I would look for online.
Here is my code:
package diceroll;
import java.util.ArrayList;
import java.util.Scanner;
public class DiceRoll {
public static void main(String[] args) {
int numplayers = 0, numdice = 0; // incrementers for #rolls and #players
// ArrayList<ArrayList> players = new ArrayList<ArrayList>();
// players.add(rolls); /// adding list to a list
// System.out.println(players);
ArrayList<Integer> rolls = new ArrayList<>();
System.out.println("Enter the number of players.");
Scanner scan = new Scanner (System.in);
numplayers = scan.nextInt();
System.out.println("Enter the number of dice.");
numdice = scan.nextInt();
while (numdice > 0 ) {
Die die1 = new Die();
die1.roll();
rolls.add(die1.getFaceValue());
numdice--;}
System.out.println(rolls);
// sum for array, but i cant access the arraylength
int total = 0;
for (int n : rolls) //what does the colon : do ?
{total += n;
System.out.println("Dice total:" + total);
}
}
}
There is also a basic Die.java class that assigns a random number to face value and has the roll method I use to randomize the die.
Output:
run:
Enter the number of players.
1
Enter the number of dice.
4
[5, 4, 6, 6]
5
9
15
The only problem is changing the number of players currently has no effect.
21
You may probably want to use another loop outside your while loop, if you want to repeat the #dice for all the players.
The for(int i:rolls) --> this statement is read as "for each integer 'i' in rolls" which means, for every iteration of the loop, the values in rolls are assigned to y:
And this is equivalent to
for(int j=0;j<rolls.size();j++){
i = rolls[j];
// Other statements goes here.
}
I am triying to create random value for my game to show enemies on screen. BUt it some times shows 2 together some times 3 ...I want to ask that which is the best formul for creating random value.. This is my so far random value
random = 1 * (int) (Math.random() * 100);
"BUt it some times shows 2 together some times 3"
Given perfectly random numbers... In every 100 random values from 0 to 99, you'll find an average of 1.0 doubles. A triple will occur on average once for every 10,000 values. Given 10 million random numbers, java.util.Random yeilds the following results on my machine:
Doubles: 99873
Triples: 985
Double Rate: 1 in 100
Triple Rate: 1 in 10152
Source code:
import static java.lang.System.*;
import java.util.Random;
public class Sandbox {
public static final int NUM_ITERATIONS = 10000000;
public static void main(String[] args) {
Random rand = new Random();
int cur;
int last = -1;
int secondLast = -2;
int nDoubles = 0;
int nTriples = 0;
for (int i = 0; i < NUM_ITERATIONS; i++) {
cur = rand.nextInt(100);
if (cur == last) {
nDoubles++;
if (cur == secondLast) nTriples++;
}
secondLast = last;
last = cur;
}
out.println("Doubles: " + nDoubles);
out.println("Triples: " + nTriples);
out.println();
out.println("Double Rate: 1 in " + Math.round(1.0 * NUM_ITERATIONS / nDoubles));
out.println("Triple Rate: 1 in " + Math.round(1.0 * NUM_ITERATIONS / nTriples));
exit(0);
}
}
Actually the creation of genuinely random random numbers is a complex game in its own right. The Wikipedia article on this subject will give you an insight into the complexity that lies therein. Simple approximations such as those outlined above are probably sufficient for game purposes but will, it should be noted, be inclined to be 'streaky' from time to time.
You can use java.util.Random:
Random random = new Random(); // uses System.nanoTime() as seed
int enemies = random.nextInt(100);
Anyway, your approach is also fine, as it is in fact equivalent (behind the scene) with the above.
You can print a sequence of 100 random numbers generated your way and see for yourself that there isn't a problem.
What you use if perfectly fine.
In case you want something simplier you might like to use Random class like this:
Random generator = new Random(seed);
int number = generator.nextInt(100);
...and sometimes 77, sometimes 23, etc, as expected in a uniform distribution?
If you would like a normal distribution instead for your "enemies", so that extremes are less likely, it seems to be there in Java.