How to draw a number from 0 to 4 in Java (Android)?
How to use the Random function?
The follwing will do what you need.
Random r = new Random();
int randomInt = r.nextInt(5);
If you do this in a loop, make sure you initialize the Random outside of the loop.
Random r = new Random();
for(int i = 0;i < someThing; i++) {
System.out.println(r.nextInt(5));
}
See the documentation for the Random class: http://download.oracle.com/javase/6/docs/api/java/util/Random.html
Please Pay Attantion - Calling each time the code:
Random r = new Random();
Will probably return you the same numbers (i guess few of you have noticed that phanamona).
I guess it connected somehow to the Java problem with random numbers:
Java: Can (new Random()).nextInt(5) always return the same number?
and: Java random always returns the same number when I set the seed?
Anyway my solution is to add a static variable to my class:
static Random sRandomGen = new Random();
and call the nextInt from the relevant method when i need the random number. Thatway i recieve an equal dividing between results.
int rnd = sRandomGen.nextInt(numofmatches - 1);
This solution works great for me.
One thing to be careful of is that you shouldn't create a new Random object every time you want a new number. This line should be executed once when the application starts:
Random r = new Random();
Then this should be called each time you want a new random number:
int x = r.nextInt(5);
System.out.println(""+(int) (Math.random()*5.0));
If you only need to generate a single random number, I believe it's slightly cheaper to use the Math.random() than to make an object.
Note: to generate any random integer from 0 to n, (0 inclusive, n exclusive), just use:
(int) (Math.random()*n);
To generate any random integer from m to m+n, (m inclusive, m+n exclusive), just use:
m + (int) (Math.random()*n);
Related
I have a class called 'Face' that creates a static instance of java.util.Random:
public static Random random = new Random();
Then, in Main, I set the seed and get a random value:
Face.random.setSeed(1);
int rand = Face.random.nextInt(5);
The value of 'rand' is different every time I run the program, though. I need it to be the same every time. I thought setting a seed did this, but I must not understand correctly. What am I missing?
If you are always setting the seed for every call, then it appears that the sequence of random numbers will be reset.
Try
random.setSeed(1);
for (int i = 0; i < 5; i++) {
int rand = random.nextInt(5);
System.out.println(rand);
}
While I was trying to create a small GUI in Java, I've stumbled onto this small issue with arrays.
I've tried inserting Random Integers into an one dimensional array, only to find out that the Random Integers won't get assigned.
//Declaring an Integer Array
int[] wuerfel = new int[2];
//It will loop once while assigning a random number to the array
for(int i = 0; i <= 1; i++) {
Random rand = new Random(6);
int zahlen = rand.nextInt(6) + 1;
wuerfel[i] = zahlen;
}
System.out.println(Arrays.toString(wuerfel));
I expect the output from the array to be a number between 1 - 6.
However, I keep receiving [2,2] as a result every time I try to rerun.
The constructor call new Random(6) doesn't do what you think it does: 6 is the seed, rather than the range of possible outputs. Therefore it will produce the same output every time.
Possible solutions:
Use the no-argument constructor for Random() instead, which will give it a different seed each time.
Declare and initialise rand outside the loop, with or without an explicit seed.
Use Math.random().
So in your code you set up a seed for your Random and you create new Random object every loop iteration so it just returns same number every time. If you use seed the documentation of Random class says :
If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers.
In your case you can get rid of seed value from your constructor or move Random class object creation outside of the loop :
public static void main(String[] args) {
int[] arr = new int[2];
Random rand = new Random();
for(int i = 0; i <= 1; i++) {
int zahlen = rand.nextInt(6) + 1;
arr[i] = zahlen;
}
System.out.println(Arrays.toString(arr));
}
Here I moved creation of Random instance outside of the loop so only one object is created and I am not passing seed to the constructor. I could pass the seed but in this case it is not needed as I don't need to create more instances of Random and I dont need them to generate same results.
*
int[] wuerfel = new int[2];
//It will loop once while assigning a random number to the array
Random rand = new Random();
for(int i = 0; i <= 1; i++) {
int zahlen = rand.nextInt(6) + 1;
wuerfel[i] = zahlen;
}
System.out.println(Arrays.toString(wuerfel));
* try this one create Random object with passing parameter
I have 4 buttons in an array. I am able to generate a random number and set it to all those buttons, but that's not what I intend to do. What I really want to do it set a random number to each button. E.g: instead of having '17' inside all four buttons, I may have '18', '15', '10', and '11' in each button. Instead of manually assigning a random in to each button, how could I do this to all buttons?
Here's my code:
Random rbselection = new Random();
final int rbselector = rbselection.nextInt(4);
final Button[] selectrb = new Button[4];
selectrb[0] = rb1;
selectrb[1] = rb2;
selectrb[2] = rb3;
selectrb[3] = rb4;
Random randoms1 = new Random();
int setRandoms1 = randoms1.nextInt(10);
for(int allrbA=0; allrbA<4; allrbA++) {
selectrb[allrbA].setText(""+setRandoms1);
}
Also, does anyone know how to stop a single number from being outputted twice when doing this? For example if the random numbers set are between 10 and 20 and one of them is 12, anyone know how to make all other possible numbers anything between that range apart from 12?
If I were you..
public static void main(String[] args) {
Set<Integer> uniqueRandomNumbers = new LinkedHashSet<>();
while (uniqueRandomNumbers.size() != 4) {
Random random = new Random();
uniqueRandomNumbers
.add(Math.abs(Integer.valueOf(random.nextInt())));
}
System.out.println(uniqueRandomNumbers);
}
Explanation :
I am generating random numbers. First I got random number 100, I added it to a 'Set' as set always maintains the uniqueness, if I get 100 again by any chance the size of the Set won't be increasing.
When size of the Set is 4 the loop breaks and the set contains unique random numbers.
Iterate through the Set to set the text.
To get random number in Java:
Random rand = new Random();
int n = rand.nextInt(50) + 1;
Where 1 is going to be your minimum in the range and 50 is going to be your max. Use this link for reference: Getting random numbers in Java
Depending on how many buttons you have. You could have
rbselection.nextInt(50) + 1;
to generate a new Int between 1 to 50 range every time u call it and add it to some list or Set.
So something like this:
Random rand = new Random();
int n = rand.nextInt(50) + 1;
ArrayList<Integer> ar = new ArrayList<Integer>();
int i = 0;
while (i < 4)
{
int temp = rbselection.nextInt(50) + 1;
if (ar.contains(temp))
continue;
ar.Add(temp);
i++;
}
Also, u can change the above code to something like:
while (i < 4)
{
int temp = rbselection.nextInt(50) + 1;
if (ar.contains(temp))
continue;
array[i].setText(temp);
ar.Add(temp);
i++;
}
Where array is the button array of size 4.
Try this:
Random rnd = new Random();
for(int allrbA=0; allrbA<4; allrbA++)
selectrb[allrbA].setText(String.valueOf(rnd.nextInt(20)));
I want to generate random numbers within the range 1 to 4, 4 including.
Here is my code:
int num = r.nextInt(4) + 1; //r is instance of Random.
However, I am running the above code in a loop and don't want repeating random number.
What happens now is often I am getting:
1,1,1,2,3,1,4,2,2,1,4,2,4,4,2,1,4,3,3,1,4,2,4,1 as my output.
Here, though the numbers are random within the range(1-4), but often repeated like the number "1"in the first 3 iterations.
What I am looking for is a way to get non repeating random number within the loop.
One simple way I know is of keeping the last random number before current iteration and compare, but I am sure there must be better solution to this.
Thanks in advance.
Use random.nextInt(range-1) and then map that number to the output number with a function that excludes the previous number:
public class Test {
private final Random random = new Random();
private final int range;
private int previous;
Test(int range) { this.range = range; }
int nextRnd() {
if (previous == 0) return previous = random.nextInt(range) + 1;
final int rnd = random.nextInt(range-1) + 1;
return previous = (rnd < previous? rnd : rnd + 1);
}
public static void main(String[] args) {
final Test t = new Test(4);
for (int i = 0; i < 100; i++) System.out.println(t.nextRnd());
}
}
There is no "better" answer.
You are getting a random number. Check this line:
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
this could be perfectly random.
So I propose you describe a better requirement.
Do you want always a next number that is different from the previous? Do you want a maximum of duplicates in a special rang? lets say within 6 consecutive numbers, every number is allowed to occur twice?
If you bring such a requirement we might be able to help you. otherwise we can just say: what you seeing is really random :)
As you have more numbers than you have to choice from you have to repeat some numbers. All you can do is minimise the number of immediate repeats.
One way to do this is to use Collections.shuffle which allow you to have numbers in a random order, without repeats and do this each time. You could prevent the last N value being repeated.
To stop consecutive repeating numbers you can reduce the range and use modulus.
int n = 0, max = 4;
Random rand = new Random();
for(int i = 0; i < numbers; i++) {
n = (n + rand.nextInt(max-1)) % max;
int numToUse = n + 1;
// use this number.
}
This work as there is really only max-1 possible values as you are excluding the last value used.
Here is an algorithm:
initialize an array A[4] with the numbers 1-4
set a counter Acnt, the effective size of A. Initialize to 4
for i in 1 to length(output sequence)
choose a random integer X from 0 to Acnt -1
save A[X] to your output sequence
swap(A[X],A[Acnt - 1])
Acnt--
if(Acnt == 0) Acnt = lengh(A)
Imagine A is a bag of balls with the numbers 1-4. Each iteration of your loop, you remove a ball. Rather than actually deleting from the array, which is expenisve, you simply hide the ball at the end of the array. When you decrement the number of balls in the bag (Acnt), the next ball you select comes from the non-hidden balls.
When you have no more balls to select, you unhide the balls by resetting the count of balls in your bag back to the full count.
This is basically the standard shuffle algorithm.
Edit: Rereading the question, I see now he allows repeats after only 1 number instead of the whole sequence, in which case it all you need to do to modify this is change if (Acnt == 0) to if(Acnt == length(A) - 1).
I have the following code to create a random series of a numbers from 0 to a given amount.
ArrayList<Integer> places = new ArrayList<Integer>();
for (int cnt = 0; cnt < NUMBER; cnt++) {
int place = (int)(random.nextDouble()*places.size());
places.add(place , new Integer(cnt));
}
I use this code in a method and then I run this method for about 1000 times for statistics purposes.
My problem is that created series is the same for all of the 1000 time.
Every time that I run the sequence is different, but same for all of the for values.
What should I do? Is there a method like srand() in C++?
Your algorithm seems flawed if you are trying to generate an array with numbers 0 ... NUMBER-1 in random order. Consider:
Random rnd = new Random(System.currentTimeMillis());
...
ArrayList<Integer> places = new ArrayList<Integer>(NUMBER);
for (int i = 0; i < NUMBER; ++i) {
places.add(i);
}
Collections.shuffle(places, rnd);
Use you use Math.random(). It will return a double from 0.0 to 1.0 exclusively. So you can replace the 2 lines inside the for loop with this:
places.add((int)(Math.random() * places.size()),cnt);
//you don't have to do "new Integer(cnt)" because of Java's auto-boxing feature