Is there any way to generate random numbers without duplication? For instance I want to generate 50 random numbers from 1 to 100 no duplication, any way to do this or do I have to check every time incoming number is already created or not?
-
If it's only small range of integer you can use hash table to keep all free number. Then pop it out at random index.kitta– kitta2018-09-30 10:13:44 +00:00Commented Sep 30, 2018 at 10:13
-
you can create an array of integer with 1 to 100 number and shuffle it using shuffle method and used as much as number you require.Viren V Varasadiya– Viren V Varasadiya2018-09-30 10:40:21 +00:00Commented Sep 30, 2018 at 10:40
-
shuffle sounds good to me. Is it not generating same number?Daibaku– Daibaku2018-09-30 11:04:58 +00:00Commented Sep 30, 2018 at 11:04
Add a comment
|
3 Answers
you can use shuffle as following code.
import 'dart:math';
var list = new List<int>.generate(10, (int index) => index); // [0, 1, 4]
list.shuffle();
print(list);
2 Comments
Daibaku
Thank you for the example. Can I get first 5 shuffled numbers?
Viren V Varasadiya
you can get using list.sublist(0,5).
You can use Set. Each object can occur only once when using it. Just try this:
Set<int> setOfInts = Set();
while (setOfInts.length < 50) {
setOfInts.add(Random().nextInt(range) + 1);
}
You can read the documentation here: Set Doc
Comments
Here is an alternative that avoids creating an array of all the possible values, and avoids repeatedly looping until no collision occurs. It may be useful when there is a large range to select from.
import 'dart:math';
class RandomList {
static final _random = new Random();
static List<int> uniqueSample({int limit, int n}) {
final List<int> sortedResult = [];
final List<int> result = [];
for (int i = 0; i < n; i++) {
int rn = _random.nextInt(limit - i); // We select from a smaller list of available numbers each time
// Increment the number so that it picks from the remaining list of available numbers
int j = 0;
for (; j < sortedResult.length && sortedResult[j] <= rn; j++) rn++;
sortedResult.insert(j, rn);
result.add(rn);
}
return result;
}
}
I haven't tested it exhaustively but it seems to work.