繁体   English   中英

Java程序,用于查找甲板中四张卡等于24的组合数

[英]Java program to find the number of combinations that four cards in a deck will equal 24

我有一个Java程序,将需要一副卡片,并计算四张卡的组合数量将等于24.到目前为止,我有这个:

public class Assign5b {
    public static void main(String[] args) {
        int[] deck = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 
            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 
            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 
            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};

        int total;
        total = calculate(deck);
        output(total);
    }

    public static int calculate(int[] deck) {
        int total = 0;
        int stack1, stack2, stack3, stack4, accumulate;

        for (stack1 = 0; stack1 < 52; stack1++) {
            for (stack2 = (stack1 + 1); stack2 < 52; stack2++) {
                for (stack3 = (stack2 + 1); stack3 < 52; stack3++) {
                    for (stack4 = (stack3 + 1); stack4 < 52; stack4++) {
                        accumulate = (deck[stack1] + deck[stack2] + deck[stack3] + deck[stack4]);
                        if (accumulate == 24)
                            total++;
                    }
                }
            }
        }       
        return total;
    }   

    public static void output(int total){
        System.out.println ("The total number of card combinations of 4 that \n" + "equal 24 is: " + total);
    }
}

所以我的问题不是它没有运行,或者它没有显示正确的值,而是那些嵌套的循环。 我不希望他们在那里。 它使它运行效率非常低,我知道有更好的方法让它运行我只是无法想象它。

您可以在每个循环的开头添加检查,以查看运行总计是否已超过24.在这种情况下,无论如何都没有必要执行这些循环:

public static int calculate(int[] deck, int target) {
    int total = 0;
    int stack1, stack2, stack3, stack4, accumulate;

    for (stack1 = 0; stack1 < 52; stack1++) {
        if (deck[stack1] > target) break;

        for (stack2 = (stack1 + 1); stack2 < 52; stack2++) {
            if (deck[stack1] + deck[stack2] > target) break;

            for (stack3 = (stack2 + 1); stack3 < 52; stack3++) {
                if (deck[stack1] + deck[stack2] + deck[stack3] > target) break;

                for (stack4 = (stack3 + 1); stack4 < 52; stack4++) {
                    if (deck[stack1] + deck[stack2] + deck[stack3] + deck[stack4] > target) break;
                    accumulate = (deck[stack1] + deck[stack2] + deck[stack3] + deck[stack4]);
                    if (accumulate == 24)
                        total++;
                }
            }
        }
    }

    return total;
}

这假定您的deck升序排序,例如

int[] deck = {1, 1, 1, 1,
              2, 2, 2, 2,
              ...
              13, 13, 13, 13};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM