gpt4 book ai didi

ruby - 你如何在 Ruby 中检查数组的范围?

转载 作者:数据小太阳 更新时间:2023-10-29 07:22:58 27 4
gpt4 key购买 nike

我正在编写一个扑克程序,但我不知道如何处理顺子。

顺子:5张手牌中的所有牌都是连续值。前任。 2..6、3..7、4..8、5..9、6..T、7..J、8..Q、9..K、T..A

cards = [2, 3, 4, 5, 6, 7, 8, 9, "T", "J", "Q", "K", "A"]

如何检查这些组合的手牌(数组)?最好我可以检查它是否在卡片数组中连续 5 个。

最佳答案

编辑 2:这是我绝对的最终解决方案:

require 'set'
STRAIGHTS = ['A',*2..9,'T','J','Q','K','A'].each_cons(5).map(&:to_set)
#=> [#<Set: {"A", 2, 3, 4, 5}>, #<Set: {2, 3, 4, 5, 6}>,
# ...#<Set: {9, "T", "J", "Q", "K"}>, #<Set: {"T", "J", "Q", "K", "A"}>]

def straight?(hand)
STRAIGHTS.include?(hand.to_set)
end

STRAIGHTS.include?([6,3,4,5,2].to_set)
# STRAIGHTS.include?(#<Set: {6, 3, 4, 5, 2}>)
#=> true

straight?([6,5,4,3,2]) #=> true
straight?(["T","J","Q","K","A"]) #=> true
straight?(["A","K","Q","J","T"]) #=> true
straight?([2,3,4,5,"A"]) #=> true

straight?([6,7,8,9,"J"]) #=> false
straight?(["J",7,8,9,"T"]) #=> false

编辑 1:@mudasobwa 指出 'A',2,3,4,5 是一个有效的顺子,打乱了 apple cart。我相信我已经确定了我的答案。 (我相信他不会告诉我 'K','A',2,3,4 也是有效的。)

我建议如下:

CARDS     = [2, 3, 4, 5, 6, 7, 8, 9, "T", "J", "Q", "K", "A"]
STRAIGHTS = CARDS.each_cons(5).to_a
#=>[[2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8],
# [5, 6, 7, 8, 9], [6, 7, 8, 9, "T"], [7, 8, 9, "T", "J"],
# [8, 9, "T", "J", "Q"], [9, "T", "J", "Q", "K"],
# ["T", "J", "Q", "K", "A"]]

def straight?(hand)
(hand.map {|c| CARDS.index(c)}.sort == [0,1,2,3,12]) ||
STRAIGHTS.include?(hand.sort {|a,b| CARDS.index(a) <=> CARDS.index(b)})
end

关于ruby - 你如何在 Ruby 中检查数组的范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29598289/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com