user1161137 - 1 year ago 97
C# Question

# Random number generator, pick 3 in a range, returns group of 2 in some iterations

i put a random number generator together using Linq. the range of those random numbers needs to be in this case 1-6 inclusive. i want groups of 3 distinct numbers chosen.

i don't understand why this code returns groups that contain only 2 numbers.

``````        do
{
Random rnd = new Random();
int[] myRndNos = Enumerable
.Range(1, 6)
.Select(i => rnd.Next(1, 7))
.Distinct()
.Take(3)
.ToArray();

string test = string.Join(",", myRndNos);

System.Console.WriteLine(test);
} while (true);
``````

it returns a sample like:

``````4,6,1
5,2,3
2,4,5
3,2
3,5,1
etc...
``````

why in some cases is it taking only 2 numbers? doesn't make sense to me.
tx

You are generating 6 random numbers but if those numbers happen to be duplicates the distinct will eliminate them leaving you with only the list on unique values, if there are only 2 unique items then that's all you will get.

Because you want 3 distinct numbers, I think what you are after is a shuffle.

``````private static Random rnd = new Random();

int[] myRndNos = Enumerable.Range(1, 6).OrderBy(i => rnd.Next()).Take(3).ToArray();
``````

or

``````private static Random rng = new Random();

int[] myRndNos = Enumerable.Range(1, 6).Shuffle();

public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1) {
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
``````

Source of algorithm: Randomize a List<T>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download