Explain what this code is doing - java

I'm a newbie in java. I was going through some tutorials and came across this code I was not able to understand the code. Please explain what it means.
class Randoms
{
public static void main(String[] args)
{
Random rand = new Random();
int freq[] = new int[7];
for(int roll = 1; roll < 10; roll++)
{
(++freq[1 + rand.nextInt(6)]);
}
...

Line by line:
Random rand = new Random(); create new instance of the Random object, this is responsible for the creation of random numbers.
int[] freq = new int[7]; create a new int array that can store 7 elements, with indices from 0...6. It is worth noting that in Java, the ints stored in the array are initialized to 0. (This is not true for all languages, an example being C, as in C the int arrays initially store memory junk data, and must be explicitly initialized to zero).
for(int roll = 1; roll < 10; roll++) this rolls 9 times (because 1...9, but it's better practice to go from 0)
(++freq[1 + rand.nextInt(6)]); this line is something that you shouldn't ever do in this sort of fashion, because it's a monstrosity as you can see.
Do something like this:
for(int roll = 0; roll < 9; roll++)
{
int randomNumber = rand.nextInt(6); //number between 0...5
int index = 1 + randomNumber; //number between 1...6
freq[index]++; //increment the number specified by the index by 1
//nearly equivalent to freq[index] += 1;
}
So basically it randomizes the number of 9 dice throws, and stores the dice throw count (or so it calls it, frequency) in the array.
Thus, it's simulating 9 dice throws (numbers from 1...6), and each time it "rolls" a particular number, it increases the number stored in the array at that specific location.
So in the end, if you say:
for(int i = 1; i <= 6; i++)
{
System.out.println("Thrown " + freq[i] + " times of number " + i);
}
Then it will be clearly visible what's happened.

(++freq[1 + rand.nextInt(6)]); // this line of code.
The above line of code is pre-incrementing the value of freq[] array at the specified position,i.e., 1+rand.nextInt(6) --- referred value is ++freq[some-position to be evaluated] which we will evaluate below.
This rand.nextInt(6) will generate an integer number lesser than 6 and greater than 0,as it is a pre-defined method of Random Class ,randomly.We can't predict it.
And,then say number generated is 4. SO, 1+rand.nextInt(6)=5.
Hence,your code would simplify to (++freq[1 + rand.nextInt(6)]) OR `(++freq[5]).
So,simplification of this code will be equivalent to a number which equals 1 more than 6th element of array freq[].
// as freq[5] is the 6th element of the array freq[].
Also,there are some other points which SIR David Wallace suggested me to include which I would like to explain a bit more.It goes below :-
++a here ++ is called pre-increment operator and it increases the value of a by 1. There also exists an altered reverse version of it.
a++ here this ++ is called post-increment operator and it also increases the value of a by 1.But,WAIT,you might have thought that there aren't differences,but there are.
For the differences potion,I'd like to suggest to have a reading of What is the difference between pre-increment and post-increment in the cycle (for/while)?, though it is questioned in sense of C++,the same is in Java too!

// Create a new Random Object, this helps you generate random numbers
Random rand = new Random();
// create a integer array with 7 integers
int freq[] = new int[7];
// loop 9 times
for(int roll = 1; roll < 10; roll++)
{
// rand.nextInt(6) generates a number between 0 and 5 (<6). add one to it
// ++ adds one to the integer in the array that is at the index of 1-6.
(++freq[1 + rand.nextInt(6)]);
}
Some strange things about this code:
Roll loop starts at 1 then goes to 10 so at first glance it would seem to loop 10 times but actually runs 9 times.
The ++ inside the loop would generally be located on the right and could lead to some confusion among newer programmers.
freq[1 + rand.nextInt(6)] causes freq[0] to never be used.

At first a new object of the Random-Class and an array with 7 elements are created. Each element of the Array has the value 0. Inside the for-loop you randomly pick element 2 to 7 of the Array and increase its current value by 1. This is done 9 times.
Your code will never pick the first element of the Array which has the index 0.
I would rewrite the code to make it more clear:
Random rand = new Random();
int freq[] = new int[6];
int randomIndex = 0;
for(int roll = 0; roll < 9; ++roll)
{
randomIndex = rand.nextInt(6);
freq[randomIndex] = freq[randomIndex] + 1;
}
This code has not been tested, but it should basicly do the same.

Related

How do I get the code to print random numbers in all the elements of the 2d array?

I got the 2d array to print but with all zero's and the only random number comes up on the bottom right corner
How do I get the code to print random numbers in all the elements of the 2d array?
Here is my code:
public static void main(String[] args) {
int columns = 8;
int rows = 4;
int rLow = 2;
int rHigh = 9;
printRandos(columns, rows, rLow, rHigh);
}
public static void printRandos(int clmn, int rws, int rlow, int rhigh) {
Random rando = new Random();
int randoNum = rlow + rando.nextInt(rhigh);
int[][] randoArray = new int[rws][clmn];
for (int i = 0; i < rws; i++) {
for (int k = 0; k < clmn; k++) {
randoArray[rws - 1][clmn - 1] = randoNum;
System.out.print(randoArray[i][k] + " ");
}
System.out.print("\n");
}
}
for (int i = 0; i < rws; i++)
{
for (int k = 0; k < clmn; k++)
{
int randoNum = rlow + rando.nextInt(rhigh);
randoArray[i][k] = randoNum;
System.out.print(randoArray[i][k]+" ");
}
System.out.print("\n");
}
your mistake inside the inner for loop of the printRandos method. Firstly your random number is outside the loop so your array elements were receiving the same number all the time. Another mistake is that you are assigning the value to the same array element all the time i.e rws-1 and clmn-1 .
inside your inner loop replace it with this:
int randoNum = rlow + rando.nextInt(rhigh);
randoArray[i][k] = randoNum;
System.out.print(randoArray[i][k]+" ");
Your bug is in this line:
randoArray[rws-1][clmn-1] = randoNum;
This stores your random number into randoArray[rws-1][clmn-1] each time, which as you noticed, is the bottom right corner. rws is always 4, and clmn is always 8. So you store the same number there 32 times, which gives the same result as storing it only once.
In the following line you are correctly printing the number from the current array location:
System.out.print(randoArray[i][k]+" ");
An int array comes initialized with all zeroes, and since except for the last corner you have not filled anything into your array, 0 is printed.
Also if you want different random numbers in all the cells, you would need to call rando.nextInt() inside your innermost for loop.
Unless you need this 2-D array for some purpose (which doesn't show from the minimal example code that you have posted), you do not need it for printing a matrix of random numbers, i.e., you may just print the numbers form within your loop without putting them into the array first.
Finally if rhigh should be the highest possible random number in the array, you should use rando.nextInt(rhigh - rlow + 1). With rlow equal to 2 and rhigh equal to 9 this will give numbers in the range from 0 inclusive to 9 - 2 + 1 = 8 exclusive, which means that after adding to rlow = 2 you will get a number in the range from 2 to 10 exclusive, in other words, to 9 inclusive.
I am on purpose leaving to yourself to fix your code based on my comments. I believe your learning will benefit more from working it out yourself.
Your assign the array value outside the array length
int[][] randoArray = new int[rws][clmn];
randoArray[rws][clmn] = randoNum;
Here randoArray[rws] is out of bounds.

ArrayList contains

I don't really understand what's happening, if someone could explain this to me that would be great.
So, here's my code:
public static ArrayList<Integer> numbers = new ArrayList<Integer>();
public static void main(String[] args){
for(int i =0; i != 90; i++){
System.out.println(generate());
}
}
public static int generate(){
Random random = new Random();
int rand = random.nextInt(89)+1;
while(numbers.contains(rand)){ //<---Here seems to be my problem
rand = random.nextInt(89)+1;
System.out.println("Number: " + rand + " already exists!");
}
numbers.add(rand);
return rand;
}
I am writing a program that generates a random number from 0-90, each of which are different to the last. Unfortunately, it seems that the while loop only returns true.
You're picking from 89 random numbers (1-89 inclusive) and trying to find a unique number each time... but you're calling that 90 times. What do you expect the last iteration to do? (To put it another way - you're trying to squeeze 90 numbers into 89 slots. That's not going to work.) On the last iteration, all the possible values will already be in the list, so the condition of your while loop will always be met, whatever value is randomly chosen on each iteration.
If you wanted the numbers to be between 1 and 90 inclusive, you should be using random.nextInt(90) + 1. The argument to nextInt is the maximum number exclusive to generate - so if you call random.nextInt(3) for example, it will generate 0, 1 or 2.
(There are better ways of doing this, by the way - such as populating the list and then using Collections.shuffle - but I've concentrated on explaining the behaviour of your current code.)
You can do it easily by using collections shuffle
public static ArrayList<Integer> numbers = new ArrayList<Integer>();
for(int i =1; i <= 90; i++){
number.add(i)
}
Collections.shuffle(numbers); // at this point the number are shuffled.
Read about shuffle.

How can we use array elements as a counters in java?

import java.util.Random;
public class DemoArrayElement {
public static void main(String arg[]) {
Random rand = new Random();
int[] freq = new int[7];
for (int roll = 1; roll < 10; roll++) {
++freq[1 + rand.nextInt(6)];
}
System.out.println("FACE\tFREQUENCY");
for (int face = 1; face < freq.length; face++) {
System.out.println(face + "\t\t" + freq[face]);
}
}
}
Can someone please explain me this ++freq[1+rand.nextInt(6)]; line of code.
This program simulates rolling a die 10 times. The array freq is used to count the frequencies each face value is rolled - the index represents the face value and the content the number of times it was rolled. So, e.g., freq[3] contains the number of times 3 was rolled.
Let's take a look at ++freq[1+rand.nextInt(6)]; and take it apart:
rand.nextInt(6) calls Java's random number generator (a java.util.Random instance) and asks it for a uniformly distributed random number between 0 and 5 (inclusive). Adding 1 to it gives you a random face value form a die - a number between 1 and 6.
Accessing this index in the freq array (freq[1+rand.nextInt(6)]), as noted above, will return the number of times this face value was randomly encountered. Since we just encountered it again, this number is incremented (the ++ operator).
frec is an array containing 7 numeric elements.
++freq[1+rand.nextInt(6)]; means pre-increment a random element from an array.
Example: if the second element from the array is 5:
++freq[1]; will make it 6.

Java Random number but not zero

int num = 10;
Random rand = new Random();
int ran = rand.nextInt(num);
if (ran==0){
ran= ran+1;
}
System.out.println("random : "+ran);
This is what i have coded so far, is there a better way to do this? I feel that this is hard coding when random is 0, I added 1.
The problem with that code is that 1 is twice as likely as other numbers (as your effective result is 1 when nextInt() returns 0 or 1).
The best solution is to just always add 1 and request random numbers from a smaller range:
int rnd = rand.nextInt(num - 1) + 1;
I guess you are trying to get a random number between 1 and 'num'.
a more generic way can be :
int Low = 1;
int High = 10;
int R = r.nextInt(High-Low) + Low;
This gives you a random number in between 1 (inclusive) and 10 (exclusive). ( or use High=11 for 10 inclusive)
Random random = new Random();
int ran = random.nextInt(9) + 1; //10 is maxRandom value for this code. 1-10
you also could do the following:
int randomNumber = 0;
do {
randomNumber = rand.nextInt(maxValue);
} while(randomNumber == 0);
Try this:
int num,max=10,min=1;
Random r=new Random();
num=r.nextInt(max-min)+1;
You'll need this import at the beginning of your file:
import java.util.Random;
Just lower the bound (num variable) by 1 and add 1 to the ran variable
int num = 10;
Random rand = new Random();
int ran = rand.nextInt(num - 1) + 1;
// or decrease num first n-- and then int ran = rand.nextInt(num) + 1
now the bound(limit) is 8 (inclusive for example, the final number is always exclusive) and if it comes 0, it will increase to 1 and if it comes 8, it will increase to 9, which was originally supposed to be the bound.
Don't expect this functionality from Random and do it yourself as you should. One can do pretty much anything with the result - multiply, add (e.g. 2*nextInt(n)+1 for random odd number), use logarithmic scale for musical note frequencies, use a map or enum to obtain random objects ...
Method nextInt(n) is here only to give you n different values (from 0 to n-1). Don't ask more of it, implement the rest by yourself. If I understand your question well, you require numbers 1..9, so you should ask for nextInt(9)+1 to get 0..8 and then add 1.
I hope this explanation helps, I saw many answers, but I didn't like the explanation in any of them.
Try:
int num = 10;
Random rand = new Random();
int ran = rand.nextInt(num) + 1;

How to get a 50/50 chance in random generator

I am trying to get a 50/50 chance of get either 1 or 2 in a random generator.
For example:
Random random = new Random();
int num = random.nextInt(2)+1;
This code will output either a 1 or 2.
Let's say I run it in a loop:
for ( int i = 0; i < 100; i++ ) {
int num = random.nextInt(2)+1 ;
}
How can I make the generator make an equal number for 1 and 2 in this case?
So I want this loop to generate 50 times of number 1 and 50 times of number 2.
One way: fill an ArrayList<Integer> with fifty 1's and fifty 2's and then call Collection.shuffle(...) on it.
50/50 is quite easy with Random.nextBoolean()
private final Random random = new Random();
private int next() {
if (random.nextBoolean()) {
return 1;
} else {
return 2;
}
}
Test Run:
final ListMultimap<Integer, Integer> histogram = LinkedListMultimap.create(2);
for (int i = 0; i < 10000; i++) {
nal Integer result = Integer.valueOf(next());
histogram.put(result, result);
}
for (final Integer key : histogram.keySet()) {
System.out.println(key + ": " + histogram.get(key).size());
}
Result:
1: 5056
2: 4944
You can't achieve this with random. If you need exactly 50 1s and 50 2s, you should try something like this:
int[] array = new int[100];
for (int i = 0; i < 50; ++i)
array[i] = 1;
for (int i = 50; i < 100; ++i)
array[i] = 2;
shuffle(array); // implement shuffling algorithm or use an already existing one
EDIT:
I understand that if you are looking to accomplish exactly 50-50 results, then my answer was not accurate. You should use a pre-filled collection, since it is impossible to achive that using any kind of randomness. This considered, my answer is still valid for the title of the question, so, this is it:
Well, you do not need the rnd generator to do this.
Comming from javascript, I would go with a single liner:
return Math.random() > 0.5 ? 1: 2;
Explanation: Math.random() returns a number between 0(inclusive) and 1(exclusive), so, we just examine weather is larger than 0.5 (middle value). In theory there is a 50% change that does.
For a more generic use, you can just replace 1:2 to true:false
You can adjust the probability along the way so that the probability of getting a one decreases as you get more ones. This way you don't always have a 50% chance of getting a one, but you can get the result you expected (exactly 50 ones):
int onesLeft = 50;
for(int i=0;i<100;i++) {
int totalLeft = 100 - i;
// we need a probability of onesLeft out of (totalLeft)
int r = random.nextInt(totalLeft);
int num;
if(r < onesLeft) {
num = 1;
onesLeft --;
} else {
num = 2;
}
}
This has an advantage over shuffling because it generates numbers incrementally so it desn't need memory to store the numbers.
You have already successfully created a random generator that returns 1 or 2 with equal probability.
As (many) other's have mentioned, your next request, to force an exact 50/50 distributions in 100 trials, does not fall in line with random number generation. As shown in https://math.stackexchange.com/questions/12348/probability-of-getting-50-heads-from-tossing-a-coin-100-times, the realistic expectation of that occurring is only around 8%. So even while you might expect 50 of each, that exact outcome is actually rather rare.
The Law of Large Numbers states that you should close in on expected value as your number of trials increases.
So for your actual question: How can I make the generator make an equal number for 1 and 2 in this case?
The best (humorous) answer I can come up with is: "Run it in an infinite loop."

Categories

Resources