Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get 4 unique random numbers in range <0;9>?

Tags:

c#

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?

like image 788
Richard Knop Avatar asked Nov 09 '10 00:11

Richard Knop


2 Answers

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.

like image 185
LukeH Avatar answered Sep 30 '22 20:09

LukeH


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

like image 23
pm100 Avatar answered Sep 30 '22 20:09

pm100