如何比较两个输入列表的元素?

时间:2014-10-16 02:10:36

标签: clojure

我们必须开发一款扑克游戏。我已经开发了所有必需的功能,但我坚持一个。它是:(更高的踢球者?kicker1 kicker2)比较两个踢球者中的相应值,如果第一个踢球者具有较大的第一个差值,则返回true,如果第二个踢球者具有较大值,则返回false,或者如果列表成对相等则返回。例如:(更高的踢球者?'(8 5 9)'(8 7 3))应该返回false,因为8 == 8但是7> 5。假设两个踢球者名单长度相等。

我能做的就是比较两只手,比如:

(defn compare-cards [[v1 s1] [v2 s2]]
  (if (= v1 v2)
    (compare (suit-value s1) (suit-value s2))
    (compare v1 v2)))

(defn sort-cards [cards]
  (sort compare-cards cards))

(defn parse-hand [s]
  (sort-cards (mapv parse-card (.split s " "))))

(def foo [[:straight straight?] [:high-card high-card?]])

(defn categorize-hand [hand]
  (some #(% (parse-hand hand)) (map second foo)))

(defmulti tie-break (fn [h _] (categorize-hand h)))

(defmethod tie-break :high-card [h1 h2]
  (drop-while zero? (map compare-cards (reverse h1) (reverse h2))))

(defmethod tie-break :straight [[f1 & _] [f2 & _]]
  (compare-cards f1 f2))

(defn compare-hands [hand1 hand2]
  (let [category1-value (.indexOf (map first foo) (categorize-hand hand1))
        category2-value (.indexOf (map first foo) (categorize-hand hand2))]
    (if (= category1-value category2-value)
      (tie-break (parse-hand hand1) (parse-hand hand2))
      (compare category1-value category2-value))))

但是,在逐个比较面值时,我会陷入困境,看看第一个是否更大。任何人都可以帮助我吗?

就像我在做:

(defn higher-kicker? [
card-ranks-1 card-ranks-2] 
(->> (map compare card-ranks-1 card-ranks-2) 
(filter #(not (zero? %)))

然后该怎么做?

1 个答案:

答案 0 :(得分:0)

奇怪的是,我找不到一个从两个列表中创建对的列表的函数,所以我自己滚动了。请注意zipmap,因为它不保留排序。那之后就说了一切都很简单。得到第一个不相等的对。如果没有任何列表相等,则返回false,否则比较它们,如果第一个大于第二个则返回。

(defn make-pairs [list1 list2] (partition 2 (interleave list1 list2)))

(defn pair-not= [[item1 item2]] (not (= item1 item2)))

(defn unequal-pairs [list1 list2] (filter pair-not= (make-pairs list1 list2)))

(defn higher-kicker? [kicker1 kicker2]
  (let [unequal-pair (first (unequal-pairs kicker1 kicker2))]
  (if unequal-pair
    (> (first unequal-pair) (second unequal-pair))
    false)))