Skip to content

Instantly share code, notes, and snippets.

@plecong
Created December 9, 2015 05:39
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 plecong/72f9711c885a489e9e05 to your computer and use it in GitHub Desktop.
Save plecong/72f9711c885a489e9e05 to your computer and use it in GitHub Desktop.
open System
open System.Collections.Generic
open System.IO
open System.Text.RegularExpressions
type Route = {
a : string; b : string; distance : int
}
let routesRegex = @"(\w+) to (\w+) = (\d+)"
let readRoute (input : string) : Route =
seq {
for g in Regex.Match(input, routesRegex).Groups do
yield g
}
|> Seq.map (fun g -> g.Value)
|> Seq.toArray
|> (fun g -> { a = g.[1]; b = g.[2]; distance = Convert.ToInt32(g.[3]) })
let distrib e L =
let rec aux pre post =
seq {
match post with
| [] -> yield (L @ [e])
| h::t -> yield (List.rev pre @ [e] @ post)
yield! aux (h::pre) t
}
aux [] L
let rec perms = function
| [] -> Seq.singleton []
| h::t -> Seq.collect (distrib h) (perms t)
let extractCities (rs : Route seq) =
let s = new HashSet<string>()
for r in rs do
s.Add(r.a) |> ignore
s.Add(r.b) |> ignore
s |> Seq.toList
let extractRouteMap (rs : Route seq) =
rs
|> Seq.map (fun x -> [ ((x.a, x.b), x.distance); ((x.b, x.a), x.distance) ])
|> List.concat
|> dict
let routeDistance (routeMap : IDictionary<(string * string),int>) (route : string list) =
route
|> Seq.pairwise
|> Seq.map (fun p -> routeMap.[p])
|> Seq.sum
let sortedRoutes =
let routes =
File.ReadAllLines(@"./AdventOfCode_Day9_input.txt")
|> Seq.map readRoute
|> Seq.toList
let routeMap = extractRouteMap routes
let router = routeDistance routeMap
extractCities routes
|> perms
|> Seq.map router
let part1 =
sortedRoutes
|> Seq.min
let part2 =
sortedRoutes
|> Seq.max
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment