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
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)
.
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 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);
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
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 Array of Unique Random Numbers within Inclusive Range
You could make your live much easier using a Set to store all random numbers until you reach the expected number of randoms:
func uniqueRandoms(numberOfRandoms: Int, minNum: Int, maxNum: UInt32) -> [Int] {
var uniqueNumbers = Set<Int>()
while uniqueNumbers.count < numberOfRandoms {
uniqueNumbers.insert(Int(arc4random_uniform(maxNum + 1)) + minNum)
}
return uniqueNumbers.shuffled()
}
print(uniqueRandoms(numberOfRandoms: 5, minNum: 0, maxNum: 10))
func uniqueRandoms(numberOfRandoms: Int, minNum: Int, maxNum: UInt32, blackList: Int?) -> [Int] {
var uniqueNumbers = Set<Int>()
while uniqueNumbers.count < numberOfRandoms {
uniqueNumbers.insert(Int(arc4random_uniform(maxNum + 1)) + minNum)
}
if let blackList = blackList {
if uniqueNumbers.contains(blackList) {
while uniqueNumbers.count < numberOfRandoms+1 {
uniqueNumbers.insert(Int(arc4random_uniform(maxNum + 1)) + minNum)
}
uniqueNumbers.remove(blackList)
}
}
return uniqueNumbers.shuffled()
}
uniqueRandoms(numberOfRandoms: 3, minNum: 0, maxNum: 10, blackList: 8) // [0, 10, 7]
Related Topics
Printing All Instances of a Class
Saving and Loading Multiple Objects in Pickle File
How to Fix Overlapping Annotations/Text
Python Strings and Integer Concatenation
Retrieving Parameters from a Url
Slicing a List in Python Without Generating a Copy
Post-Install Script with Python Setuptools
Set Colorbar Range in Matplotlib
Understanding Nested List Comprehension
Python Nameerror: Name Is Not Defined
In Tkinter How to Make a Widget Invisible
Opencv 2.4 Videocapture Not Working on Windows
Check for Presence of a Sliced List in Python