题目要求:
根据上排给出的十个数,在其下排填出对应的十个数。
要求下排每个数都是先前上排那十个数在下排出现的次数。
例如:上排:0,1,2,3,4,5,6,7,8,9
下排:6,2,1,0,0,0,1,0,0,0
0在下排出现了6次,1在下排出现了2次,2在下排出现了1次,3在下排出现了0次...以此类推
题目分析:
先初始化下排的十个数都为0,然后根据上排逐渐更新下排的值,直到上排和下排数据匹配为止。
top | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | |
bottom | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 第一行 |
10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 第二行 | |
9 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 第三行 | |
8 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 第四行 | |
7 | 2 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 第五行 | |
6 | 2 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 第六行 | |
6 | 2 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 第七行 |
分析上表: bottom的第一排为初始化值,全部为0.
bottom第二排的值是根据第一排的bottom和top得来的。top中的0在第一排中有10个,则更新第二排中对应top为0的那个数为10。同理top为1-9在第一排中没有,则更新第二排中对应top为1-9的那些数为0.
......
bottom第六行的值根据top和bottom第五行的值来更新,在第五行中有6个0,则在第六行中top为0的那一列为6;在第五行中有2个1,则在第六行中top为1的那一列为2...
bottom第七行的值根据top和bottom第六行的值来更新,在第六行中有6个0,则在第七行中top为0的那一列为6;在第六行中有2个1,则在第七行中top为1的那一列为2...第六行和第七行数据相同,则更新完成。
代码:
#include <iostream>
using namespace std;
const int len = 10;
class NumberTb
{
private:
int top[10];
int bottom[10];
bool success;
public:
NumberTb();
~NumberTb(){}
int *getBottom();
void setNextBottom();
int getFrequency(int num);
};
NumberTb::NumberTb()
{
success = false;
for(int i = 0;i<len;i++)
{
top[i] = i;
bottom[i] = 0;
}
}
int *NumberTb::getBottom()
{
while(!success)
setNextBottom();
return bottom;
}
void NumberTb::setNextBottom()
{
bool reb = true;
for(int i=0;i<len;i++)
{
int fre = getFrequency(i);
if(bottom[i]!=fre)
{
bottom[i] = fre;
reb = false;
}
}
success = reb;
}
int NumberTb::getFrequency(int num)
{
int count = 0;
for(int i = 0;i<len;i++)
{
if(bottom[i]==num)
count++;
}
return count;
}
int main(void)
{
NumberTb nTb;
int *result = nTb.getBottom();
cout << "top: ";
for(int i = 0;i<len;i++)
cout << i << " ";
cout << endl;
cout << "bottom:";
for(int i=0;i<len;i++)
cout << *(result+i) << " ";
cout << endl;
return 0;
}