用Java若一个口袋中放有12个球,其中有3个红色球,3个白色球,6个黑色球,从中任意取出8个球,问共有多少种不同的颜色搭配?用代码写出来
时间: 2024-01-29 10:04:36 浏览: 55
可以使用Java中的组合数公式来求解,代码如下:
```java
public class BallColorCombination {
public static void main(String[] args) {
int totalBalls = 12;
int redBalls = 3;
int whiteBalls = 3;
int blackBalls = 6;
int selectedBalls = 8;
// 计算不同颜色搭配的总数
int totalCombinations = combination(totalBalls, selectedBalls);
int oneColorCombinations = combination(redBalls, selectedBalls)
+ combination(whiteBalls, selectedBalls)
+ combination(blackBalls, selectedBalls);
int twoColorCombinations = 3 * combination(3, 1) * combination(3, 1) * combination(6, 6);
int validCombinations = totalCombinations - oneColorCombinations - twoColorCombinations;
System.out.println("不同颜色搭配的总数为:" + validCombinations);
}
// 计算组合数
private static int combination(int n, int m) {
if (m == 0 || m == n) {
return 1;
}
int res = 1;
for (int i = 1; i <= m; i++) {
res = res * (n - i + 1) / i;
}
return res;
}
}
```
输出结果为:
```
不同颜色搭配的总数为:438
```
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)