Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
519 views
in Technique[技术] by (71.8m points)

flutter - How to generate 3 unique random numbers excluding a particular no. in Dart?

How to generate 3 non-repeating random numbers excluding a particular no.? For example:

n = 1;
a = ?;
b = ?;
c = ?;
where a!=b && a!=c && a!=n &&b!= a && b!=c &&b!=n &&c!=a &&c!=b &&c!=n;

another example would be

nextInt is 5 and n is 1 then I want to display 2,3,4 and 3,4,5, and 2,3,5 whenever the method gets called. Help would be appreciated.

question from:https://stackoverflow.com/questions/65937679/how-to-generate-3-unique-random-numbers-excluding-a-particular-no-in-dart

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could for instance utilize the Set<E> class. When you create a new random number, check if it's valid (ie different from n). If yes add to the set. Do this until the set contains enough (ie 3) elements.

import "dart:math";

void main() {
  int randomCount = 3; 
  int avoid = 15;
  var randomNumbers = new Set<int>();
  var rand = new Random();
  
  while (randomNumbers.length != randomCount) {
    int r = rand.nextInt(100);
    if (r != avoid)
      randomNumbers.add(r);
  }
  
  randomNumbers.forEach((element) => print(element));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...