iT邦幫忙

2022 iThome 鐵人賽

DAY 20
0
Modern Web

clojure 刷刷鍋系列 第 20

Clojure 肉片 -第 20 塊

  • 分享至 

  • xImage
  •  

【今日湯底】

Take an integer n (n >= 0) and a digit d (0 <= d <= 9) as an integer.

Square all numbers k (0 <= k <= n) between 0 and n.

Count the numbers of digits d used in the writing of all the k**2.

Call nb_dig (or nbDig or ...) the function taking n and d as parameters and returning this count.

Examples:
n = 10, d = 1
the k*k are 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100
We are using the digit 1 in: 1, 16, 81, 100. The total count is then 4.

nb_dig(25, 1) returns 11 since
the k*k that contain the digit 1 are:
1, 16, 81, 100, 121, 144, 169, 196, 361, 441.
So there are 11 digits 1 for the squares of numbers between 0 and 25.
Note that 121 has twice the digit 1.

(必須通過以下測試)

(ns countdig.core-test
  (:require [clojure.test :refer :all]
            [countdig.core :refer :all]))

(defn test-assert [act exp]
  (is (= act exp)))
  
(deftest a-test1
  (testing "nb-dig"
     (test-assert(nb-dig 5750, 0), 4700)
     (test-assert(nb-dig 11011, 2), 9481)
     (test-assert(nb-dig 12224, 8), 7733)
     (test-assert(nb-dig 11549, 1), 11905)
))

【我的答案】

(ns countdig.core)

(defn nb-dig [n d]
  (let [dict (->> n
               inc
               range
               (map #(str (* % %)))
               (clojure.string/join "")
               frequencies)]
    (get dict (first (str d))))
  )
;; 看完別人答案後,嘗試用 re-seq / re-pattern 組合技 寫出另個版本
(ns countdig.core)

(defn nb-dig [n d]
  (->>
    (range (inc n))
    (map #(str (* % %)))
    (clojure.string/join "")
    (re-seq (re-pattern (str d)))
    count)
  )

【其他人的答案】

(ns countdig.core)

(defn nb-dig [n d]
  ((->> (range (inc n))
        (mapcat #(str (* % %)))
        frequencies)
   (first (str d))))
(ns countdig.core)

(defn nb-dig [n d]
  (->> (inc n)
       (range)
       (map #(* % %))
       (map str)
       (filter #(clojure.string/includes? % (str d)))
       (map #(count (re-seq (re-pattern (str d)) %)))
       (reduce +)))

上一篇
Clojure 肉片 -第 19 塊
下一篇
Clojure 肉片 -第 21 塊
系列文
clojure 刷刷鍋30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言