Take 2 strings s1 and s2 including only letters from a to z. Return a new sorted string, the longest possible, containing distinct letters - each taken only once - coming from s1 or s2.
Examples:
a = "xyaabbbccccdefww"
b = "xxxxyyyyabklmopq"
longest(a, b) -> "abcdefklmopqwxy"a = "abcdefghijklmnopqrstuvwxyz"
longest(a, a) -> "abcdefghijklmnopqrstuvwxyz"
concat
: combines two strings into a single sequence (strings are automatically treated as sequences of characters)distinct
: removes duplicate characters from the sequencesort
: sorts characters alphabeticallyapply
str: converts sequence of characters back to a string; implement
(defn longest [s1 s2]
(->> (concat s1 s2)
(distinct)
(sort)
(apply str)))
; test
; execute implement function
(defn tester [s1 s2 exp]
(= (longest s1 s2) exp))
; args & exception
(comment
(tester "aretheyhere" "yestheyarehere" "aehrsty")
(tester "loopingisfunbutdangerous" "lessdangerousthancoding" "abcdefghilnoprstu")
(tester "inmanylanguages" "theresapairoffunctions" "acefghilmnoprstuy"))
這次終於完賽啦,實際上只寫了 28 題 (扣掉 Day 0 & day 4 番外篇)。
大部分題目是今年四月開始寫,慢慢累積起來的。但後面大概七八題是鐵人賽開始才寫的。
最後。根據這 30 天寫的內容,整理一下幾個我最常用的方法。
處理集合:
map
: transforming a collection and returning a new lazy sequence.reduce
: aggregating a collection into a single accumulated value.filter
: selecting elements from a collection based on a predicate, returning a new lazy sequence.apply
: applying functions to collections (it expands the last collection into multiple arguments).*lazy sequenc: A sequence whose elements are only computed when they are needed.
處理字串:
split
: splits a string into a sequence of substrings, based on a given pattern (usually a regex).join
: joins a collection of strings into a single string, optionally with a separator.replace
: replaces all instances of a substring or regex match in a string with a new value.取得元素:
first
: returns the first element of a collection (If the collection is empty, it returns nil).rest
: returns a sequence of all elements except the first.另外,也很常使用 thread last。
->>
: takes a value and threads it as the last argument into each following form.特別適合用在集合處理(搭配上面提到的 map、filter、reduce 等等),因為這些 function 的參數通常在最後。就可以很自然地把一個資料流一步步處理。
最後,寫題之餘,放一隻想看的影片,提醒自己之後要看。
"Simple Made Easy" - Rich Hickey (2011)