I am trying to work out how to make a random number generator that outputs 4 integers going from 0 to 9 without any repeats.
Would like some help please i have just started coding in c# but cant find any answers to my issue
I am trying to work out how to make a random number generator that outputs 4 integers going from 0 to 9 without any repeats.
Would like some help please i have just started coding in c# but cant find any answers to my issue
For "quick and dirty" solution you can use LINQ
. For example something like this will randomly select 4 numbers in range from 0 to 9:
var random = new Random();
var numbers = Enumerable.Range(0, 10)
.OrderBy(_ => random.Next())
.Take(4)
.ToList();
In case you need something more prescise and faster then you can implement Fisher–Yates shuffle for example.
You need to remove the int
from the checking if it has already repeated.
so:
if (val1 == val2)
{
val2 = rnd.Next(1,11);
}
and not:
if (val1 == val2)
{
int val2 = rnd.Next(1,11);
}
The latter will declare a new variable "val2" which exists only inside the scope of the "if" block, instead of updating the existing "val2" variable as you intended. This is called "shadowing".