I have repetition in loop - when isAllowed = true - then continue next iteration, but when isAllowed is false - then the program should repeat generate random positions, coordinates and check if the isAllowed until is true.
How to make recursion in that loop to achieve this objective?
foreach (var fleet in groupedFleetsbySpaceshipCounts)
{
var randomPositionX = new Random().Next(0, 9);
var randomPositionY = new Random().Next(0, 9);
var cords = int.Parse(randomPositionX.ToString() + randomPositionY);
map.Location[cords].ActualFleetPosition = fleet.Key[i];
var isAllowed = IsPositionAllowed(map, cords);
if (isAllowed)
{
break;
}
else
{
randomPositionX = new Random().Next(0, 9);
randomPositionY = new Random().Next(0, 9);
cords = int.Parse(randomPositionX.ToString() + randomPositionY);
map.Location[cords].ActualFleetPosition = fleet.Key[i];
isAllowed = IsPositionAllowed(map, cords);
if (isAllowed)
{
break;
}
else
{
//recursion
}
}
i++;
}
var randomPositionX = new Random().Next(0, 9); var randomPositionY = new Random().Next(0, 9);don't do this, declare the randoms outside the scope you have them as static (class level) and then use them in your calling code.Randominstances in a loop - you also do not need distinct instances to generate 2 values.