簡體   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