Search code examples
dart

How to Generate Random number without repetition in Dart?


I want to generate random numbers within the range of 1-100, without repetition in flutter. And when there are no more numbers to generate (i.e :- every number within 1-100 have been generated randomly without repeats) I want to set a boolean named "noNumbersLeft" to true. How do I do that?


Solution

  • As pointed out in comments the previous way is inefficient. I've updated that to use Set instead of Map. But it doesn't make it efficient. Instead you can you can generate a List containing 1-100 first and shuffle it. Then you take value from this shuffled list until it's empty.

    final rnList = List<int>.generate(100, (index) => index + 1)..shuffle();
    
    while (rnList.isNotEmpty) {
      final rn = rnList.removeLast();
      // do sth with the number
    }
    

    INEFFICIENT

    This while loop will create all the numbers from 1-100 without repetition.

    final generatedRandoms = <int>{};
    
    final rng = Random();
    while (generatedRandoms.length < 100) {
      final gr = rng.nextInt(100) + 1;
      generatedRandoms.add(gr);
    }
    

    Now if you need the random number generation happens at different times, say when user taps on a button, the approach stays the same. You use a set, map or array where you keep track of generated numbers. If the number is generated already you call rng.nextInt until you get a number that hasn't been generated. Once your map reaches 100 length means you've used them all and then can set noNumbersLeft to true.