iT邦幫忙

2022 iThome 鐵人賽

DAY 21
0
Modern Web

clojure 刷刷鍋系列 第 21

Clojure 肉片 -第 21 塊

  • 分享至 

  • xImage
  •  

【今日湯底】

Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_').

Examples:

  • 'abc' => ['ab', 'c_']
  • 'abcdef' => ['ab', 'cd', 'ef']

(必須通過以下測試)

(ns split-str.test
  (:require [clojure.test :refer :all]
            [split-str.core :refer :all]))
            
(def ^:private sample-tests
  [{:tested-str "cdabefg"
    :result ["cd" "ab" "ef" "g_"]}
   {:tested-str "cdabefgh"
    :result ["cd" "ab" "ef" "gh"]}
   {:tested-str "abcd"
    :result ["ab" "cd"]}])
    
(doseq [{:keys [tested-str result]} sample-tests]
  (eval
    `(deftest ~(symbol (str "sample-test-" tested-str))
      (is (~'= ~result (~'solution ~tested-str))))))

【我的答案】

(ns split-str.core)

(defn solution
  [s]
  (->>
    (partition 2 2 ["_"] s)
    (map #(clojure.string/join "" (vec %))))
)

【其他人的答案】

(ns split-str.core)


(defn solution
  [s]
(map clojure.string/join (partition 2 2 "_" s)))
(ns split-str.core)

(defn solution
  [s]
  (map #(apply str %) (partition 2 2 "_" s)))

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

尚未有邦友留言

立即登入留言