Reputation: 225
So guys how do we generate a random number between a range but that shouldnt contain a particular no. in that range in dart?
Upvotes: 1
Views: 2276
Reputation: 1
Here is an example: We set a FlatButton and when pressed, the var "leftdicenumber" receives a random number betxeen 1 and 6:
FlatButton(
onPressed: () {
leftdicenumber = Random().nextInt(6) + 1;
},);
Upvotes: 0
Reputation: 169
Let me show u an example;
// created my method to get random numbers and use wherever I want // used math library to create numbers randomly and equaled to numbers. // now we have to check if it will contains 0 so we will call method again to create new random numbers list which one no including 0.
import 'dart:math';
int void randomNumbers()
{
int numbers=Random().NextInt(10);
if(numbers!=0)
{
return numbers;
}
else
{
int newNumbers= randomNumbers();
return newNumbers,
}
}
so u can call that method created below in anytime to anywhere.
Upvotes: 1
Reputation: 358
Depends on requirements for time, and distribution of result, say you wish to preserve even distribution and want to avoid calling a new random number, and are using the range 0-2000 and filling in 100
import 'dart:math';
void main() {
var n = 100;
do {
r = rng.nextInt(2000);
}
if (r >= n){
r++
}
print(r);
}
Upvotes: 3
Reputation: 7610
If you want to print random numbers from 0 to 999 except say, the number 100. Then the following code fragment will be sufficient.
import 'dart:math';
void main() {
var n = 100;
do {
r = rng.nextInt(1000);
} while (r == n);
print(r);
}
Upvotes: 4