gpt4 book ai didi

Java 程序查找一副牌中四张牌的组合数等于 24

转载 作者:太空宇宙 更新时间:2023-11-04 12:09:58 25 4
gpt4 key购买 nike

我有一个 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;
}

这假设您的牌组升序顺序排序,例如

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

关于Java 程序查找一副牌中四张牌的组合数等于 24,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39939676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com