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

这是我所拥有的简化版本。假设玩家获得了一张由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对A表示。我认为必须有一种更简单的方法来做错吗?

最佳答案

您的代码几乎完成的所有工作都是类型转换。如果您只是将手存储为位格式(需要> 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;

使用单行循环的等效项是:
var suits = [];
for(var i=0; i < 13; i++) {
   suits[i] = rawHand[i] || rawHand[i+13] || rawHand[i+26] || rawHand[i+39];
}

这要短得多并且更容易理解。

与使用位或运算符节省的代码和CPU时间相比,按位表示进行转换要花费更多的代码和CPU时间。

关于javascript - 有比这更简单的方法来计算扑克中的顺子吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4004856/

10-10 04:58