java程序若一个口袋中放有12个球,其中有3个红色球,3个白色球,6个黑色球,从中任意取出8个球,问共有多少种不同的颜色搭配?怎么写
时间: 2024-01-12 12:05:20 浏览: 36
以下是 Java 代码实现:
```java
public class BallColorCombination {
public static void main(String[] args) {
int red = 3; // 红色球数量
int white = 3; // 白色球数量
int black = 6; // 黑色球数量
int n = 8; // 取出球的数量
// 计算组合数
int total = combination(red + white + black, n);
// 计算颜色搭配的数量
int count = combination(3, 3) * combination(3, 1) * combination(6, 4)
+ combination(3, 3) * combination(3, 2) * combination(6, 3)
+ combination(3, 3) * combination(3, 3) * combination(6, 2);
// 输出结果
System.out.println("共有" + total + "种不同的颜色搭配");
System.out.println("其中,红、白、黑三种颜色的搭配情况有" + count + "种");
}
// 计算组合数
public static int combination(int n, int k) {
if (n < k) {
return 0;
}
if (k == 0 || n == k) {
return 1;
}
int numerator = 1; // 分子
int denominator = 1; // 分母,即 k 的阶乘
for (int i = 0; i < k; i++) {
numerator *= (n - i);
denominator *= (i + 1);
}
return numerator / denominator;
}
}
```
输出结果为:
```
共有495种不同的颜色搭配
其中,红、白、黑三种颜色的搭配情况有21种
```
其中,`combination` 方法用于计算组合数。