码迷,mamicode.com
首页 > 其他好文 > 详细

明明的随机数

时间:2017-10-18 10:02:01      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:span   oid   输出   style   using   输入格式   协助   好的   logs   

/p

问题描述
  明明想在学校中请一些同学一起做一项问卷调查,为了实验的客观性,他先用计算机生成了N个1到1000之间的随机整数(N≤100),对于其中重复的数字,只保留一个,把其余相同的数去掉,不同的数对应着不同的学生的学号。然后再把这些数从小到大排序,按照排好的顺序去找同学做调查。请你协助明明完成“去重”与“排序”的工作。
输入格式
  输入有2行,第1行为1个正整数,表示所生成的随机数的个数:
  N
  第2行有N个用空格隔开的正整数,为所产生的随机数。
输出格式
  输出也是2行,第1行为1个正整数M,表示不相同的随机数的个数。第2行为M个用空格隔开的正整数,为从小到大排好序的不相同的随机数。
样例输入
10
20 40 32 67 40 20 89 300 400 15
样例输出
8
15 20 32 40 67 89 300 400
 
解题思路:
      该题可以边输入随机数,边排序,并实现所有数字不重复
#include<iostream>
using namespace std;
int a[100];
int find(int x, int num)
{//查找x可以插入的位置,并返回该位置,如果
 //没找到(存在相等的数)返回-1 
   if(x > a[num-1])
       return i;
   else if(x < a[0])
       return 0;
   else
   {
       for(int j = 0; j < i-1; j++)
       {
           if(x < a[j+1] && x > a[j])
               return j+1;
       }
       return -1;
   }
}

void insert(int x, int num, int pos)
{//将该值插入到a[pos]的位置 
    for(int j = num-1; j >= pos; j--)
       a[j + 1] = a[j];
    a[pos] = x;
}
int main()
{
    int n, x, pos; 
    while(cin>>n)
    {//n为总的随机数,num记录不重复的随机数的个数,至少为1 
        int num = 1;
        for(int i = 0; i < n; i++)
        {
            cin>>x;
            if(i == 0)
                a[0] = x;
            else
            {
                pos = find(x, num);
                if(pos != -1)
                {
                    insert(x, num, pos);
                    num++;
                }  
            }
        }
        cout<<num<<endl;
        for(int i = 0; i < num; i++)
           cout<<a[i]<<" ";
        cout<<endl;
    }
}

 

 

明明的随机数

标签:span   oid   输出   style   using   输入格式   协助   好的   logs   

原文地址:http://www.cnblogs.com/denghui666/p/7684678.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!