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
Related
Can someone explain this code line by line. I just started to learn how to code and I'm learning java right now,but I'm having hard time how this function executes. What does new int[10]; really do? and I don't really get the difference or how repeatedDigits[index] part is used differently from the repeatedDigits[remainder] part.
Write a function that counts the repeated digits in the integer x.
For * example: if x is 999, then your function must print back that 9 occurs 3 * times. Another example, if the integer x is 992121, then your function * must print back that 9 occurs 2 times, 2 occurs 2 times and 1 occurs 2 * times. This was a guideline for the function.
public static void countRepeatedDigitsInANumber(int x) {
int[] repeatedDigits = new int[10];
while (x > 0) {
int remainder = x % 10;
x = x / 10;
repeatedDigits[remainder] = repeatedDigits[remainder] + 1;
}
int index = 0;
while (index < 10) {
if (repeatedDigits[index] != 0)
System.out.println("The digit " + index + " occurs " +
repeatedDigits[index]);
index++;
}
}
This is a code that compiles. I'm just posting this because I'm having hard time to understand. I would realy appreciate if someone could give any suggestion to learn java quickly as well!
What does new int[10];
It creates a new array of size 10 that can hold int values. All of the values in the array will be initialized to 0 (this is just how Java handles int primitives).
In this case, it looks like this array is being used to store the number of times that the digit corresponding to its index has been seen.
Hmm, that was confusing to type, and probably even more confusing to read, so let me use an example. For the input 992121, you'd expect the repeatedDigits array to look like this when the program is done:
[0, 2, 1, 0, 0, 0, 0, 0, 0, 2]
i.e. Two 1s, one 2, and two 9s
while (x > 0) {
This starts a loop that will keep going until x is equal to (or smaller than, but that shouldn't happen) zero.
int remainder = x % 10;
This essentially "captures" the right-most digit of the number using modular arithmetic. It divides the number by 10, and any remainder is going to be what's in the "ones place" (i.e. the right-most digit).
x = x / 10;
This shifts digits to the right by one, and throws away the right-most digit (since you've already captured it).
repeatedDigits[remainder] = repeatedDigits[remainder] + 1
This just increments the value in the array at the appropriate location. For example, if you just pushed a 9 off the right end of the number, this will increment the value in repeatedDigits[9] so you know that you just saw an additional 9.
int index = 0;
while (index < 10) {
We're about to do some looping! There are (in my opinion) better ways to do this, but this works just as well. Basically, you want index to start at 0, and loop all the way up to 9, but stop when you get to 10.
if (repeatedDigits[index] != 0)
If the value at a given location in the repeatedDigits array is not zero, then...
System.out.println("The digit " + index + " occurs " + repeatedDigits[index]);
... print it out!
index++;
And finally, increment index so we can check the next number. This is exactly the same as index = index + 1.
Welcome to SO and the beautiful world of Java! I've attached hyperlinks all throughout my answer that could possibly help you out.
int[] repeatedDigits = new int[10];
The above line of code is creating an array with 10 elements, from index: 0 to index: 9.
int remainder = x % 10;
The above line of code is calculating the remainder once 'x' has been divided by 10. For example, if 'x = 9192' then it would be dividing '9192 / 10 = 919.2' And taking the remainder. Which in this case is the '2'. Notice how it's actually looking at the number in reverse? So a number like '9192' is actually being processed as '2919'.
x = x / 10;
The above line of code is dividing the number down by 10- since it's integer division it drops all decimal values. Since we have already calculated the last number. So our '9192' is now just '919'.
repeatedDigits[remainder] = repeatedDigits[remainder] + 1;
The above line of code is going to the index of the array of the remainder value that we stored earlier. Remember how our remainder was '2'? It's not going to index: 2 in our array and adding 1 to it's value- which was originally 0. So now our array at index: 2 has the value: 1. Meaning the number 2 was repeated 1 time.
What I've laid out above is just 1 iteration of the while loop that the top half of your code is in. So get a piece of paper and redo everything I did above with the remaining number '919'.
Once you're finished you should notice that your array looks something like this:
index 0: 0
index 1: 1
index 2: 1
index 3: 0
index 4 to 8: 0
index 9: 2
This means that '1' came once. '2' came once. and '9' came twice.
As for advice on learning Java? Read a lot. Google every little question you have, and if you don't understand how something is working get a piece of paper and write it out.
int[] repeatedDigits = new int[10];
//create an array of integers of size 10
while (x > 0) {
//while the integer provided is greater than 0
int remainder = x % 10;
//gets the smallest value digit in a base ten system. 101%10 =1
x = x / 10;
//in base ten this reduces the size of the number by a tens place. 101/10 =10 as 10 can be fully divided into 101 10 times. You've dropped the last digit of the number in this way. This is what will allow you to exit the while loop, as eventually x will be equal to 0.
repeatedDigits[remainder] = repeatedDigits[remainder] + 1;
remainder here can be between 0-9. This is because remainder is the remainder of dividing the provided integer by 10. You can't divide a number greater than 0 by ten and have a value less than zero or greater than 9.
The array you created has indexes 0-9, as it is ten spaces long (0,1,2,3,4,5,6,7,8,9). You are assigning the value of the index of repeated Digits that corresponds to your remainder to whatever it was previously plus 1.
What this means is you have found that the last digit in the number is equal to some value X. X must be between 0-9. As you have an array with indexes between 0-9 you get the value associated with repeatedDigits[X], add one to it as you have found another value of X, and set repeatedDigits[X]'s value equal to what is was before you found this new X plus one.
}
int index = 0;
You start at the first value of an array (0)
while (index < 10) {
Go through the values of the array from 0 to 9
if (repeatedDigits[index] != 0)
if the value of the array repeatedDigits at index is not 0. This is the same as saying if there was a value of index found in the input number.
System.out.println("The digit " + index + " occurs " +
repeatedDigits[index]);
index is the number we looked at. The count of how many times it occurred is stored at repeatedDigits[index]. We are printing the value and how many times it occurred.
index++;
Increase the index, examining the next index value.
}
}
Let me see if I can clear a few things up for you. My first suggestion is to format your code so that the lines within loops are indented:
public static void countRepeatedDigitsInANumber(int x) {
int[] repeatedDigits = new int[10];
while (x > 0) {
int remainder = x % 10;
x = x / 10;
repeatedDigits[remainder] = repeatedDigits[remainder] + 1;
}
int index = 0;
while (index < 10) {
if (repeatedDigits[index] != 0)
System.out.println("The digit " + index + " occurs " + repeatedDigits[index]);
index++;
}
}
}
This helps us to see the structure of the program. We can now see that the program runs as follows:
Define a new int array: int[] repeatedDigits = new int[10];
Run a while loop: while (x > 0) { ... }
Define an int variable: int index = 0;
Run a second while containing an if statement: while (index < 10) { if ( ... ) { ... } }
I'll try to explain each of the four pieces one at a time.
First we define our int array. new int[10] defines an array with ten spots in it, each of which can hold an integer. You can think of this like ten boxes next to each other, each labeled with an index. This array will be used to keep track of how many times we've seen each integer. repeatedDigits[0] will hold the number of times we've seen a 0 digit in our number; repeatedDigits[6] will hold the number of times we've seen a 6 digit, and so on.
Here's the heart of the program. We're going to break down the number, one digit at a time, and for each digit, we add one to the spot in the array used to keep track of how many times we've seen that digit. This line gets us the rightmost digit in our number: int remainder = x % 10;. % is called the modulo operator, and you can search for that to learn more about it. With the input 992121, this will assign remainder to 1.
The next line uses integer division to remove that last digit from the number, so that the next time through the loop we get the next digit. if x = 992121 then after x = x / 10, x will equal 99212.
Finally, we add one to the spot in the repeatedDigits array corresponding to the digit we saw. So in our example, remainder = 1, so we add 1 to the repeatedDigits[1] spot. This line takes advantage of the fact that an uninitialized int defaults to 0.
We've reached the end of the while loop, so we check the condition, and find that x > 0, so we run the loop again. We repeat this for every digit in the input number`.
The hard work is now done; the rest of the program is there to print out the results.
We assign index to 0. The next while loop will increment this variable from 0 to 9, printing the value of the repeatedDigits array for each digit.
We run the loop from index = 0 to index = 9. For each value, we check to see if we saw that digit in our input number (that's the if statement). We check the value in repeatedDigits[index] to see if it doesn't equal 0. If so, then we must have incremented it in the previous loop, so we know that digit appeared at least once in the original input. In that case, we print a line to the console using System.out.println. Then we increment index and start the loop again.
Please let me know if you have any questions, and good luck!
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;
}
I have an generation method that generates numbers between 1 and 8. But the problem is that this method often generates the numbers 1-7 and almost never number 8. My question is that how to generate random numbers in certain interval but that all numbers appear approximately same times ?
EDIT:
my number generator
public int generateNumber() {
Random r = new Random();
return r.nextInt(8 - 1) + 1;
}
The random generator generates an "uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)" Please refer to the documentation:
http://docs.oracle.com/javase/7/docs/api/java/util/Random.html
You can do:
random.nextInt(max - min + 1) + min
And it should be fine.
Alternatively,
Random randomGenerator = new Random();
for (int idx = 1; idx <= NUMBER_OF_INTEGERS_YOU_WANT; idx++){
int randomInt = randomGenerator.nextInt(8)+1;
CODE_HERE
}
"almost never number 8": If that generator ever generates 8 there is something wrong.
The nextInt gives a number between 0 and 6 (borders inclusive) and adding one gives the interval [1,7].
To get numbers in [1,8] you can use
r.nextInt(8) + 1
You need something like
return r.nextInt(8) + 1;
Which will return values from 1 to 8. So it starts with 0 and generated number max uptil n-1 i.e. 7 as per this.
In your case, you have r.nextInt(8 - 1) which evaluates to r.nextInt(7) so it would generate numbers from 0 -6 and on top of that you are adding 1 to number from above api, so your range is 1-7 and not 1-8.
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.
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.