我有一个算法可以计算德州扑克中玩家手牌是否为顺子。它能正常工作,但我想知道是否有更简单的方法,不需要涉及数组/字符串转换等操作。
这是我拥有的算法的简化版本。假设玩家获得了一手由52个元素组成的牌值数组:
这里的技巧是将各种花色进行或运算,使其只有一个从2到Ace的表示。我是否错误地认为还有更简单的方法来做到这一点?
这是我拥有的算法的简化版本。假设玩家获得了一手由52个元素组成的牌值数组:
var rawHand = [1,0,0,0,0,0,0,0,0,0,0,0,0, //clubs
0,0,0,0,0,0,0,0,0,0,0,0,0, //diamonds
0,1,1,0,1,0,0,0,0,0,0,0,0, //hearts
0,0,0,1,0,0,0,0,1,0,0,0,0];//spades
1代表该值槽中的一张牌。上面的手牌有一张2梅花,没有方块,一张3红心,一张4红心和一张6红心,一张5黑桃和一张10黑桃。现在我看它是否为顺子。
var suits = []; //array to hold representations of each suit
for (var i=0; i<4; i++) {
var index = i*13;
// commenting this line as I removed the rest of its use to simplifyy example
//var hasAce = (rawHand[i+13]);
//get a "suited" slice of the rawHand, convert it to a string representation
//of a binary number, then parse the result as an integer and assign it to
//an element of the "suits" array
suits[i] = parseInt(rawHand.slice(index,index+13).join(""),2);
}
// OR the suits
var result = suits[0] | suits[1] | suits[2] | suits[3];
// Store the result in a string for later iteration to determine
// whether straight exists and return the top value of that straight
// if it exists; we will need to determine if there is an ace in the hand
// for purposes of reporting a "low ace" straight (i.e., a "wheel"),
// but that is left out in this example
var resultString = result.toString(2);
//Show the result for the purposes of this example
alert("Result: " + resultString);
这里的技巧是将各种花色进行或运算,使其只有一个从2到Ace的表示。我是否错误地认为还有更简单的方法来做到这一点?
for(var i=3;i--;){...}
可以使其更快。 - vol7ron