iT邦幫忙

2025 iThome 鐵人賽

DAY 30
0
Software Development

clojure 30 days系列 第 30

clojure 30 days - day 30

  • 分享至 

  • xImage
  •  

Problem Description

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"

Note

  • keywords:
    • concat: combines two strings into a single sequence (strings are automatically treated as sequences of characters)
    • distinct: removes duplicate characters from the sequence
    • sort: sorts characters alphabetically
    • apply str: converts sequence of characters back to a string

Implementation

; 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)


上一篇
clojure 30 days - day 29
系列文
clojure 30 days30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言