Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

thinking in sequences

  • Loading branch information...
commit c958cd1700767539f1d9f44f4e4d2d5e4c709676 1 parent 9634ab3
Stuart Halloway authored
Showing with 47 additions and 16 deletions.
  1. +28 −16 src/bowling_game.clj
  2. +19 −0 test/test/bowling_game.clj
44 src/bowling_game.clj
View
@@ -2,30 +2,42 @@
(defn new-game [] [])
(defn next-two-balls [rolls]
- (+ (rolls 0) (rolls 1)))
+ (apply + (take 2 rolls)))
(defn score-strike [rolls]
- [1 (+ 10 (+ (rolls 1) (rolls 2)))])
+ (apply + (take 3 rolls)))
(defn score-spare [rolls]
- [2 (+ 10 (rolls 2))])
+ (apply + (take 3 rolls)))
(defn score-no-mark [rolls]
- [2 (next-two-balls rolls)])
+ (apply + (take 2 rolls)))
+
+(defn strike? [rolls]
+ (= 10 (first rolls)))
+
+(defn spare? [rolls]
+ (= 10 (next-two-balls rolls)))
(defn score-next-frame [rolls]
- (if (= 10 (first rolls))
- (score-strike rolls)
- (if (= 10 (next-two-balls rolls))
- (score-spare rolls)
- (score-no-mark rolls))))
-
-(defn score [game]
- (loop [frame 1 rolls game score 0]
- (if (> frame 10)
- score
- (let [frame-score (score-next-frame rolls)]
- (recur (inc frame) (subvec rolls (frame-score 0)) (+ score (frame-score 1)))))))
+ (cond
+ (strike? rolls) (score-strike rolls)
+ (spare? rolls) (score-spare rolls)
+ :else (score-no-mark rolls)))
+
+(defn frame-advance [rolls]
+ (if (strike? rolls) 1 2))
+
+(defn score-frames [frames]
+ (letfn [(score-frames*
+ [frames]
+ (if (seq frames)
+ (lazy-seq (cons (score-next-frame frames)
+ (score-frames* (drop (frame-advance frames) frames))))))]
+ (take 10 (score-frames* frames))))
+
+(defn score [frames]
+ (apply + (score-frames frames)))
(defn roll [game pins]
(conj game pins))
19 test/test/bowling_game.clj
View
@@ -19,6 +19,25 @@
(deftest can-create-game
(is (not (nil? (new-game)))))
+(deftest scoring-frames
+ (are [description score frames] (= score (score-next-frame frames))
+ :strike 30 [10 10 10]
+ :spare 20 [5 5 10]
+ :no-mark 8 [5 3 5]))
+
+(deftest advancing-frames
+ (is (= 1 (frame-advance [10])))
+ (is (= 2 (frame-advance [5 5])))
+ (is (= 2 (frame-advance [1 1]))))
+
+(deftest test-score-frames-for-various-games
+ (are [description expected-scores game] (= expected-scores (score-frames game))
+ "gutter game" (repeat 10 0) (repeat 20 0)
+ "all ones" (repeat 10 2) (repeat 20 1)
+ "all fives (spares)" (repeat 10 15) (repeat 21 5)
+ "all tens (strikes)" (repeat 10 30) (repeat 22 10)
+ ))
+
(deftest test-various-games
(are [description expected-score game] (= expected-score (score game))
"gutter game" 0 (gutter-game (new-game))
Please sign in to comment.
Something went wrong with that request. Please try again.