KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: A wrapper for Random with added functionality
PRODUCT: 4D | VERSION: 11.4 | PLATFORM: Mac & Win
Published On: August 20, 2009

There are times when a developer feels the need for a routine that goes a step or two beyond that what is provided by a native 4D command. Below is a just such a routine. A super wrapper for the 4D's Random command that makes getting a random number within a min and max range very easy.

The following method, "UTIL_Random", can be used to get a random integer in the range passed as parameters. Pass two integer values and a random integer between them will be returned. If the integers are the same number, then a random number from zero to MAXINT will instead be returned.

`UTIL_Random ($Min_L;$Max_L) -> LONGINT

C_LONGINT($0;$Rand_L)
C_LONGINT($Min_L;$1)
C_LONGINT($Max_L;$2)
`--------------------------------------------------------------------------------
C_BOOLEAN(◊RandomWarmed_b)
`--------------------------------------------------------------------------------
C_LONGINT($Ndx;$Jdx;$Kdx;$SOA;$RIS)

`====================== Initialize and Setup ================================

$Min_L:=$1
$Max_L:=$2

`// For speed purposes this is only done once
If (Not(◊RandomWarmed_b))
    $RIS:=(Milliseconds%(32768-10+1))+10
    For ($Ndx;1;$RIS)
        $SOA:=Random
    End for
End if

`======================== Method Actions ==================================

If ($Max_L<$Min_L)
    $Ndx:=$Max_L
    $Max_L:=$Min_L
    $Min_L:=$Ndx
End if

If ($Max_L>MAXINT )
    $Max_L:=MAXINT
End if

If ($Min_L=$Max_L)
    $Jdx:=0
    $Kdx:=MAXINT -1
    $Ndx:=$Kdx-$Jdx
    $Rand_L:=$Jdx+(Int(((Random/32768)*$Ndx)+1))
    $Rand_L:=$Rand_L/MAXINT

Else
    $Jdx:=$Min_L-1
    If ($Max_L=MAXINT )
        $Max_L:=$Max_L-1
    End if
    $Kdx:=$Max_L
    $Ndx:=$Kdx-$Jdx
    $Rand_L:=$Jdx+(Int(((Random/32768)*$Ndx)+1))

End if

`======================== Clean up and Exit =================================

$0:=$Rand_L


To get a random number between the inclusive numbers 128 and 256 simply call UTIL_Random (128;256).

Commented by Ben Kershaw on February 9, 2011 at 11:57 AM
The code is missing the "◊RandomWarmed_b:=True" after warming the Random function.