This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 6 years ago.
I am kind of new in Java, and I got assigned some exercises. Any idea how to this small problem?
create an array consisting of 100 random integers in the range 100 to 500, including the end points.
make a method to print the array, 5 numbers per line, with a space between each.
make a method to print the smallest number in the array.
So far this is what i got for the first 2 parts but i doesn't seem work, help please, sorry for asking such dumb questions...
package randomhundred;
import java.text.DecimalFormat;
public class RandomHundred {
public static void main(String[] args) {
//setting the 100 array
int rand [] = new int [100];
double numb;
DecimalFormat dec = new DecimalFormat("0");
for(int i=0; i<rand.length; i++){
numb = Math.random() * ( 500 - 100 );
}
}
public static int arai (){
return System.out.print(" " + dec.format(numb) + " ");
}
}
Let's get step 1 right.... generating 100 random values.
Your process is nearly there.... but:
it does not generate an int value so you can't store it in an int[] array.
it will never generate the value 500.
To convert the random number to an integer, try the following:
int numb;
....
numb = (int)(Math.random() * ( 500 - 100 ));
but, this will not generate the value 500 (because 500 - 100 is 400, but, there's actually 401 numbers you need to generate....), so change it to (see How do I generate random integers within a specific range in Java?):
numb = 100 + (int)(Math.random() * ( (500 - 100) + 1))
Now we have random numbers between 100 and 500 (inclusive), you need to store them in your array now:
rand[i] = numb;
Once you have that working, come back and we can tackle the other problems.
until then, you can print out your array with:
System.out.println(Arrays.toString(rand)); // Arrays is java.util.Arrays
I'll try to supply some pseudo code for your problem:
// Task 1
Declare array of 100 ints (I will relate to 100 later on with n).
Fill array with random integers between 100 and 500 including borders
Hint code for this: 100 + new Random().nextInt(401), 401 as the upper bound is exclusive which makes the max result: 100 + 400 -> 500 and the minimum: 100 + 0 = 100. Even though this will generate the 100 numbers it will be faster if you store the random instance somewhere and re-use it, but that's an optimization step.
// Task 2
for i = 0; i < n; i++
print integer from array
add space
if i is divisible by 5 then
add new line
end-if
end-for
//Task 3
declare a min of the maximum value which is possible: in this case your maximum random number of 500
loop through the list checking for smaller numbers
after loop has finished print the last number
I hope this is clear enough for you get an idea on how this could be done.
Ad. 1
For the sake of completeness (it's been explained by others):
for(int i=0; i<rand.length; i++){
rand[i] = 100 + (int)(Math.random() * ( 401 ));
}
Ad. 2
This is wrong:
public static int arai (){
return System.out.print(" " + dec.format(numb) + " ");
}
Return type is int, but System.out.print() doesn't return anything, so change int to void and remove return keyword. Next, you'll need to iterate through the whole array:
public static void arai (){
for (int i=0; i< 100; i++) {
//this is modulo, which means that if i divided by 5 has no remainder, print next line
//eg. 5%2 = 1, because 2*2 + 1 = 5
//5%3 = 2 and so on, read here http://en.wikipedia.org/wiki/Modulo_operation
if (i%5 == 0) {
System.out.println();
}
//finally, print each value from rand array
System.out.print(rand[i] + " ");
}
}
Ad. 3
Try yourself, and comeback if you have issues, but follow Johnnei's advice of finding the smallest number.
NOTE: you also need to make the rand array declaration global, so that it's available to arai() method.
Related
I am having trouble getting the percentage of the frequency to print. Below is the question:
Write a program to simulate the rolling of two dice. The program should use an object of class Random once to roll the first die and again to roll the second die. The sum of the two values should then be calculated. Each die can show an integer value from 1 to 6, so the sum of the values will vary from 2 to 12, with 7 being the most frequent sum and 2 and 12 being the least frequent sums. Your application should roll the dice 36,000 times. Use a one dimensional array to keep track of the number of times each possible sum appears. Display the results in tabular format. Determine whether the totals are reasonable (e.g., here are six ways to roll a 7, so approximately one-sixth of the rolls should be 7). Sample output:
Sum Frequency Percentage
2 1027 2.85
3 2030 5.64
4 2931 8.14
5 3984 11.07
6 5035 13.99
7 5996 16.66
8 4992 13.87
9 4047 11.24
10 2961 8.23
11 1984 5.51
12 1013 2.81
This is my code so far:
import java.util.Random;
public class dice_roll {
public static void main(String [] args){
Random rand = new Random();
int dice1, dice2;
int [] frequency = new int [13];
int [] rolls = new int [13];
int sum;
double percentage;
for (int i = 0; i <= 36000; i++) {
dice1 = rand.nextInt(6)+1;
dice2 = rand.nextInt(6)+1;
frequency[dice1+dice2]++;
sum = dice1 + dice2;
}
System.out.printf("Sum\tFrequency\tPercentage\n");
for (int i = 2; i < frequency.length; i++) {
percentage = (frequency[i] * 100.0) / 36000;
System.out.printf("%d\t%d\t\n",i,frequency[i]);//this line here
}
}
}
First of all, your for loop is off by 1:
for (int i = 0; i <= 36000; i++) {
// ^
// remove this "=" or you will loop 36001 times
Your sum seems redundant, so remove that as well.
I think you just don't know how to format the output so that the floats correct to 2 d.p. right?
It's easy. Just add do %.2f!
Your printf will be like:
System.out.printf("%d\t%d\t%.2f\n",i,frequency[i], percentage);
Another problem with your code is that it might produce unaligned stuff. It also does not align the values to the right as the sample output shows. To fix this, you also just need to change the printf. Like this:
System.out.printf("%3d\t%9d\t%10.2f\n",i,frequency[i], percentage);
If you want to read more about how printf works, list here.
Stealing from this answer: we can use padRight which is defined as:
public static String padRight(String s, int n) {
return String.format("%1$-" + n + "s", s);
}
and do:
System.out.printf("Sum\tFrequency\tPercentage\n");
for (int i = 2; i < frequency.length; i++) {
String s = padRight(String.valueOf(i), 4);
String f = padRight(String.valueOf(frequency[i]), 12);
percentage = (frequency[i] * 100.0) / 36000;
String p = String.format("%.2f", percentage); // This formatting will keep two digits after the point
System.out.printf("%s%s%s\n", s ,f, p);
}
OUTPUT (example)
Sum Frequency Percentage
2 992 2.76
3 2031 5.64
4 3034 8.43
5 3947 10.96
6 4887 13.58
7 5948 16.52
8 4965 13.79
9 4051 11.25
10 3014 8.37
You can play with it and remove the \t from the first line and use spaces instead in order to create the amount of spacing you want between the columns and then pass the second parameter in the calls to padRight accordingly.
import java.util.*;
import java.lang.*;
public class Main {
public static void main(String[] args) {
Random dice = new Random();
int a[]=new int [7];
for(int i = 1 ; i <=100;i++){
++a[1+dice.nextInt(6)];
}
System.out.println("Sno\t Values");
int no;
for(int i=1;i<a.length;i++){
System.out.println(i+"\t"+a[i]);
}
}
}
Sno Values
1 19
2 13
3 16
4 16
5 19
6 18
Can any one please explain this line "++a[1+dice.nextInt(6)]"
i know this program provides random number generated from 1-6 on how many times within the given value
Mostly, that's just hard to read code. It would be at least slightly simpler to read (IMO) as
a[dice.nextInt(6) + 1]++;
... but it's easier still to understand it if you split things up:
int roll = dice.nextInt(6) + 1;
a[roll]++;
Note that there's no difference between ++foo and foo++ when that's the whole of a statement - using the post-increment form (foo++) is generally easier to read, IMO: work out what you're going to increment, then increment it.
Random.nextInt(6) will return a value between 0 and 5 inclusive - so adding 1 to that result gets you a value between 1 and 6 inclusive.
Yes, first you have
int a[]=new int [7];
which is an array that can hold 7 elements (valid indices being 0-6), all of which have an initial value of 0. Then
++a[1+dice.nextInt(6)];
is saying
int randomIndex = 1 + dice.nextInt(6); // <-- a random value 1 to 6 inclusive
a[randomIndex] = a[randomIndex] + 1;
Which is counting how many ones through sixes are rolled.
++a[1+dice.nextInt(6)]
dice.nextInt(6)= return an integer between 0 and 5
then you add 1 to that value, after that you get the element at that index in the array a and you increase that using the ++ operation
nextInt() returns a pseudorandom, uniformly distributed value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.
So the value of 1+dice.nextInt(6) will fall between 1 to 6 (both inclusive) and increment the value of a[x] like a counter for x
This question already has answers here:
Generating an Odd Random Number between a given Range
(10 answers)
Closed 7 years ago.
I'm trying to generate odd numbers randomly. I tried this, but it generates even numbers also:
int coun=random.nextInt();
for(int i=1; i<100; i++){
if(i%2==1){
coun=random.nextInt(i);
}
}
How can I generate odd numbers randomly?
You could add 1 to even numbers
int x=(int) (Math.random()*100);
x+=(x%2==0?1:0);
or multiply the number by 2 and add one
int x=(int) (Math.random()*100);
x=x*2+1;
a lot of possible solutions.
All numbers of the form 2*n + 1 are odd. So one way to generate a random odd number would be, to generate a random integer, multiply it by 2, and add 1 to it:
int n = random.nextInt();
int r = 2 * n + 1; // Where r is the odd random number
For each random number n, there is a unique odd random number r generated (in other words, it is a bijection) - thus ensuring unbiasedness (or at least, as much unbiasedness as the function random.nextInt()).
There is 50 odd numbers between 0 and 100. To select one of them you can do
int n = random.nextInt(50);
to get the n-th odd number you can
int odd = n * 2 + 1;
Putting it all together
int odd = random.nextInt(max / 2) * 2 + 1;
One solution would be to test wheter the random integer value is odd or not. If it is not, you can add or subtract one with half probability.
Random random = new Random();
int i = random.nextInt();
if (i % 2 == 0) {
i += random.nextBoolean() ? 1 : -1;
}
This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 9 years ago.
I'm writing code for a kind of minigame in another game (Minecraft) in Java and I stumbled upon a problem.
I have two ints, int point 1 and int point 2. They are x coordinates, from ex: -100000 to 100000. But also -10000 to -5000, and 10000 to 20000. So negative to positive, but also negative to negative and positive to positive.
And that is the problem. I need to find a solution how to get random numbers from ex -100 to -50. But the same code has to be used with -100 to 50, and 10 to 50.
If you guys can help me, that'd be great!
Greetings,
Jesse.
PS: If you need a code snippet or something, just say it.
Silviu Burcea's comment contains a google search which answers your question. Numbers are numbers. It doesn't matter what sign they have. So going to the first result from the google search gave the answer:
public static void main(String[] args){
Random rand = new Random();
for(int j = 0; j < 100; j++){
// just modified the line from the other thread
// which was "int randomNum = rand.nextInt((max - min) + 1) + min;"
int i = rand.nextInt(-50 - -100 + 1) + -100;
System.out.println("Next value = " + i);
}
}
That prints out pseudo random numbers between -100 and -50. So yeah, your question is a duplicate.
int mix = Math.min(point1, point2) + (int)(Math.abs(point1 - point2) * Math.random()));
EDIT:
int mix = Math.min(point1, point2) + Math.round(Math.abs(point1 - point2) * Math.random()));
EDIT2 :
int mix = Math.min(p1, p2) + (int)Math.round(-0.5f+(1+Math.abs(p1 - p2))*Math.random());
The distirubtion of this expression evaluation seems to be probably better. But this is not an optimised solution in fact.
I'm trying to make a method where you choose 2 number in main and the method finds the highest value between does to numbers.
The program takes a number divides it by 2, if not possible to divide multiply by 3 and add 1, divide again and so on until reaching 1.
output: number 10
6 times
int count = 0;
while( number != 1){
count++;
if(number % 2 == 0){
number = number / 2;
}else{
number = number * 3 + 1;
}
}
return count;
This is what i have so far and i have no idea how to pick 2 number and finding the highest one in between those 2.
Use the java.util.Random for generating random values.
Random r = new Random();
int n1 = r.nextInt();
int n2 = r.nextInt();
If you put what you have in a method that takes an int as a parameter, you can call it twice, once using a java.util.Random - generated number, and again using a different random value. You can store the results of both calls as ints, and compare the two of them. Hope that helps!
int first = reduceNumber(r.nextInt());
int second = reduceNumber(r.nextInt());
Use the Random class to generate random numbers.
To know the maximum of them,
int max = Math.max(n1, n2);
I'm sorry. Those to numbers are pick by me in main. I think i have to use array.
So the output should be like this:
Using Scanner in main.
lowest limit: 2
highest limit: 10000000
the number 837799(method that finds the number) is the one that is divided
the most times: 524(code that counts how many times it has been divided) which i have..
That's how it's suppose to look like. So i don't think random is going to help.