Explorar o código

D09 cleanup code

bastien.monsarrat %!s(int64=6) %!d(string=hai) anos
pai
achega
572fee3a98
Modificáronse 1 ficheiros con 9 adicións e 13 borrados
  1. 9 13
      D09.1/Program.cs

+ 9 - 13
D09.1/Program.cs

@@ -1,6 +1,7 @@
 using System;
 using System.Collections.Generic;
 using System.IO;
+using System.Linq;
 
 namespace D09._1
 {
@@ -11,7 +12,7 @@ namespace D09._1
         public VisitedList(VisitedList list) => Next = list;
         public bool Contains(Place place)
         {
-            if (Visited.Equals(place)) return true;
+            if (Visited?.Equals(place) ?? false) return true;
             return Next?.Contains(place) ?? false;
         }
         public int Count() => 1 + Next?.Count() ?? 1;
@@ -40,17 +41,18 @@ namespace D09._1
 
     class Program
     {
-        static (int best, int worst) Test(Place start, VisitedList visited, int traveled, int totalPlaces)
+        static (int best, int worst) TestTravelRoutes(Dictionary<string, Place> places, Place start = null, VisitedList visited = null, int traveled = 0)
         {
-            if (visited.Count() == totalPlaces)
+            if (visited?.Count() == places.Count)
                 return (traveled, traveled);
 
             int best = -1, worst = -1;
-            foreach ((int distance, Place neighbor) in start.Neighbors)
+            foreach ((int distance, Place neighbor) in start?.Neighbors ?? places.Values.Select(v => (0, v)))
             {
-                if (visited.Contains(neighbor)) continue;
+                if (visited?.Contains(neighbor) ?? false) continue;
+
+                (int b, int w) = TestTravelRoutes(places, neighbor, new VisitedList(visited) { Visited = start }, traveled + distance);
 
-                (int b, int w) = Test(neighbor, new VisitedList(visited) { Visited = start }, traveled + distance, totalPlaces);
                 if (best == -1 || b < best) best = b;
                 if (w > worst) worst = w;
             }
@@ -67,13 +69,7 @@ namespace D09._1
 
             ParseFile(args, places);
 
-            int best = -1, worst = -1;
-            foreach ((string name, Place start) in places)
-            {
-                (int b, int w) = Test(start, new VisitedList(null) { Visited = start }, 0, places.Count);
-                if (best == -1 || b < best) best = b;
-                if (w > worst) worst = w;
-            }
+            (int best, int worst) = TestTravelRoutes(places);
 
             Console.WriteLine($"The best distance is : {best}");
             Console.WriteLine($"The worst distance is : {worst}");