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));
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…