5

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?

3
  • 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. Commented 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. Commented Sep 30, 2018 at 10:40
  • shuffle sounds good to me. Is it not generating same number? Commented Sep 30, 2018 at 11:04

3 Answers 3

7

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the example. Can I get first 5 shuffled numbers?
you can get using list.sublist(0,5).
0

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

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.