I want to get 4 unique random floating point numbers in the range <0;9>. How could I do that. Is it possible to do this with a single function so I don't need to generate random numbers in a loop?
var rng = new Random();
int first = rng.Next(10);
int second = rng.Next(10);
int third = rng.Next(10);
int fourth = rng.Next(10);
If you need four distinct values then you can do something like this...
var rng = new Random();
var values = Enumerable.Range(0, 10).OrderBy(x => rng.Next()).ToArray();
int first = values[0];
int second = values[1];
int third = values[2];
int fourth = values[3];
Note that if you needed to generate many numbers then a proper shuffle implementation will give better performance than OrderBy
: O(n) rather than O(n log n). If you only need a handful of numbers then OrderBy
will be fine.
I am sorry but I could not resist
http://xkcd.com/221/
In that spirit you can do
r1=2.7;
r2=6.9;
r3=4.2;
r4=8.1;
I swear they are random
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With