Skip to content

Instantly share code, notes, and snippets.

@johnboker
Created December 9, 2015 16:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnboker/c96646f79c1f17202638 to your computer and use it in GitHub Desktop.
Save johnboker/c96646f79c1f17202638 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Linq;
namespace AdventOfCodeDay9
{
class MainClass
{
public static void Main (string[] args)
{
var sr = new StreamReader ("../../input1.txt"); // select part one or two here.
string line;
var regex = new Regex ("^(?<City1>.*?) to (?<City2>.*?) = (?<Distance>.*?)$");
var distances = new Dictionary<string, int> ();
var cities = new List<string> ();
while ((line = sr.ReadLine ()) != null) {
var m = regex.Match (line);
if (m.Success) {
var city1 = m.Groups ["City1"].Value;
var city2 = m.Groups ["City2"].Value;
cities.Add (city1);
cities.Add (city2);
var distance = int.Parse (m.Groups ["Distance"].Value);
distances.Add ($"{city1}-{city2}", distance);
} else {
throw new Exception ("Oh Noes!");
}
}
Console.WriteLine (distances.Count);
cities = cities.Distinct ().ToList ();
cities.ForEach (Console.WriteLine);
var allPaths = cities.Permute ();
var shortest = DistanceForPath (distances, cities);
var longest = shortest;
foreach (var p in allPaths) {
var dist = DistanceForPath (distances, p.ToList ());
Console.WriteLine (dist + ": " + string.Join ("-", p));
shortest = Math.Min (dist, shortest);
longest = Math.Max (dist, longest);
}
Console.WriteLine ($"Shortest {shortest}");
Console.WriteLine ($"Longest {longest}");
}
private static int DistanceForPath (Dictionary<string, int> distances, List<string> path)
{
int dist = 0;
for (int i = 0; i < path.Count () - 1; i++) {
var key = $"{path[i]}-{path[i+1]}";
if (!distances.ContainsKey (key)) {
key = $"{path[i+1]}-{path[i]}";
}
dist += distances [key];
}
return dist;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment