Skip to content

Instantly share code, notes, and snippets.

@Ethan826
Last active February 26, 2016 16:25
Show Gist options
  • Save Ethan826/2261d13d467789f2996e to your computer and use it in GitHub Desktop.
Save Ethan826/2261d13d467789f2996e to your computer and use it in GitHub Desktop.
Calculate the chances of the Cubs performance
(ns baseball.core
(:require [clojure.set :as s])
(:gen-class))
(def TEAMS
{:orioles 1901 :red-sox 1901 :yankees 1901 :rays 1998 :blue-jays 1977
:white-sox 1901 :indians 1901 :tigers 1901 :royals 1969 :twins 1901
:astros 1962 :angels 1961 :athletics 1901 :mariners 1977 :rangers 1961
:braves 1871 :marlins 1993 :mets 1962 :phillies 1883 :nationals 1969
:cubs 1874 :reds 1869 :brewers 1969 :pirates 1882 :cardinals 1882
:diamondbacks 1998 :rockies 1993 :dodgers 1884 :padres 1969 :giants 1883})
;; ==============================================================================
;; Cubs chances
(defn how-many [year teams]
(count (filter #(> year (second %)) teams)))
(defn get-counts [start end teams]
(apply merge (map #(assoc {} % (how-many % teams)) (range start end))))
(defn get-chances [start end teams]
(reduce *
(map #(let [total (second %)] (/ (- total 1.0) total))
(get-counts start end teams))))
;; ==============================================================================
;; General chances
(defn get-teams-in-year [year teams]
(set (map first (filter #(> year (second %)) teams))))
(defn simulate-one-year [teams]
(get (vec teams) (rand-int (count teams))))
(defn simulate-one-reality [start end teams]
(map #(simulate-one-year (get-teams-in-year % teams)) (range start end)))
(defn run-simulation [start end teams runs]
(let [start-year-teams (set (get-teams-in-year start teams))
infinite-results (repeatedly #(simulate-one-reality start end teams))
finite-results (take runs infinite-results)
original-teams (get-teams-in-year start teams)
winner-sets (doall (pmap set finite-results))
no-winner-sets (map #(s/difference original-teams %) winner-sets)]
(double (/ (count (filter (complement empty?) no-winner-sets)) runs))))
(defn -main [& args]
(println (str "The chances the Cubs would lose since 1908: "
(get-chances 1909 2015 TEAMS)))
(println (str "The chances any team extant by 1908 would do the same: "
(run-simulation 1909 2015 TEAMS 100000)))
(shutdown-agents))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment