iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 9
0
自我挑戰組

各種筆記系列 第 9

[Kata] Clojure - Day 9

  • 分享至 

  • xImage
  •  

Maximum Length Difference

You are given two arrays a1 and a2 of strings. Each string is composed with letters from a to z. Let x be any string in the first array and y be any string in the second array.

Find max(abs(length(x) − length(y)))

If a1 and/or a2 are empty return -1 in each language except in Haskell (F#) where you will return Nothing (None).

有 a1 和 a2 兩個陣列,陣列的 items 由不同長度的字串組成,找出字串長度差異最大值。
如果 a1 或 a2 為空陣列,則回傳 -1

Example

a1 = ["hoqq", "bbllkw", "oox", "ejjuyyy", "plmiis", "xxxzgpsssa", "xxwwkktt", "znnnnfqknaz", "qqquuhii", "dvvvwz"]
a2 = ["cccooommaaqqoxii", "gggqaffhhh", "tttoowwwmmww"]
mxdiflg(a1, a2) --> 13

Solution

(ns maxdifflength.core)

(defn mxdiflg [a1 a2]
  (reduce max -1 
    (for [x a1, y a2] 
      (Math/abs (- (count x) (count y))))))
;; val is optional, coll will be applied to f
(reduce f coll)
(reduce f val coll)

(reduce + [1 2])   ;; 3
(reduce + 3 [1 2]) ;; 6
;; Return the maximun of nums
(max x & more)

(max 5 4 3 2 1)          ;; 5

;; apply and reduce can be used when elements in sequence
(apply max [1 2 3 4 5])      ;; 5
(apply max '(1 2 3 4 5))     ;; 5
(reduce max '(1 2 3 4 5))    ;; 5
(reduce max 10 '(1 2 3 4 5)) ;; 10
(for seq-exprs body-expr)

;; assign vector to x & y, and produce sequence after pair x & y
(def nums [1 2 3])
(for [x nums y nums] (* x y)) ;; (1 2 3 2 4 6 3 6 9)

上一篇
[Kata] Clojure - Day 8
下一篇
[Kata] Clojure - Day 10
系列文
各種筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言