Generating Unique Random Numbers Within a Range

Generate 'n' unique random numbers within a range

If you just need sampling without replacement:

>>> import random
>>> random.sample(range(1, 100), 3)
[77, 52, 45]

random.sample takes a population and a sample size k and returns k random members of the population.

If you have to control for the case where k is larger than len(population), you need to be prepared to catch a ValueError:

>>> try:
... random.sample(range(1, 2), 3)
... except ValueError:
... print('Sample size exceeded population size.')
...
Sample size exceeded population size

How do you generate multiple unique random numbers within a range in mysql

Welcome to S/O. So, RAND() returns a random floating point number between 0 and 1, such as .28932353289090. So, if you want to get a given value such as from 0-10, just multiply the RAND() * 10. It will still be floating point, so if you wanted an integer of it, just wrap that with a cast, such as cast( rand() * 10 as signed ) to get an INTEGER value result. But casting this can give you a 10 due to implied rounding such as getting a .95 or greater will round UP to the next digit.

Next, you want the breakdowns going for the low, medium and high range of 2 - 32, 33-65, 66-98. So your gaps are not perfectly balanced, but I think what you are trying to do is break a possible 0-98 (99 possible values) into 3 groups. Why those specific, I dont know, but can give you a good start to see how you might get and adjust as you see fit.

Your low group is actually at most 32, but starting a MINIMUM of 2. So, start with your maximum RANGE which is 30. So, based on the casting I exampled above,

cast( 30 * rand() as signed) 

will give you a value of 0-30. Now, just add 2 to it since that is your low range, thus a final of

2 + cast( 30 * rand() as signed)

Now, apply similar logic to your medium and high.

33-65 = range = 33-33 = 0 (low), 65-33 = 32 (high) randomness + a fixed 33

33 + cast( 32 * rand() as signed) 

So, if the rand() return 0, then you are at 33 + 0 = 33, your low value for the mid range. If the rand() returns the .95 or better, * 32 will give you your high randomness of 32 + your base of 33 = 65, the high end of you mid range.

Same for your high end

66-98 = 66-66 = 0 (low), 98-66 = 32 (high) + fixed 66.

66 + cast( 32 * rand() as signed) 

Finally, your steps between x, where x = 1, you are in the below 100 range. x=2 is 100 starting range, x=3 = 200 starting range. So this is simply tacking on (x-1) * 100 to whatever your underlying random such as

(( x-1 ) * 100 ) + ( 33 + cast( 32 * rand() as signed ))

So, you were getting close, but I think this resolves it for you. By using FLOOR() will always chop-off the rounding, but applying the cast as signed will allow the full range. Your choice on means to get rid of rounding.

Generate unique random numbers between 1 and 100

For example: To generate 8 unique random numbers and store them to an array, you can simply do this:

var arr = [];while(arr.length < 8){    var r = Math.floor(Math.random() * 100) + 1;    if(arr.indexOf(r) === -1) arr.push(r);}console.log(arr);

how to generate unique random numbers with a specific range

Solution 1:

I read Jon Skeet's comment, of course, this is the easiest solution:

List<Integer> list = new ArrayList<>();
for (int i = 0; i < 255; i++) {
list.add(i);
}
//and here is the point. Java already have this implemented for you
Collections.shuffle(list);

Or in Java 8 declarative style:

List<Integer> list= IntStream.range(0, 255)
.boxed()
.collect(Collectors.toList());
Collections.shuffle(list);

or

List<Integer> list = new ArrayList<>();
IntStream.range(0, 255).forEach(list::add);
Collections.shuffle(list);

Solution 2 (picking up on your solution):

You need to generate number for each cell, and check if this number already exists:

 short [] array =new short[255];
Random rand = new Random();

for (int i=0; i<array.length; i++) {
int random_integer = -1;

//generate integer while it exists in the array
while(exists(random_integer, array)) {
random_integer = rand.nextInt(255);
}

array[i] = random_integer;
}

And now, let's check whether it exists:

public boolean exists(int number, int[] array) {
if (number == -1)
return true;

for (int i=0; i<array.length; i++) {
if (number == array[i])
return true;
}
return false;
}

Of course, you can use a hashmap for example, to speed up the exists() method, i.e. to lower the complexity from O(n) to O(1);

How do I generate random but unique numbers in python?

You can get such a list of a given number of non-repeating elements taken from a given pool via random.sample:

>>> random.sample(range(500, 510), 9)
[500, 501, 503, 502, 505, 507, 508, 506, 504]

How to generate unique random numbers (that don't repeat)?

One straightforward way to do non-repeating 'random' (psudeorandom) whole numbers in a modest range is to create a list using range(1, n), then random.shuffle() the list, and then take as many numbers as you want from the list using pop() or a slice.

import random

max = 11
l = list(range(1, max)) # the cast to list is optional in Python 2
random.shuffle(l)

Now every time you want a random number, just l.pop().

Another is to use random.sample() -- see https://docs.python.org/3/library/random.html

Generate N random and unique numbers within a range

Take an array of 50 elements: {1, 2, 3, .... 50}
Shuffle the array using any of the standard algorithms of randomly shuffling arrays. The first six elements of the modified array is what you are looking for. HTH

Generating UNIQUE Random Numbers within a range

Array with range of numbers at random order:

$numbers = range(1, 20);
shuffle($numbers);

Wrapped function:

function UniqueRandomNumbersWithinRange($min, $max, $quantity) {
$numbers = range($min, $max);
shuffle($numbers);
return array_slice($numbers, 0, $quantity);
}

Example:

<?php
print_r( UniqueRandomNumbersWithinRange(0,25,5) );
?>

Result:

 Array
(
[0] => 14
[1] => 16
[2] => 17
[3] => 20
[4] => 1
)


Related Topics



Leave a reply



Submit