iT邦幫忙

2022 iThome 鐵人賽

DAY 27
0
Modern Web

clojure 刷刷鍋系列 第 27

Clojure 肉片 -第 27 塊

  • 分享至 

  • xImage
  •  

【今日湯底】

Create a function that returns the name of the winner in a fight between two fighters.

Each fighter takes turns attacking the other and whoever kills the other first is victorious. Death is defined as having health <= 0.

Each fighter will be a Fighter object/instance. See the Fighter class below in your chosen language.

Both health and damagePerAttack (damage_per_attack for python) will be integers larger than 0. You can mutate the Fighter objects.

Your function also receives a third argument, a string, with the name of the fighter that attacks first.

Example:
declare_winner(Fighter("Lew", 10, 2), Fighter("Harry", 5, 4), "Lew") => "Lew"

Lew attacks Harry; Harry now has 3 health.
Harry attacks Lew; Lew now has 6 health.
Lew attacks Harry; Harry now has 1 health.
Harry attacks Lew; Lew now has 2 health.
Lew attacks Harry: Harry now has -1 health and is dead. Lew wins.
Technical note: The second fighter argument (f2) always attacks first.

(defrecord Fighter [name hp attack])

(必須通過以下測試)

(ns clojure.two-fighters-test
  (:require [clojure.test :refer :all]
            [clojure.two-fighters-preloaded :refer [->Fighter]]
            [clojure.two-fighters :refer :all]))

(deftest simple-test
  (is (= "Harald" (declare-winner (->Fighter "Harald" 20 5) (->Fighter "Harry" 5 4))))
  (is (= "Harald" (declare-winner (->Fighter "Harald" 20 5) (->Fighter "Jerry" 30 3)))))

【我的答案】

(ns clojure.two-fighters
  (:require [clojure.two-fighters-preloaded :refer [->Fighter]]))

(defn declare-winner [f1 f2]
  (let [f1-survive (Math/ceil (/ (:hp f1) (:attack f2)))
        f2-survive (Math/ceil (/ (:hp f2) (:attack f1)))]
    (prn (:name f1) f1-survive (:name f2) f2-survive)
    (if (>= f2-survive f1-survive)
      (:name f2)
      (:name f1)))
  )

【其他人的答案】

(ns clojure.two-fighters)

(defn declare-winner [f1 f2]
  (cond 
    (<= (:hp f1) 0) (:name f2)
    (<= (:hp f2) 0) (:name f1)
    :else 
      (recur 
        (update f1 :hp - (:attack f2)) 
        (update f2 :hp - (:attack f1)))))

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

尚未有邦友留言

立即登入留言