Skip to content

Instantly share code, notes, and snippets.

@sbenhaim
Created December 18, 2015 03:13
Show Gist options
  • Save sbenhaim/0bc9446620b7ce4b3cb7 to your computer and use it in GitHub Desktop.
Save sbenhaim/0bc9446620b7ce4b3cb7 to your computer and use it in GitHub Desktop.
(ns advent.a13
(:require [clojure.string :as str]
[clojure.math.combinatorics :refer [permutations]]))
(defn parse [l]
(let [[_ subject sign value object]
(re-find #"(\w+) would (gain|lose) (\d+) happiness units by sitting next to (\w+)." l)]
[subject
object
(Integer/parseInt
(if (= sign "gain") value
(str "-" value)))]))
(defn happiness-map [data]
(reduce
(fn [rls [subject object value]]
(update rls subject #(assoc % object value)))
{}
data))
(defn pairs [arrangements]
(conj (partition 2 1 arrangements)
(list (first arrangements) (last arrangements))))
(defn scores [rules pairs]
(reduce +
(map (fn [pair] (+ (or (get-in rules pair) 0)
(or (get-in rules (reverse pair)) 0)))
pairs)))
(let [rules (happiness-map (map parse (str/split-lines (slurp "a13.txt"))))
people (conj (keys rules) "Selah")]
(->> people
permutations
(map pairs)
(map (partial scores rules))
(apply max)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment