View Full Version : Random number set
Adam - FMM
05-09-06, 08:21 PM
I need to generate a set of 5 random numbers, none of them can be higher then 9 and they must all be different from each other (no repeats).
1 2 4 6 8 is ok
1 2 2 6 8 is not
I've been fiddling with the random(x) function inside while loop(s) but I'm missing a step I think.
aGorilla
05-09-06, 08:59 PM
This will give you a comma delimited string. You can convert it to an array with miva_array_deserialize, or run through it using gettoken.
<MvEVAL EXPR="{random19()}">
<MvFUNCTION NAME="random19" STANDARDOUTPUTLEVEL="">
<MvASSIGN NAME="l.random" VALUE="">
<MvWHILE EXPR="{len(l.random) LT 10}">
<MvCOMMENT> this gives you 1-9, if you want 0-9, just use random(9) </MvCOMMENT>
<MvASSIGN NAME="l.rand" VALUE="{random(8) + 1}">
<MvIF EXPR="{NOT (l.rand IN l.random)}">
<MvASSIGN NAME="l.random" VALUE="{l.random $ ',' $ l.rand}">
</MvIF>
</MvWHILE>
<MvCOMMENT> strip off first comma. </MvCOMMENT>
<MvFUNCTIONRETURN VALUE="{substring(l.random, 2, 9)}">
</MvFUNCTION>
Example output:
9,7,2,3,6
1,9,2,3,8
1,3,9,7,5
4,5,3,1,6
4,2,7,8,5
7,2,6,8,3
4,7,5,8,6
Adam - FMM
05-09-06, 09:35 PM
I like that. Thanks.
truXoft
05-10-06, 04:38 PM
You can do it little bit simpler and shorter in this way:
<MvFUNCTION NAME="randArr" PARAMETERS="size">
<MvWHILE EXPR="{miva_array_elements(l.array) LT l.size}">
<MvASSIGN NAME="l.tmp" VALUE="{random(8)+1}">
<MvASSIGN NAME="l.array" INDEX="{l.tmp}" VALUE="{l.tmp}">
</MvWHILE>
<MvFUNCRETURN VALUE="{l.array}">
</MvFUNCTION>
Sample output:
1,2,5,6,9
2,3,4,6,8
1,2,3,5,9
1,2,3,4,5
1,3,4,6,8
1,2,3,7,8
1,2,6,8,9
3,4,5,6,7
You would call it with <MvEVAL EXPR="{randArr(5)}">. Additionally, as you can see, the output is already sorted like in your examples, and unlike in the other function, though if you prefer it unsorted it would be possible too with a similar method.
vBulletin® v3.7.4, Copyright ©2000-2008, Jelsoft Enterprises Ltd.