产生不重复的随机数

来源:互联网 发布:青年网络公开课金灿荣 编辑:程序博客网 时间:2024/04/29 10:50

由于flash游戏中要产生1~N的N个不重复随机数,个人想法有三个

1.按顺序产生1~N,通过某种方法随机打乱,通过随机交换达到

2.随机产生10*N个数,按顺序合并重复的,直到找到N个。

3.产生随机数之后存到数组,每产生一个随机数,判断是否重复,如果重复再产生一次,如果不重复,就产生下一个数

下面是对第3个方法的实现

C语言实现

#include <stdio.h>#include <stdlib.h>#include <time.h>#define N 9  //定义常量/*srand()设置随机数种子(随机盐)  time(0)和time(NULL)返回系统时间秒数,需要导入time.h  C语言产生的随机数范围0~RAND_MAX*/int main(){    int a[N];//定义一个数组,下标a[0]~a[N-1]    int n=0;    int i=0,j=0;    int temp;    a[0]=rand()%N+1;    for(i=0;i<N;i++){        temp=rand()%N+1;        for(j=0;j<i;j++){ //判断重复           if(temp==a[j]){i--;break;}else{a[i]=temp;}        }    }    //打印    for(i=0;i<N;i++){        printf("%d ",a[i]);    }    printf("\n");    return 0;}
结果

6 8 5 9 2 4 1 3 7Process returned 0 (0x0)   execution time : 0.436 sPress any key to continue.

Flash AS3脚本实现

//在AS3中Math.random()的范围是0.000~0.999//产生1~n的n个不重复的随机数function randomArray(dim:int):Array {var ar:Array=new Array(dim);ar[0]=Math.floor(Math.random()*dim+1);for(var i=1;i<dim;i++){var temp=Math.floor(Math.random()*dim+1);//判断是否重复for(var j=0;j<i;j++){if(temp==ar[j]){i--;break;}else{ar[i]=temp;}}}return ar;}//输出trace(randomArray(9));

结果

8,5,3,1,4,2,6,7,9





0 0