生成任意個不重複的隨機數

版權聲明:本文系做者原創。未經許可,不得轉載。ubuntu

C語言版:     
  最多支持 1024個,固然能夠在源碼中修改。不過若是更多,可能數據類型要改,int 要改成 float之類的。
生成的隨機數不重複,且每次運行不一樣。 在ubuntu9.04下gcc編譯經過。

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#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
相關文章
相關標籤/搜索