I'm trying to generate 1000 random numbers between 13 and 100. So far it's only generating 75% of what I want repeatedly a thousand times. Here's what I have so far:
Random rand = new Random();
for (int j = 0; j < 1000; j++)
{
int pick = rand.nextInt((87) + 13);
pick++;
}
Why isn't it working?
Pay attention to nextInt() covering the 0 inclusively and the specified value exclusively! So it has to be rand.nextInt(88) to make the highest int generated be 87. Here is what you want:
Random rand = new Random();
for (int j = 0; j<1000; j++)
{
int pick = rand.nextInt(88)+13;
}
rand.nextInt(88) + 13; should give you numbers between 13 and 100, and you just put it in your loop.
The line :
So far its only generating 75% of what i want repeatedly a thousand times
Really doesn't add up to me. It might be a seeding issue you're having though. Make sure to always re-seed the random number, using time.
But I agree with Abdul , you need to take the +13 out of that parenthesis:
rand.nextInt(87) + 13;
Because rand.nextInt((87) + 13) is the same as rand.nextInt((67) + 23) as rand.nextInt((1) + 99)
But if you want more "true" randomness, look into something called buzzhash (though that is for hashing ; yet may be modded for number)
I use this in my codes:
public static int randomInteger(int min, int max)
{
java.security.SecureRandom rand = new java.security.SecureRandom();
//get bounded [0, max) from nextInt()
int randomNum = rand.nextInt(max) + min;
return randomNum;
}
value = randomInteger(13,100); //13..99
value = randomInteger(13,101); //13..100
Related
This is what I tried so far in my app.
I got this code by searching it from Google.
Inside the Button OnClick() I called the Arandom() method:
public void Arandom(View view) {
final int SET_SIZE_REQUIRED = 4;
final int NUMBER_RANGE = 70;
Random random = new Random();
Set set = new HashSet<Integer>(SET_SIZE_REQUIRED);
while(set.size()< SET_SIZE_REQUIRED) {
while (set.add(random.nextInt(NUMBER_RANGE)) != true) ;
}
assert set.size() == SET_SIZE_REQUIRED;
ArrayList<Integer> Elements = new ArrayList<>(set);
Log.i("Elements","A:" + Elements.get(0));
Log.i("Elements","B:" + Elements.get(1));
Log.i("Elements","C:" + Elements.get(2));
Log.i("Elements","D:" + Elements.get(3));
}
Now I am able to get four unique random numbers by this code but the problem is there sum is greater then 60. Let me explain it little bit.
When I run the code I get:
A:61
B:45
C:31
D:49
This is the screen shot of my log cat
So I want the sum of all the numbers should be in the specified range (which is 1 to 60).
e.g: A = 20 , B = 25 , C = 3 and D = 11 then their sum is 59 which is within the range
Now another e.g: Suppose A = 5 , B = 22 , C = 18 and D = 3 then their sum will be 48
When we Add A,B,C,D then their sum should not exceed the range that is 60
I am new to Android and Java, and I am learning on my own by searching some materials on Google.
Let's say your target sum is T. It's easiest if you try to pick the numbers in descending order (you can shuffle them afterwards, if you want).
The largest number you can pick for the 1st of four numbers is T-6, because you need to pick 3, 2 and 1 for the smaller numbers.
The smallest number you can pick is the one where n+(n-1)+2+1 = T, so T/2+1.
So, pick the first number in the range (T/2+1) to T-6.
Then repeat the process to pick the third-largest and second-largest, applying similar logic to determine the possible range. There should be no choice in the smallest number, it's just whatever else you need to add to make the final sum.
Note that you need to take care with rounding of things like the T/2.
I made the return type an int[]. You know how big you want to make the set, so there is no need to use sets or lists. The input parameter is changed to SET_SIZE_REQUIRED instead of using view. Make sure that a funtion only has one purpose and not do a calculation and change on a view at the same time.
Replace the 60f to something else if you want the sum to be more or less than 60.
public int[] Arandom(int numberOfValues) {
int[] values = new int[numberOfValues];
int sum = 0;
for(int i = 0; i < numberOfValues; i++){
values[i] = (int)(Math.random() * 100);
sum += values[i];
}
float multiplier = 60f / sum;
for(int i = 0; i < numberOfValues; i++){
values[i] = (int)(values[i] * multiplier);
Log.i("Value " + (i + 1), values[i]);
}
return values;
}
Or just do this:
public int[] Arandom(int numberOfValues) {
int[] values = new int[numberOfValues];
for(int i = 0; i < numberOfValues; i++){
values[i] = (int)(Math.random() * (60f / numberOfValues));
Log.i("Value " + (i + 1), values[i]);
}
return values;
}
int[] integers = new int[12];
Random r = new Random();
for (int i = 0; i < integers.length; i++) {
integers[i] = r.nextInt((10 - (-10) + 1) + (-10));
}
I'm executing it using online compiler and it throws an error at random.
can anyone help me to solve that problem? I don't know how to write that half of it be negative and half positive. And that random number can't be 0
First of all, to generate a number between -10 and 10, the correct code is :
integers[i] = r.nextInt(21)-10;
r.nextInt(21) will generate numbers between 0 and 20, so subtracting 10 will give you the desired range.
Now, you must validate the random numbers you generated, to make sure you don't generate too many positives or negative, and no zeroes.
int posCount=0;
int negCount=0;
for (int i = 0; i < integers.length; i++) {
integers[i] = r.nextInt(21)-10;
if (integers[i]>0)
posCount++;
else if (integers[i]<0)
negCount--;
if (posCount>6||negCount>6||integers[i]==0)
i--; // redo the current iteration of the loop, since the last generated
// number should be replaced
}
Another alternative, which will run faster, is to generate first 6 positive integers (r.nextInt(10)+1) and then 6 negative integers (-1-r.nextInt(10)), but I'm not sure whether the order of the generated numbers is important (i.e. is it acceptable that all the positives will come before all of the negatives).
1+ r.nextInt(10) gives integers 1-10. For negative integers, just put minus sign to the result of this calculation. Call it six times for positives and six times for negatives. What kind of error you get?
check this :
Random r = new Random();
int[] integers = new int[10];
boolean isEven=false;
int i = 0;
while(true){
int check = r.nextInt(10)*(isEven?-1:1);
if (check != 0){
isEven = !isEven;
integers[i] = check;
System.out.println(integers[i]);
i++;
}
if(i == 10){
break;
}
}
Keeping it simple:
Fill the current index with a random number from (1 to 10);
Fill the next index with a random number from (-1 to -10);
int[] integers = new int[12];
Random r = new Random();
for (int i = 0; i < integers.length; i+=2) {
integers[i] = r.nextInt(10) + 1;
if((i+1)<integers.length){
integers[i+1] = r.nextInt(10) -10;
}
}
I know for generating random number there is random function in java
for example
int randomNumber = ( int )( Math.random() * 9999 );
which will generate randomNumber from [0,9999] but it only returns one number by given range.
But I just want to know if there is any built in function or you can say native function which will generate more than one random numbers and it should also not match with each other
suppose from above example if i want to generate 4 number
it will return like 1,10,50,5544
Here you can see that there is a four random number and it is not matching with each other .
try something like this
Create an ArrayList and add your random number and while adding check if ArrayList already contains the number or not.
Eg:
ArrayList<Integer> numbers = new ArrayList<Integer>();
while (numbers.size()<=YOUR_MAX_SIZE)
{
int randomInteger = ( int )( Math.random() * 9999 );
if (!numbers.contains(randomInteger)) {
{
numbers.add(randomInteger);
}
}
Another technique (besides the one shown by #MichaelShrestha) is to put the entire range of numbers in a collection, then shuffle it and take the numbers in the shuffled order.
It has the advantage that whereas the other method might spin though many (many) numbers to find a non-duplicate random value, this will only have to be run once. OTOH, for small collections of numbers, #Michael's technique might be faster.
Try this, as proposed here:
int min = 1;
int max = 10000;
Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;
EDIT:
With no duplicates:
Random rng = new Random(); // Ideally just create one instance globally
int min = 1;
int max = 10000;
Set<Integer> generated = new LinkedHashSet<Integer>();
while (generated.size() < numbersNeeded)
{
Integer next = r.nextInt(max - min + 1) + min;
generated.add(next);
}
LINK
There is not built in api. but you can use something like this
public static int[] getRandoms(int amount, int range){
int[] result = new int[amount];
ArrayList tempList = new ArrayList();
for(int i = 0; i< range; i++)
tempList.add(i);
Collections.shuffle(tempList);
for(int i = 0; i< amount; i++)
result[i] = (int)tempList.get(i);
return result;
}
Here amount is the number of randome numbers you want and the range is the maximum range of random number
ArrayList<Integer> rnumbers = new ArrayList<Integer>();
for (int i = 0; i < 4; i++) {
int randomNumber = (int) (Math.random() * 9999);
while (rnumbers.contains(randomNumber)) {
randomNumber = (int) (Math.random() * 9999);
}
rnumbers.add(randomNumber);
}
As HashSet contains unique object... You can have the unique random numbers.
Set uniqueRandomNumber = new HashSet();
int i = 5 //number Of Random Number Required;
for(int = 0; i<5; 1++){
int randomNumber = ( int )( Math.random() * 9999 );
uniqueRandomNumber.add(randomNumber);
}
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;
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."