设为首页收藏本站

Crossin的编程教室

 找回密码
 立即加入
查看: 74373|回复: 1
打印 上一主题 下一主题

【每日一坑 2】 去除重复

[复制链接]

0

主题

0

好友

79

积分

注册会员

Rank: 2

楼主
发表于 2013-12-17 00:56:08 |显示全部楼层

回帖奖励 +5

本帖最后由 xuefu 于 2013-12-17 00:59 编辑

第一次发现C标准库里还有排序的函数。。。
  1. #include <assert.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>

  4. int compare_ascending(const void* a, const void* b)
  5. {
  6.   return (*(int*)a - *(int*)b);
  7. }

  8. int main(int argc, const char *argv[])
  9. {
  10.   int a, n, m, i = 0, j = 0;
  11.   int* secret;

  12.   printf("Input n: ");
  13.   scanf("%d", &n);

  14.   assert(n > 1 || n == 1);

  15.   printf("Input m: ");
  16.   scanf("%d", &m);

  17.   if(m > 0 && !(m > n))
  18.     printf("Below is the number: \n");
  19.   else
  20.   {
  21.     printf("the number m should be greater than zero and not larger than n.\n");
  22.     exit(0);
  23.   }

  24.   secret = malloc(sizeof(int) * m);
  25.   srand(time(NULL));

  26.   while(m--)
  27.   {
  28.     /* generate the number you want */
  29.     while(1)
  30.     {
  31.       a = rand() % n + 1;
  32.       /* check a whether is repeated */
  33.       for(j = 0; j < i; j++)
  34.       {
  35.         if(a == secret[j])
  36.         {
  37.           a = 0;
  38.           break;
  39.         }
  40.       }
  41.       if(a != 0)
  42.         break;
  43.     }
  44.     secret[i++] = a;
  45.   }

  46.   qsort(secret, i, sizeof(int), compare_ascending);

  47.   for (j = 0; j < i; j++)
  48.     printf("%d ", secret[j]);

  49.   printf("\n");
  50.   free(secret);

  51.   return 0;
  52. }
复制代码
回复

使用道具 举报

0

主题

0

好友

79

积分

注册会员

Rank: 2

沙发
发表于 2013-12-18 00:08:20 |显示全部楼层
阿聪 发表于 2015-2-6 22:42
xuefu帮忙看看呗,好像不是很高效 。。先排序后去重,m、n设为10,懒得接受输入。

...

排序里加入去掉重复的。。。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即加入

QQ|手机版|Archiver|Crossin的编程教室 ( 苏ICP备15063769号  

GMT+8, 2024-5-7 05:37 , Processed in 0.019116 second(s), 23 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部