Generate N Random and Unique 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 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]

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

Generate N unique random integers within a specified range

This is because the call to np.random.randint might return the same value twice and this redundancy is taken away by pandas (check df[[1, 1]]). So instead you can use np.random.choice(80, 30, replace=False).

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);

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
)

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

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);

Generate list of unique random numbers in Swift from range

There are 2 problems here:

  1. You don't generate enough numbers. You need to keep generating random numbers until your set is large enough:

    func getRandomNumbers(maxNumber: Int, listSize: Int)-> [Int] {
    var randomNumbers = Set<Int>()
    while randomNumbers.count < listSize {
    let randomNumber = Int(arc4random_uniform(UInt32(maxNumber+1)))
    randomNumbers.insert(randomNumber)
    }
    return randomNumbers
    }
  2. You're biasing your random numbers by putting them in the ordering Set chooses, which is highly predictable. You should append your numbers to an array (to keep them in order that they are generated), while still leveraging a set in parallel, for its fast deduplication:

    func getRandomNumbers(maxNumber: Int, listSize: Int)-> [Int] {
    precondition(listSize < maxNumber, "Cannot generate a list of \(listSize) unique numbers, if they all have to be less than \(maxNumber)")

    var randomNumbers = (array: [Int](), set: Set<Int>())

    while randomNumbers.set.count < listSize {
    let randomNumber = Int(arc4random_uniform(UInt32(maxNumber+1)))
    if randomNumbers.set.insert(randomNumber).inserted { // If the number is unique
    randomNumbers.array.append(randomNumber) // then also add it to the arary
    }
    }

    return randomNumbers.array
    }


Related Topics



Leave a reply



Submit