前两天看到有人要编个考试系统,当时只是简单回了下用随机函数RND
实际一般需要从数据库中随机提取N道题目。
以下代码都基于VBS;
通常的编写类似这样的
'产生不重复随机数function rndarray(istart,iend,sum)dim arrayid(),i,j,blnre,temp,iloop,eloopredim arrayid(sum-1)i=0iloop=0eloop=0blnre=falserandomizedo while i<sumtemp=int(rnd*(iend-istart+1)+istart)if i=0 thenarrayid(0)=tempi=i+1iloop=iloop+1else
for j=0 to i-1if arrayid(j)=temp thenblnre=trueiloop=iloop+1exit for'这一句很重要,防止多余的循环elseiloop=iloop+1end ifnext
if blnre=false then arrayid(i)=temp i=i+1 else blnre=false end if
end ifeloop=eloop+iloopiloop=0looprndarray=join(arrayid)&"循环次数:"&eloopend function
response.write rndarray(1,10,5)&"<br>"'调用过程
PS。其中的iloop、eloop是为了计算循环次数而已。
以上,大多数人的都是用这种方法编写的,生成一个随机数,然后再和以前生成的做比较,判断是否可用;
但这不是一种AI的,或者说有效率的方法,为什么不用两个数组呢?
数组1,存放需要的字符串,或数字等,数组2存放生成的随机数;当每次随机生成中间变量temp的一个下标x,赋给数组2,然后从数组1中,去掉下标为x的数字,赋给中间变量temp;这样每生成一个随机数,就从数组1中拿掉这个数,下次再生成一个数就不会重复了,这种产生随机数的方法原理实际是从数组1中提取。
方法二
function rndstr(istart,iend,isum)dim i,j,vntarray()redim vntarray(iend-istart)j=istartfor i=0 to iend-istartvntarray(i)=jj=j+1next
dim vntarray2(),temp,x,yredim vntarray2(isum-1)y=iend-istart+1x=0temp=vntarraydo while x<isumdim arandomizevntarray2(x)=temp(int(rnd*y))a=" "&vntarray2(x)&" "temp=split(trim(replace(chr(32)&join(temp)&chr(32),a," ")))x=x+1y=y-1looprndstr=join(vntarray2)end function
response.write rndstr(1,5,2)
这样,是不是更简单呢
展开一下,假如要生成随机字符串,包含字母数字时,仅需为数组1赋值时,用函数chr(num);
假设,需要做一个手机中奖的页面程序。
首先把值赋给数组1,可以130....~139....循环赋值,当然实际使用时从数据库中把已有的赋值,然后再随机提取赋给数组2;
最后,再修饰一下
temp=replace(join(array2),chr(32),"")phone=left(temp,6)&"***"&right(temp,2)
得到类似137648***58的结果,呵呵
写那么多,累死了~~
推荐阅读
截取实际长度字符串,并用空格替换
function cutstr(thestr,strlen)dim l,t,cl=len(thestr)t=0for dxy=1 to lc=Abs(asc(Mid(thestr,dxy,1)))if c>255 thent=t+2elset=t+1end ifif t>=strlen thenthev=left(thestr,dxy)exit forelsebu=strlen-tfor bu>>>详细阅读
本文标题:ASP生成不重复随机数字的另类思路
地址:http://www.17bianji.com/kaifa2/ASP/33326.html
1/2 1