~willvaughn/kata

9580409b7397fa62d4f5e45d29a93f16c540b5af — William Vaughn 1 year, 5 months ago 4cdbcaa
codewars greed is good
A codewars/src/clj/org/willvaughn/codewars/greed_is_good.clj => codewars/src/clj/org/willvaughn/codewars/greed_is_good.clj +51 -0
@@ 0,0 1,51 @@
(ns org.willvaughn.codewars.greed-is-good)

;;; Greed is a dice game played with five six-sided dice. Your mission, should you choose to accept it, is to score a throw according to these rules. You will always be given an array with five six-sided dice values.
;;; 
;;;  Three 1's => 1000 points
;;;  Three 6's =>  600 points
;;;  Three 5's =>  500 points
;;;  Three 4's =>  400 points
;;;  Three 3's =>  300 points
;;;  Three 2's =>  200 points
;;;  One   1   =>  100 points
;;;  One   5   =>   50 point
;;; A single die can only be counted once in each roll. For example, a given "5" can only count as part of a triplet (contributing to the 500 points) or as a single 50 points, but not both in the same roll.
;;; 
;;; Example scoring
;;; 
;;;  Throw       Score
;;;  ---------   ------------------
;;;  5 1 3 4 1   250:  50 (for the 5) + 2 * 100 (for the 1s)
;;;  1 1 1 3 1   1100: 1000 (for three 1s) + 100 (for the other 1)
;;;  2 4 4 5 4   450:  400 (for three 4s) + 50 (for the 5)
;;; In some languages, it is possible to mutate the input to the function. This is something that you should never do. If you mutate the input, you will not be able to pass all the tests.

(def triplet-scores
  {1 1000
   2 200
   3 300
   4 400
   5 500
   6 600})

(def solo-scores
  {1 100
   5 50})

(defn score [dice]
  (reduce
   (fn [score [dice freq]]
     (let [triplet? (>= freq 3)
           triplet-score (if triplet?
                           (get triplet-scores dice)
                           0)
           solo-score (if-let [v (get solo-scores dice)]
                        (* v
                           (if triplet?
                             (- freq 3)
                             freq))
                        0)]
       (+ score solo-score triplet-score)))
   0
   (frequencies dice)))

A codewars/test/clj/org/willvaughn/codewars/greed_is_good_test.clj => codewars/test/clj/org/willvaughn/codewars/greed_is_good_test.clj +18 -0
@@ 0,0 1,18 @@
(ns org.willvaughn.codewars.greed-is-good-test
  (:require
   [clojure.test :refer :all]
   [org.willvaughn.codewars.greed-is-good :refer [score]]))

(deftest basic-tests
  (is (= (score [1 1 1 3 3]) 1000))
  (is (= (score [2 2 2 3 3])  200))
  (is (= (score [3 3 3 3 3])  300))
  (is (= (score [4 4 4 3 3])  400))
  (is (= (score [5 5 5 3 3])  500))
  (is (= (score [6 6 6 3 3])  600))

  (is (= (score [1 1 1 1 3])  1100))
  (is (= (score [1 1 1 1 5])  1150))
  (is (= (score [2 4 4 5 4])  450))
  (is (= (score [3 4 5 3 3])  350))
  (is (= (score [1 5 1 3 4])  250)))