public static SwapLocations ( |
||
locations | ||
index1 | int | |
index2 | int | |
return | void |
public static void FullyRandomizeLocations(Location[] locations) { if (locations == null) { throw new ArgumentNullException("locations"); } // This code does a full randomization of the destination locations without creating a new array. // If we have 3 items, for example, it will first determine which one of the 3 will be in the last // place, swapping items if needed. Then, it will chose which one of the first 2 items is put at the // second place. And, as everything works by swaps, the item in the first position is obviously the // only one that remains, that's why the i>0 is used instead of i>=0. int count = locations.Length; for (int i = count - 1; i > 0; i--) { int value = GetRandomValue(i + 1); if (value != i) { Location.SwapLocations(locations, i, value); } } }
public static void MutateRandomLocations(Location[] locations) { if (locations == null) { throw new ArgumentNullException("locations"); } if (locations.Length < 2) { throw new ArgumentException("The locations array must have at least two items.", "locations"); } // I opted to give up to 10% of the chromosome size in number of mutations. // Maybe I should find a better number of make this configurable. int mutationCount = GetRandomValue(locations.Length / 10) + 1; for (int mutationIndex = 0; mutationIndex < mutationCount; mutationIndex++) { int index1 = GetRandomValue(locations.Length); int index2 = GetRandomValue(locations.Length - 1); if (index2 >= index1) { index2++; } switch (GetRandomValue(3)) { case 0: Location.SwapLocations(locations, index1, index2); break; case 1: Location.MoveLocations(locations, index1, index2); break; case 2: Location.ReverseRange(locations, index1, index2); break; default: throw new InvalidOperationException(); } } }