Skip to content

Instantly share code, notes, and snippets.

@tskardal
Last active August 29, 2015 14:23
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save tskardal/3e0373e8fd456d2f36d8 to your computer and use it in GitHub Desktop.
Solving the bowling kata i Clojure
(ns kata-bowling.bowling)
(defn- last-frame? [x y z]
(some nil? [x y z]))
(defn- spare? [x y]
(= (+ x y) 10))
(defn- strike? [x]
(= x 10))
(defn score [[x y z & rolls]]
(cond
(last-frame? x y z) (+ (take-while some? [x y z]))
(spare? x y) (+ 10 z (score (cons z rolls)))
(strike? x) (+ 10 y z (if (empty? rolls) 0 (score (concat [y z] rolls))))
:else (+ x y (score (cons z rolls)))))
(ns kata-bowling.bowling-test
(:require [clojure.test :refer :all]
[kata-bowling.bowling :refer :all]))
(deftest bowling
(testing "everything in the gutter"
(is (= 0 (score (repeat 20 0)))))
(testing "one single pin"
(is (= 1 (score (cons 1 (repeat 19 0))))))
(testing "a spare gives ten plus the number of pins in next throw"
(is (= (+ 10 5 5) (score [5 5 5]))))
(testing "a strike gives ten plus the number of pins in the two next throws"
(is (= (+ 10 3 1 2 5) (score [10 1 2 5]))))
(testing "no spares or strikes"
(is (= 90 (score (take 20 (interpose 0 (repeat 9)))))))
(testing "all spares"
(is (= 150 (score (repeat 21 5)))))
(testing "a perfect game"
(is (= 300 (score (repeat 12 10))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment