课堂练习找水王02

设计思想:有一组数据,从第一个开始读取,放入一个3个元素的数组b,(同时有另一个记录相同的个数的数组c)。每输出一次就判断,b是否有相同的元素,如果有就在c的对应位置加1,如果没有相同元素但有空的,把元素放到b空的位置,否则c数组全部减一。

#include<iostream>
#include<string>
using namespace std;
void  main()
{
    string a[100];
    string b[3];
    int num[3] = {0,0,0};
    
    for (int i = 0; i < 30; i++)
    {
        a[i] = 'a';
    }
    for (int i = 30; i < 60; i++)
    {
        a[i] = 'b';
    }
    for (int i = 60; i < 70; i++)
    {
        a[i] = 'c';
    }
    for (int i = 70; i < 100; i++)
    {
        a[i] = 'd';
    }
    for (int i = 0; i < 100; i++)//将数组输出
    {
        if (a[i] == b[0])
        {
            num[0] = num[0] + 1;
        }
        else if (a[i] == b[1])
        {
            num[1] = num[1] + 1;
        }
        else if (a[i] == b[2])
        {
            num[2] = num[2] + 1;
        }
        else if (num[0] != 0 && num[1] != 0 && num[2] != 0)
        {
            num[0]--;
            num[1]--;
            num[2]--;
        }
        else
        {
            for (int j = 0; j < 3; j++)//如果有空的,赋值给空的
            {
                if (num[j] == 0)
                {
                    b[j] = a[i];
                    num[j]++;
                    break;
                }
            }    
        }    
    }
    cout << "水王是";
    for (int i = 0; i < 3; i++)
    {
        cout << b[i] << endl;
    }
}

截图:

30个a,30个b,10个c,30个d。

j

心得:

在上次的基础上,把三个数看成一组,进行统计相消。

原文地址:https://www.cnblogs.com/zuhaoran/p/5535369.html