生成任意个不重复的随机数

版权声明:本文系作者原创。未经许可,不得转载。

C语言版:     
  最多支持 1024个,当然可以在源码中修改。不过如果更多,可能数据类型要改,int 要改为 float之类的。
生成的随机数不重复,且每次运行不同。 在ubuntu9.04下gcc编译通过。

#include 
#include 
#include 
#include 

#define NUMBER 1024

int main(int argc, char *argv[])
{
        int i = 0;
        int j = 0;
        time_t t;
        int num = -1;
        int index[NUMBER];
        int num_array[NUMBER];
        int number;
        char buf[8] = {0};

        if (argc < 2) {
                printf("usage: Should entry the number of the random numbers!\n");
                return 0;
        }
        sprintf(buf, "%s", argv[1]);
        number = atoi(buf);
        if ( number > NUMBER) {
                printf("usage: Max is %d!\n", NUMBER);
                return 0;
        }
        printf("You want to get %d random numbers.\n", number);
        for (i = 0; i < number; i++) {
                index[i] = 0;
                num_array[i] = -1;
        }
again:
        srand((unsigned) time(&t));
        num = rand()%number;
        if(index[num] == 1)
                goto again;
        index[num] = 1;
        num_array[j++] = num;
        for(i = 0; i < number; i++) {
                if(index[i] == 0)
                        goto again;
        }
        printf("The random numbers from 0 to %d\n", number - 1);
        for (i = 0; i < number; i++)
                printf("%d\n", num_array[i]);
        return 0;
}

SHELL 版
#!/usr/bin/env bash
#generated_random_number_of_non-repetition
n=$1
a=($(for ((i=0;i<$n;i++));do echo "$i $RANDOM";done|sort -k2n|cut -d" " -f1))
echo ${a[*]}

运行:
./rand.sh 28
21 6 2 22 13 15 8 27 26 19 18 4 9 16 14 11 23 1 0 7 20 5 25 3 10 24 12 17

你可能感兴趣的:(生成任意个不重复的随机数)