Skip to content

Instantly share code, notes, and snippets.

@jraines
Last active December 2, 2016 04:15
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 jraines/50cf68759211be2c79cac79409054e04 to your computer and use it in GitHub Desktop.
Save jraines/50cf68759211be2c79cac79409054e04 to your computer and use it in GitHub Desktop.
electors.clj
(ns electoral.core
(:require [csv-map.core :as csv])
(:gen-class))
(defn get-votes [e state-name]
(:votes (first (filter #(= state-name (:state %)) e))))
(def data
(let [p (csv/parse-csv (slurp "resources/pop.csv") :key :keyword)
e (csv/parse-csv (slurp "resources/elec.csv") :key :keyword)]
(for [s p]
(-> s
(assoc :votes (get-votes e (:state s)))
(update :population #(Integer. %))
(update :votes #(Integer. %))))))
(def sorted
(sort-by :population data))
(def with-cumulative-votes
(reduce
(fn [acc x]
(let [running-vote-total (if (empty? acc) 0 (:vote-total (last acc)))
new-vote-total (+ running-vote-total (:votes x))]
(conj acc (assoc x :vote-total new-vote-total))))
[]
sorted))
(def partitioned
(partition-by #(< 270 (:vote-total %)) with-cumulative-votes))
(def eligible-fraction 241/313)
(defn population
[states]
(int
(* eligible-fraction
(->> states
(map :population)
(reduce +)))))
(def vote-counts
(let [winner-pop (population (first partitioned))
loser-pop (population (second partitioned))
half-winner-pop (/ winner-pop 2)
loser-pop (+ loser-pop half-winner-pop)]
{:winner winner-pop
:loser loser-pop}))
(defn -main
[& args]
(println vote-counts))
; {:winner 104932944, :loser 190942633}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment