iT邦幫忙

2025 iThome 鐵人賽

DAY 19
0
Software Development

clojure 30 days系列 第 19

clojure 30 days - day 17

  • 分享至 

  • xImage
  •  

Problem Description

Given a string made up of letters a, b, and/or c, switch the position of letters a and b (change a to b and vice versa). Leave any incidence of c untouched.

Example:

'acb' --> 'bca'
'aabacbaa' --> 'bbabcabb'

Note

Example walkthrough:

  1. Regex finds "a" -> function called with %="a" -> returns "b"
  2. "c" is not matched -> stays "c"
  3. Regex finds "b" -> function called with %="b" -> returns "a"
    => final result: "bca"

Implementation

; implement
(defn switch [string]
  (clojure.string/replace string #"[ab]"  ; regex matches only "a" or "b"
    #(if (= % "a")        ; the anonymous function is called for each match
       "b"                ; if the match is "a", return "b"
       "a")))             ; otherwise (must be "b"), return "a"

; test
; execute implement function
(defn tester [arg exp]
  (= (switch arg) exp))

; args & exception
(comment
  (tester "abc" "bac")
  (tester "aaabcccbaaa" "bbbacccabbb")
  (tester "ccccc" "ccccc")
  (tester "abababababababab" "babababababababa")
  (tester "aaaaa" "bbbbb"))


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

尚未有邦友留言

立即登入留言