初级系列14.三色球问题

三色球问题

问题描述

一个口袋中放有12个球,已知其中3个是红的,3个是白的,6个是黑的,现从中任取8个,问共有多少种可能的颜色搭配?

问题分析

根据问题描述可设任取的8个球中红球为m个, 白球为n个,则黑球为8-m-n个,已知12个球中有3个红球,3个白球,6个黑球,因此,m的取值范围为[0, 3] n的取值范围为[0, 3], 黑球的个数小于等于6,即8-m-n<= 6

算法设计

由问题分析可知,红,白,黑三种颜色球的个数的取值范围已经确定了,现在要求的是所有可能的颜色搭配情况,因此,可以使用循环结构检测m, n范围内的所有可能取值,再代入8-m-n<= 6中进行验证,能够满足8-m-n <= 6的那些m, n和8 -m -n的组合即为问题的解

#include <stdio.h>

int main(void)
{
    int m, n, number = 0;
    printf("红球  白球  黑球
");
    printf("...............
");
    for (m = 0; m <= 3; m++) {  /* !<变量m控制红球的个数 */
        for (n = 0; n <= 3; n++) {  /* !<变量n控制白球的个数 */
            if (8 - m - n <= 6) {
                printf("%2d     %d  %d  %d
", ++number, m, n, 8-m-n);
            }
        }

    }
}

 /* !<output */
	红球  白球  黑球
    ...............
    1     0  2  6
    2     0  3  5
    3     1  1  6
    4     1  2  5
    5     1  3  4
    6     2  0  6
    7     2  1  5
    8     2  2  4
    9     2  3  3
    10     3  0  5
    11     3  1  4
    12     3  2  3
    13     3  3  2

    Process returned 0 (0x0)   execution time : 0.032 s
    Press any key to continue.


原文地址:https://www.cnblogs.com/xzpin/p/11484609.html