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

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 do not need to generate random numbers in a loop?

+5
source share
5 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 different values, 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];

Please note that if you need to generate a lot of numbers, then a correct implementation in random order will give better performance than OrderBy: O (n) rather than O (n log n). If you need only part of the numbers, then it OrderBywill be okay.

+14

,

http://xkcd.com/221/

r1=2.7;
r2=6.9;
r3=4.2;
r4=8.1;

,

+6

?

, [0, 9999] . , , , . .

int fourDigit = m_Random.Next(10000);
int first = fourDigit % 10; fourDigit /= 10;
int second = fourDigit % 10; fourDigit /= 10;
int third = fourDigit % 10; fourDigit /= 10;
int fourth = fourDigit;

, . , , - . , , Random, .

. , , -, , . .

int fourDigit = m_Random.Next(10000);
int first = fourDigit % 10; fourDigit /= 10;
int second = fourDigit % 10; while (second == first) second = (second + 1) % 10; fourDigit /= 10;
int third = fourDigit % 10; while (third == first || third == second) third = (third + 1) % 10; fourDigit /= 10;
int fourth = fourDigit; while (fourth == first || fourth == second || fourth == third) fourth = (fourth + 1) % 10;
+2

This is what I use to get various random numbers in a given range:

var random = new Random();

int take = 4;
int rangeMin = 0;
int rangeMax = 10;

var randomUniqueNumbers = Enumerable.Range(0, int.MaxValue)
    .Select(i => random.Next(rangeMin, rangeMax))
    .Distinct()
    .Take(Math.Min(take, rangeMax - rangeMin));

It would be better with Infinite enumeration insted Enumerable.Range (0, int.MaxValue), but that does the job.

+2
source

Why not do:

    Enumerable.Range(0, 9)
              .OrderBy(x => Guid.NewGuid().GetHashCode())
              .Take(4)
              .ToArray();
0
source

All Articles