iT邦幫忙

2022 iThome 鐵人賽

DAY 17
0
Modern Web

clojure 刷刷鍋系列 第 17

Clojure 肉片 -第 17 塊

  • 分享至 

  • xImage
  •  

【今日湯底】

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'

(必須通過以下測試)

(ns kata.test
  (:require [clojure.test :refer :all]
            [kata         :refer [switcheroo]]))

(deftest basic-tests
  (is (= (switcheroo "abc") "bac"))
  (is (= (switcheroo "aaabcccbaaa") "bbbacccabbb"))
  (is (= (switcheroo "ccccc") "ccccc"))
  (is (= (switcheroo "abababababababab")  "babababababababa"))
  (is (= (switcheroo "aaaaa") "bbbbb")))

【我的答案】

(ns kata)
(defn switcheroo [xs]
  (->
    (.replaceAll xs "a" "d")
    (.replaceAll "b" "a")
    (.replaceAll "d" "b"))
  )

思路:

  1. 拿目前用過的 java replace 來處理

【其他人的答案】

(ns kata)
(defn switcheroo [xs]
  (clojure.string/replace xs #"a|b" {"a" "b" "b" "a"})
  )
(ns kata)

(defn- switch [c]
  (cond
    (= \a c) \b
    (= \b c) \a
    :else c))

(defn switcheroo [xs]
  (->> (seq xs)
       (map switch)
       (apply str))
  )

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

尚未有邦友留言

立即登入留言