DEV Community

Discussion on: Daily Challenge #8 - Scrabble Word Calculator

Collapse
 
johncip profile image
jmc

Clojure:

(ns scrabble
  (:require [clojure.string :as s]))

(def values
  (zipmap
    [\a \b \c \d \e \f \g \h \i \j \k \l \m \n \o \p \q \r \s \t \u \v \w \x \y \z]
    [ 1  3  3  2  1  4  2  4  1  8  5  1  3  1  1  3 10  1  1  1  1  4  4  8  4 10]))

(defn letter-score [[a b c]]
  (let [base (values a 0)
        mult (cond (= b \^)                0
                   (and (= b \*) (= c \*)) 3
                   (= b \*)                2
                   :else                   1)]
    (* base mult)))

(defn trim [word]
  (s/replace word #"\(\w\)$" ""))

(defn base-word-score [word]
  (->> (trim word)
       (partition-all 3 1)
       (map letter-score)
       (apply +)))

(defn bonus [word]
  (if (= 7 (count (s/replace (trim word) #"\W" ""))) 50 0))

(defn score [word]
  (let [base (base-word-score word)
        mult (cond (s/ends-with? word "(t)") 3
                   (s/ends-with? word "(d)") 2
                   :else                     1)]
    (+ (bonus word) (* base mult))))