trying to change the position of some buttons using the random function, am currently using a setup of 3 while loops for each of my buttons. it works but i was wondering if there's a more efficient way of preventing the random outputs from being the same than what i have? (im pretty new to programming so please let me know how i could improve. thanks!!:D )
Random r = new Random();
int location = r.Next(0, 3);
btnCorrect.Location = new Point(xCoordinates[location], positionY);
int location2 = r.Next(0, 3);
while (location2 == location)
{
location2 = r.Next(0, 3);
}
btnIncorrect1.Location = new Point(xCoordinates[location2], positionY);
int location3 = r.Next(0, 3);
while (location3 == location|| location3==location2)
{
location2 = r.Next(0, 3);
}
btnIncorrect2.Location = new Point(xCoordinates[location2], positionY);
CodePudding user response:
The usual solution for such tasks is to use Fisher–Yates shuffle. In your case you can shuffle indexes:
var rnd = new Random();
var indexes = Enumerable.Range(0, 3).ToArray();
for (int i = 0; i < indexes.Length; i )
{
var j = i rnd.Next(indexes.Length - i);
var element = indexes[i];
indexes[i] = indexes[j];
indexes[j] = element;
}
// use indexes to select elements
// i.e. location = indexes[0], location1 = indexes[1], location2 = indexes[2]
CodePudding user response:
This is another variation of @gurustron 's answer. This solution uses Random
for sorting the values
var rnd = new Random();
var indexes = Enumerable.Range(0, 3).OrderBy(_ => rnd.Next(1000)).ToArray();