[ZILF] Random Number Generation

So, this is really not important. I know RANDOM exists, which spits out a number from 1-N, but I wanted to know how to generate an arbitrary range. Here’s the routine I made, is there any better ways, more efficient ways, whatever, to do this?

<ROUTINE RANDINT (MIN MAX "AUX" MIN-P NUM)
 <SET MIN-P <- .MIN 1>> 

  <REPEAT (N)
    <SET N <+ .MIN-P <RANDOM .MAX>>

    <COND (<AND <G=? .N .MIN> <L=? .N .MAX>>
           <SET NUM .N>
           <RETURN>)>>

  <RETURN .NUM>>

From the little testing I’ve done this certainly does seem to work. Anyone have any suggestions or improvements?

This is a little more compact:

<ROUTINE RANDINT (MIN MAX) <RETURN <+ <- .MIN 1> <RANDOM <- <+ .MAX 1> .MIN>>>>>

2 Likes

WOW! That is a wonderful bit of wizardry! I had been rackin’ my head trying to figure out how to do it without a loop, excellent stuff. Thanks so much!