I'm trying to generate a random number within a range, and of a specific multiple. My example would be within the range of 60 - 500, and only multiples of 5, e.g. 60, 65, 70 -> 500
I'm trying to use random.nextInt(), but I can either get the range to work, or the multiplier, but not both.
Any assistance would be greatly appreciated!
I'd work my way backwards - generate a random number and then multiply it by the multiple you want:
int multiple = 5;
int rangeStart = 60;
int rangeEnd = 500;
int calcRangeStart = rangeStart / multiple;
int calcRangeEnd = rangeEnd / multiple;
int random = new Random().nextInt(calcRangeStart, calcRangeEnd) * multiple;
First work out the number of possible values for your random number, which is
((500-60)/5 + 1) or
((505-60)/5)
using integer division. Using this value as an argument to Random.nextInt will give you values starting from 0. So you just need to multiply by 5 and add 60 to get values in your desired range
Random random = new Random();
(random.nextInt((505-60)/5) * 5 + 60)
You can define your from-to and multiply numbers as ints and then generate them like this:
int from = 60, to = 500, multi = 5;
Random rand = new Random();
int n = multi*(Math.round(rand.nextInt((to+multi-from))+from)/multi);
This code will generate numbers from 60 to 500 in multiplies of 5 only.
int seed = 5;
Random random = new Random();
int inf = 12;
int sup = 100;
int number = random.nextInt((sup-inf)+1) + inf;
number *= seed;
Related
Im currently trying to get a random integer between 100 and 2000 in steps of 100 like 300, 800, 1400 etc.
Thats what I found to get a random number between a range, but how do I manage to get a random number in steps of 100?
Random random = new Random();
int start = 100;
int end = 2000;
int result = random.nextInt(start - end) + start;
The problem is whether you want 2000 included or not. And whether the step size reaches 2000 exactly. The calculation just needs to include the step size:
Random random = new Random();
final int start = 100;
final int end = 2000;
final int step = 100;
int result = start + step * random.nextInt((end - start)/step); // end excl.
int result = start + step * random.nextInt((end - start)/step + 1); // end incl.
As already commented, it is probably more clear to base all on a random number between 1 and 20, and scale that up.
int result = (1 + random.nextInt(20)) * 100; // 100 upto 2000 by 100.
a friend of mine at Uni, was wanting to generate a bunch of 13 digit numbers so he can test his sorting algorithms on, but was doing it a very long way around, so i've tried to use the following code to generate a settable number of 13 digit numbers.
public class random {
public static void main(String[] args) {
long intArray[] = new long[20]; // to generate more than 20 random numbers increase this and the 'i < 20' to the same number ie. 75
for(int i = 0; i < 20; i++) { // here
intArray[i] = numbGen();
}
for(int j = 0; j < intArray.length; j++) {
System.out.println(intArray[j]);
}
}
public static long numbGen() {
long numb = (long)(Math.random() * 10000000 * 1000000); // had to use this as int's are to small for a 13 digit number.
return numb;
}
}
my issue is now sometimes it will generate a couple of 12 digit numbers in the group of 20 and i want to find a way not to add the number to the array if it is not 13 digits. I've tried if statement but getting stuck on not being able to determine the length (individual characters) of the Long.
Thanks in Advance.
A simple solution:
while(test < 10000) {
long num = (long) (Math.random() * 100000000 * 1000000);
if(Long.toString(num).length() == 13) {
return num;
}
test++;
}
However, a better solution is this:
long number = (long) Math.floor(Math.random() * 9000000000000L) + 1000000000000L;
This will only generate random 13 digit numbers, and you don't need to check if there are more or less digits.
Note that this solution may not scale to a higher number of digits and may not return a perfect distribution of random numbers.
long min = 1000000000000L; //13 digits inclusive
long max = 10000000000000L; //14 digits exclusive
Random random = new Random()
long number = min+((long)(random.nextDouble()*(max-min)));
A generic integer based implementation would be:
public static long randomDigits(int digits) {
if (digits <= 0 || digits > 18) {
throw new IllegalArgumentException("A long can store the random of 18 full digits, you required: " + digits);
}
// use SecureRandom instead for truly random values
final Random r = new Random();
long randomNumber = r.nextInt(9) + 1;
for (int i = 1; i < digits; i++) {
randomNumber = randomNumber * 10L + (long) r.nextInt(10);
}
return randomNumber;
}
or use a shorter version for 13 digits that does not tax the RNG as much:
public static long thirteenRandomDigits() {
final Random r = new Random();
return 1_000_000_000L * (r.nextInt(9_000) + 1_000)
+ r.nextInt(1_000_000_000);
}
These solutions are better to using Math.random() because they don't rely on multiplication with a large number to generate the random values. A double only has 15-17 digits precision, which is very close to the 13 digits number it is multiplied with. This leads to unequal distributions of random numbers. Solutions based on Math.random() won't scale past 13 digits either.
The simple solution for the problem that you described:
public static long numbGen() {
while (true) {
long numb = (long)(Math.random() * 100000000 * 1000000); // had to use this as int's are to small for a 13 digit number.
if (String.valueOf(numb).length() == 13)
return numb;
}
}
This is not the most efficient or most random implementation of generating a 13-digit number but it answers your specific question.
ThreadLocalRandom is a good thing, introduced in Java 1.7
java.util.concurrent.ThreadLocalRandom
.current()
.nextLong(1000000000000L, 10000000000000L);
long randomNumber = 0;
long power = 1;
for(int i = 0; i < 12; i++) { // up to 12 not 13
Random r = new Random();
int randomInt = r.nextInt(10);
randomNumber += (power * randomInt);
power *= 10;
}
// here, the most stupid way to provide last digit to be not zero
Random r = new Random();
int randomInt = r.nextInt(9);
randomInt++;
randomNumber += (power * randomInt);
power *= 10;
First off, a Long doesn't have characters.
If you want to see if it has 13 digits, compare it to 999999999999L.
If you want to insure you have a value w/ 13 digits, get a random number between 0 and 8999999999999L (inclusive) (using the technique you already have to generate a random number in a range) and add it to 1000000000000L.
Why not we try with Unix timestamp in milliseconds.Because that will work for next 200 years and after that we need to only eliminate the trailing digit from the number.
Calendar.getInstance().get(Calendar.MILLISECOND);
and by using this method we don't need any loop or any condition and it will give me a unique number every time.
I am trying to re-generate random numbers in android. I want to generate two numbers which are divisible by each other. If the generated numbers are not divisible, I want the system to try again until it generates numbers which are divisible by each other.
Here is my code:
Random random = new Random();
arrone = random.nextInt(100 - 20) + 20;
Random randm = new Random();
arrtwo = randm.nextInt(11 - 2) + 2;
if (arrone % arrtwo ==0){
// if they are divisible do this.
} else {
// if they are not divisible, I want it to try again and find two divisble numbers
}
To rephrase the problem, you want two numbers where one is a multiple of the other. The significant difference is you don't need to use a loop to find such a pair of values.
int min = 20;
int max = 100;
int second = rand.nextInt(11 - 2) + 2;
int multiplier = Math.max((min + second-1)/second,
rand.nextInt(max / second) + 1);
int first = multiplier * second;
In this case, you know the first must be divisible by the second.
boolean divisible = false;
while (!divisible ) {
Random random = new Random();
arrone = random.nextInt(100 - 20) + 20;
Random randm = new Random();
arrtwo = randm.nextInt(11 - 2) + 2;
if (arrone % arrtwo == 0){
// if they are divisible do this.
divisible = true;
}
}
}
public class TestSample {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
double ran = Math.random();
}
}
I don't want to use Random r = new Random(); class. Is there any other way to generate random numbers. I am just struck with what logic could be applied to generate random numbers between two numbers.
It's really easy... you only need to figure out which is the minimum value and what is the difference between the two numbers (let's call it diff). Then, you can scale the Math.random value (between 0 and 1) by multiplying by diff (now its range is between 0 and diff). Then, if you add the minimum value, your range is between min and min + diff (which is the other value)
int min = min(a,b);
int max = max(a,b);
int diff = max - min;
int result = min + diff * Math.random();
Consider using this code:
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
double ran = Math.random();
double random;
if(a < b)
random = (b-a)*ran + a;
else
random = (a-b)*ran + b;
This will work for a >= 0 and b >= 0 if you consider using negative number the logic sligtly changes
If you are expecting a double result, the simplest approach is
int a =
int b =
double result = (a-b)*Math.random() + b;
It doesn't matter which is greater as you get the same distribution.
However, if you want a random integer between 'a' and 'b' is a bit more complex.
int a =
int b =
int result = Math.floor((Math.abs(a-b)+1) * Math.random()) + Math.min(a, b);
The reason the result is different is that a random double between 0 and 1 will be just less than 1 i.e. [0.0, 1.0) However a random integer between 1 and 6 usually includes 1, 2, 3, 4, 5, 6 equally. As a decimal this is the round down of [0.0 ... 7.0)
You may get white noise from your microphone, and take any number from there. After that you may take any number from the given data, and do with it what you want. The example of getting data from the microphone can be found here.
I need to make a random number between 1 and 20, and based on that number (using "If - Then" statements), I need to set the image of an ImageView.
I know that in Objective-C, it goes like this:
int aNumber = arc4Random() % 20;
if (aNumber == 1) {
[theImageView setImage:theImage];
}
How can I do this in Java? I have seen it done this way, but I do not see how I can set the range of numbers (1-20, 2-7, ect).
int aNumber = (int) Math.random()
Docs are your friends
Random rand = new Random();
int n = rand.nextInt(20); // Gives n such that 0 <= n < 20
Documentation:
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.
Thus, from this example, we'll have a number between 0 and 19
Math.random() returns an double from [0,1[.
Random.nextInt(int) returns an int from [0, int[.
You can try:
int aNumber = (int) (20 * Math.random()) + 1;
or
Random rand = new Random();
int n = rand.nextInt(20) + 1;
You can use Math.random() to generate a double between 0 and 1 non-inclusive. Android Javadoc here.