예제 #1
0
        private Dictionary <string, List <LocationsDistance> > GroupByStartLocation(LocationsDistance[] distances)
        {
            Dictionary <string, List <LocationsDistance> > groupedLocationsDistances =
                new Dictionary <string, List <LocationsDistance> >();

            foreach (LocationsDistance distance in distances)
            {
                // Each location can be starting and ending
                string[][] locationsCombinations = new string[2][] {
                    new string[2] {
                        distance.StartLocation, distance.EndLocation
                    },
                    new string[2] {
                        distance.EndLocation, distance.StartLocation
                    }
                };

                // Iterating through both combinations
                for (int i = 0; i < locationsCombinations.Length; i++)
                {
                    var locationsCombination = locationsCombinations[i];

                    LocationsDistance directedDistance = new LocationsDistance
                    {
                        StartLocation = locationsCombination[0],
                        EndLocation   = locationsCombination[1],
                        Distance      = distance.Distance
                    };

                    // If distances starting from this location still don't exist
                    if (!groupedLocationsDistances.ContainsKey(locationsCombination[0]))
                    {
                        List <LocationsDistance> distancesStartingFromLocation = new List <LocationsDistance>();
                        groupedLocationsDistances.Add(locationsCombination[0], distancesStartingFromLocation);
                    }

                    groupedLocationsDistances[locationsCombination[0]].Add(directedDistance);
                }
            }

            return(groupedLocationsDistances);
        }
        public LocationsDistance[] GetDistances(string input)
        {
            string[]            distancesArray = input.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
            LocationsDistance[] distances      = new LocationsDistance[distancesArray.Length];

            Regex distanceRegex = new Regex(@"^(\w+)\sto\s(\w+)\s\=\s(\d+)$");

            for (int i = 0; i < distancesArray.Length; i++)
            {
                Match           distanceMatches = distanceRegex.Match(distancesArray[i]);
                GroupCollection distanceGroups  = distanceMatches.Groups;

                distances[i] = new LocationsDistance
                {
                    StartLocation = distanceGroups[1].Value,
                    EndLocation   = distanceGroups[2].Value,
                    Distance      = int.Parse(distanceGroups[3].Value)
                };
            }

            return(distances);
        }