//if cities is null, O(n), otherwise O(n^3) public Population(int populationSize, City[] cities = null) { if (cities != null) { Greedy g = new Greedy(); //O(n^3) List <ArrayList> greedyRoutes = g.getRoutes(cities); //shuffle routes //O(n) int n = greedyRoutes.Count; while (n > 1) { n--; int k = rng.Next(n + 1); ArrayList value = greedyRoutes[k]; greedyRoutes[k] = greedyRoutes[n]; greedyRoutes[n] = value; } //worst O(m*n) where m is population size and n is number of cities if (populationSize > greedyRoutes.Count) { routes = new List <ArrayList>(); for (int i = 0; i < greedyRoutes.Count; i++) { routes.Add(new ArrayList()); routes[i] = greedyRoutes[i]; } for (int i = greedyRoutes.Count; i < populationSize; i++) { routes.Add(new ArrayList()); //O(n) routes[i] = Spawn(cities); } } //O(k) else { routes = greedyRoutes.GetRange(0, populationSize); } } //O(n) where n is population size else { routes = new List <ArrayList>(); for (int i = 0; i < populationSize; i++) { routes.Add(new ArrayList()); //this is to see if the constructor should spawn or not - this was for previous version that did not use the greedy results as population. Now unreachable if (cities != null) { routes[i] = Spawn(cities); } } } }
///////////////////////////////////////////////////////////////////////////////////////////// // These additional solver methods will be implemented as part of the group project. //////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// finds the greedy tour starting from each city and keeps the best (valid) one /// </summary> /// <returns>results array for GUI that contains three ints: cost of solution, time spent to find solution, number of solutions found during search (not counting initial BSSF estimate)</returns> public string[] greedySolveProblem() { string[] results = new string[3]; Greedy g = new Greedy(); ArrayList route; string time; g.solve(out route, Cities, out time); bssf = new TSPSolution(route); results[COST] = bssf.costOfRoute().ToString(); // load results into array here, replacing these dummy values results[TIME] = time; results[COUNT] = "0"; return(results); }