Tengo repetición en bucle, cuando isAllowed
= true, luego continuar con la siguiente iteración, pero cuando isAllowed
es falso, entonces el programa debe repetir generar posiciones aleatorias, coordenadas y verificar si isAllowed
hasta que sea verdadero.
¿Cómo hacer recursividad en ese ciclo para lograr este objetivo?
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++; }
Tal vez quieras algo como esto:
var random = new Random(); foreach (var fleet in groupedFleetsbySpaceshipCounts) { int coords; do { int randomPositionX = random.Next(0, 9); int randomPositionY = random.Next(0, 9); coords = 10 * randomPositionX + randomPositionY; } while (!IsPositionAllowed(map, coords)); map.Location[coords].ActualFleetPosition = fleet.Key[i++]; }
Es decir, no necesita una recursividad (es decir, un método que se llame a sí mismo), sino otro bucle anidado dentro del primero.
Tenga en cuenta que el valor máximo de random.Next
es exclusivo. Entonces, si desea números hasta el 9
, debe usar un valor superior de 10
. Además, si el valor más bajo es 0
, simplemente puede escribir random.Next(10)
.
Es importante crear el objeto Random
solo una vez, porque de lo contrario podría terminar teniendo diferentes objetos aleatorios generando la misma secuencia pseudoaleatoria. Usar un campo estático en tu clase es incluso una mejor opción que usar una variable local
private static readonly _random = new Random();
Supongo que esto debería funcionar (editado con algunos de sus comentarios, no quería entrar en otras cosas en lugar de la pregunta):
var random = new Random(); foreach (var fleet in groupedFleetsbySpaceshipCounts) { do { var randomPositionX = random.Next(0, 9); var randomPositionY = random.Next(0, 9); //Im not sure how you're managing this 'coords' map, but gonna just go to the point var cords = int.Parse(randomPositionX.ToString() + randomPositionY); map.Location[cords].ActualFleetPosition = fleet.Key[i]; } while (!IsPositionAllowed(map, cords)); i++; }
Si desea que la variable 'cords' esté disponible fuera del bucle do...while, puede declararla con seguridad fuera del bucle (aún mejor, fuera del foreach).