iT邦幫忙

2022 iThome 鐵人賽

DAY 26
0
Modern Web

clojure 刷刷鍋系列 第 26

Clojure 肉片 -第 26 塊

  • 分享至 

  • xImage
  •  

【今日湯底】

In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number.

Examples
(high-and-low "1 2 3 4 5") ; return "5 1"
(high-and-low "1 2 -3 4 5") ; return "5 -3"
(high-and-low "1 9 3 4 -5") ; return "9 -5"
Notes
All numbers are valid Int32, no need to validate them.
There will always be at least one number in the input string.
Output string must be two numbers separated by a single space, and highest number is first.

(必須通過以下測試)

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

(deftest basic-tests
    (is (= (high-and-low "8 3 -5 42 -1 0 0 -9 4 7 4 -4") "42 -9"))
    (is (= (high-and-low "1 2 3") "3 1")))

【我的答案】

(ns kata)

(defn high-and-low [s]
    (let [sort-number-vector (->> (clojure.string/split s #" ")
                               (map #(Integer/parseInt %))
                               sort
                               vec)]
      (clojure.string/join " " (mapv sort-number-vector [(dec (count sort-number-vector)) 0])))
    )

【其他人的答案】

(ns kata)
(require '[clojure.string :as str])
(defn high-and-low [s]
  (let [xs (map #(Integer/parseInt %) (str/split s #" "))]
    (format "%d %d" (apply max xs) (apply min xs))))
(ns kata)

(defn high-and-low [s]
  (let [nums (map #(Integer/parseInt %) (clojure.string/split s #" "))]
    (str (apply max nums) " " (apply min nums))))
(ns kata)
(defn string-to-numbers [string]
  (map #(Integer/parseInt %) (clojure.string/split string #" "))
)

(defn high-and-low [input]
  (let [numbers (sort (string-to-numbers input))]
    (str (last numbers) " " (first numbers))
  )
)

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

尚未有邦友留言

立即登入留言