Skip to content

Instantly share code, notes, and snippets.

@sbenhaim
Last active December 16, 2015 20:49
Show Gist options
  • Save sbenhaim/ee91dcb26524d3c3d24c to your computer and use it in GitHub Desktop.
Save sbenhaim/ee91dcb26524d3c3d24c to your computer and use it in GitHub Desktop.
(ns advent.a9
(:require [clojure.string :as str]
[clojure.math.combinatorics :refer [permutations]]))
(def text "AlphaCentauri to Snowdin = 66
AlphaCentauri to Tambi = 28
AlphaCentauri to Faerun = 60
AlphaCentauri to Norrath = 34
AlphaCentauri to Straylight = 34
AlphaCentauri to Tristram = 3
AlphaCentauri to Arbre = 108
Snowdin to Tambi = 22
Snowdin to Faerun = 12
Snowdin to Norrath = 91
Snowdin to Straylight = 121
Snowdin to Tristram = 111
Snowdin to Arbre = 71
Tambi to Faerun = 39
Tambi to Norrath = 113
Tambi to Straylight = 130
Tambi to Tristram = 35
Tambi to Arbre = 40
Faerun to Norrath = 63
Faerun to Straylight = 21
Faerun to Tristram = 57
Faerun to Arbre = 83
Norrath to Straylight = 9
Norrath to Tristram = 50
Norrath to Arbre = 60
Straylight to Tristram = 27
Straylight to Arbre = 81
Tristram to Arbre = 90")
(def test "London to Dublin = 464
London to Belfast = 518
Dublin to Belfast = 141")
(defn parse [l]
(let [[_ from to dist] (re-find #"^(\w+) to (\w+) = (\d+)" l)]
[from to (Integer/parseInt dist)]))
(defn distmap [dists]
(reduce (fn [dict [from to dist]]
(-> dict
(update from (fn [dests] (assoc dests to dist)))
(update to (fn [dests] (assoc dests from dist)))))
{} dists))
(def cities (vec (apply hash-set (flatten (map #(take 2 %) dists)))))
(defn routes [distmap]
(for [route (permutations (keys distmap))]
[route (reduce + (for [leg (partition 2 1 route)]
(get-in distmap leg)))]))
(let [distances (->> text
(str/split-lines)
(map parse)
distmap
routes
(map second))]
[(apply min distances) (apply max distances)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment