有没有比这更简单的方法来计算扑克中的直线?

Rob*_*sto 5 javascript algorithm poker

我有一个算法来计算玩家的手是否在德州扑克中持有直线.它工作正常,但我想知道是否有一种更简单的方法来做它不涉及数组/字符串转换等.

这是我所拥有的简化版本.假设玩家手牌是一个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
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

这里的诀窍是OR各种套装,所以只有一个2-Ace表示.我错误地认为必须有一种更简单的方法吗?

Mik*_*rds 2

代码所做的几乎所有工作都是类型转换。如果您一开始就以位格式存储手牌(需要 > 32 位类型),您可以执行以下操作:

var mask = 2^13 - 1; // this will zero out all but the low 13 bits
var suits = (rawHand | rawHand>>13 | rawHand>>26 | rawHand>>39) & mask;
Run Code Online (Sandbox Code Playgroud)

使用单行循环的等效方法是:

var suits = [];
for(var i=0; i < 13; i++) {
   suits[i] = rawHand[i] || rawHand[i+13] || rawHand[i+26] || rawHand[i+39];
}
Run Code Online (Sandbox Code Playgroud)

这更短且更容易理解。

与按位表示法相互转换需要的代码和 CPU 时间比使用按位 OR 运算符节省的代码和 CPU 时间要多。