Two days ago, I saw someone wanted to compile an exam system. At that time, I just briefly used the random function RND.
In practice, it is generally necessary to randomly extract N questions from the database.
The following codes are all based on VBS;
Usually written like this
'Generate non-repeating random numbers function rndarray(istart,iend,sum) dim arrayid(),i,j,blnre,temp,iloop,eloop redim arrayid(sum-1) i=0 iloop=0 eloop=0 blnre=false randomize do while i<sum temp=int(rnd*(iend-istart+1)+istart) if i=0 then arrayid(0)=temp i=i+1 iloop=iloop+1 else for j=0 to i-1 if arrayid(j)=temp then blnre=true iloop=iloop+1 The sentence "exit for'" is very important to prevent redundant loops. else iloop=iloop+1 end if next if blnre=false then arrayid(i)=temp i=i+1 else blnre=false end if end if eloop=eloop+iloop iloop=0 loop rndarray=join(arrayid)&number of loops:&eloop end function response.write rndarray(1,10,5)&<br>'Calling process |
PS. The iloop and eloop are just for calculating the number of loops.
Above, most people use this method to write, generate a random number, and then compare it with the previously generated one to determine whether it is usable;
But this is not an AI or efficient method. Why not use two arrays?
Array 1 stores the required strings, numbers, etc., and array 2 stores the generated random numbers; when a subscript x of the intermediate variable temp is randomly generated each time, it is assigned to array 2, and then the subscript is removed from array 1 as The number of Extracted from array 1.
Method two
function rndstr(istart,iend,isum) dim i,j,vntarray() redim vntarray(iend-istart) j=istart for i=0 to iend-istart vntarray(i)=j j=j+1 next dim vntarray2(),temp,x,y redim vntarray2(isum-1) y=iend-istart+1 x=0 temp=vntarray do while x<isum dim a randomize vntarray2(x)=temp(int(rnd*y)) a= &vntarray2(x)& temp=split(trim(replace(chr(32)&join(temp)&chr(32),a, ))) x=x+1 y=y-1 loop rndstr=join(vntarray2) end function response.write rndstr(1,5,2) |
Wouldn't it be simpler this way?
To expand a bit, if you want to generate a random string containing letters and numbers, you only need to assign a value to array 1, and use the function chr(num);
Suppose you need to make a mobile lottery winning page program.
First assign the value to array 1, which can be assigned cyclically from 130.... to 139.... Of course, in actual use, the existing value is assigned from the database, and then randomly extracted and assigned to array 2;
Finally, some more polish
temp=replace(join(array2),chr(32),) |
phone=left(temp,6)&***&right(temp,2)
Get results similar to 137648***58, haha
I’m exhausted from writing so much~~