Problem 017: Number letter counts

From Project Euler:

If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.

If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?

NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.

This one doesn't really involve anything fancy, it's just a simple list of sometimes-recursive conditions:
(defn translate [n]
  (cond
    (== n 1000) "onethousand"
    (>= n 100) (str (translate (quot n 100))
                    "hundred"
                    (if (> (mod n 100) 0)
                      (str "and" (translate (mod n 100)))
                      ""))
    (< n 20) (nth ["zero" "one" "two" "three" "four" "five" "six" "seven"
                   "eight" "nine" "ten" "eleven" "twelve" "thirteen"
                   "fourteen" "fifteen" "sixteen" "seventeen" "eighteen"
                   "nineteen"]
                  n)
    (== 0 (mod n 10)) (nth ["twenty" "thirty" "forty" "fifty" "sixty"
                            "seventy" "eighty" "ninety"]
                           (- (quot n 10) 2))
    :else (str (translate (* (quot n 10) 10))
               (translate (mod n 10)))))

(defn count-letters [n]
  (->> (range 1 (+ 1 n))
       (map translate)
       (map count)
       (reduce +)))
As expected, it doesn't take long at all to run:
$ lein run
Processing...
21124
"Elapsed time: 14.712378 msecs"

No comments:

Post a Comment