每个数字都应大于 0。 顺序无关紧要。例如:值可以是 25、50、25 或 25、25、50 或 50、25、25。 也许我们可以使用 Random 类并生成 3 个 int 值,每个值小于 99 且大于 0,然后将这 3 个数字相加。如果加法等于 100,则打印 3 个数字。 有没有更好的方法,还是只用上面的方法?
编辑:我正在尝试解决这个问题:https://curiosity.com/topics/can-you-solve-the-cat-fish-bird-riddle-curiosity/
我计划得到 3 个数字,它们加起来等于 100,然后我将在另一种方法中使用这 3 个数字,将第一个数字乘以 10,第二个数字乘以 3,最后一个数字乘以 0.5。如果结果加起来是 100,那么我就找到了解决方案。正确的?
编辑 2.1: 这是我想出的代码。有用!
// cat, fish, bird riddle
class RiddleOne {
private float num, a, b, c, x, y, z;
public void getBird() {
for (x = 1; x <= 100; x++) {
for (y = 1; y <= 100-x; y++) {
z = 100 - x - y;
if (checkQuantity()) {
System.out.print("\n\tThe quantity of cat, fish and bird toys purchased are " +x +", " +y +" and " +z +" respectively.");
System.out.print("\n\tThe total price of each toy is " +a +", " +b +" and " +c +" respectively.");
num = a + b + c;
System.out.print("\n\tThe total price is: " +num);
break;
}
}
}
}
public boolean checkQuantity() {
a = 10 * x;
b = 3 * y;
c = z / 2;
if (((a + b + c) == 100) && c != 0)
return true;
return false;
}
public static void main(String[] args) {
RiddleOne t = new RiddleOne();
t.getBird();
}
}
最佳答案
当顺序无关紧要时,明智的做法是让您的算法对每个解决方案只能生成特定的顺序。这样你就知道你没有重复项。例如,我将查看排序顺序。 (这意味着 a <= b <= c)
您将从生成 a 开始,因为其他 2 个必须大于或等于 a,a 必须小于 100/3,否则 b 或 c 必须小于 100/3。
然后我们知道 b 必须至少为 a,并且必须小于或等于 100 - a - b,因此也小于或等于 (100 - a)/2。
我们的算法将是这样的:
public void printAllCombinations() {
for (int a = 1; a <= 100/3; a++) {
for (int b = a; b <= (100 - a)/2; b++) {
int c = 100 - a - b;
// Report a, b and c
}
}
}
关于java - 在 Java 中获取加起来为 100 的 3 个数字的所有可能组合的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42056194/