在 5 张牌游戏中找出四张相同的牌

Finding four of a kind in a 5 card game

我正试图在 5 手牌中找到四个相同的牌。我不知道哪里出错了,但是 JUnit 报告错误。

public boolean hasFourOfaKind(String hand) {
    int counter = 0;
    char x = 0;

    for (int i = 0; i < hand.length(); i++) {
        for (int j = 0; j < hand.length(); j++) {
            if (i == 0) {
                x = hand.charAt(0);
                counter++;
            } else if (x == hand.charAt(i)) {
                counter++;

            }
        }
    }
    if (counter >= 4) {
        return true;
    } else {
        return false;
    }
}

一个真正的速成,因为你想测试你的手,假设它是一串字符,下面的代码在 javascript 中被重写,因为我也看到了问题的 JS 标签.....

function hasFourOfaKind(hand) {
    var counter = 0;
    var set_of_four = [];

    for (i = 0; i < hand.length; i++) {
        if (i == 0) {
            x = hand.charAt(0);
            set_of_four.push(x);
            counter++;
        } else {
            x = hand.charAt(i);
            if(set_of_four.indexOf(x) != '-1'){
                counter++;
            } else {
                set_of_four = set_of_four.splice(-1,1);
                set_of_four.push(x);
                counter = 0;
            }
        }
    }
    return (counter >= 3);
}

var poker_hand = 'BAAAAA';
var result = hasFourOfaKind(poker_hand);
console.log(result);

@Dmitry:感谢早前的指正……我当时太着急了……

我假设您的 hand 表示为类似 "ABCDE" 的内容。你的代码是错误的。我们来看看内部循环体:

for (int i = 0; i < hand.length(); i++) {
    for (int j = 0; j < hand.length(); j++) {
        if (i == 0) {  // take a look at this line
            x = hand.charAt(0);
            counter++;
        } else if (x == hand.charAt(i)) {
            counter++;

        }
    }
}

我已经评论了您应该查看的行。 i 在第一次外循环迭代时将始终为 0,因此您将增加计数器 hand.length() 次(这是在 i == 0 时内循环将执行的次数)。如果您的手长为 4 或更多,您的方法将始终 return true。此外,即使您修复了这部分也无济于事,因为您总是将字符与字符串的第一个字符进行比较。

作为建议,您可以从字符串中获取一个字符数组,对其进行排序,然后逐一查看有多少相同的字符:

private boolean hasFourOfaKind(String hand) {
    if (hand == null || hand.length() == 0) {
        return false;
    }
    char[] chars = hand.toCharArray();
    Arrays.sort(chars);
    char current = chars[0];
    int count = 1;
    for (int i = 1; i < chars.length; i++) {
        char next = chars[i];
        if (current != next) {
            current = next;
            count = 1;
        } else {
            count++;
            if (count == 4) {
                return true;
            }
        }
    }
    return false;
}

你的循环逻辑是错误的。它再次为同一张卡递增计数器。这就是它失败的原因。在下面提到的代码中,我只考虑了一次卡片。

public static boolean hasFourOfaKind(String hand) {
    int counter = 0;
    for (int i = 0; i < hand.length(); i++) {
        counter = 0;
        for (int j = 0; j < hand.length(); j++) {
            if (hand.charAt(j) == hand.charAt(i)) {
                counter++;
            }
        }
        if (counter >= 4) {
            return true;
        }
    }
    return false;
}