HomeUser Control Panel (unavailable in archive)ForumsTutorialsArt GalleryResourcesMaps

WaningRandom()

02-10-2010, 11:02 PM#1
Feroc1ty
Collapse JASS:
function WaningRandom takes integer lowbound, integer highbound returns integer
    local real diff = highbound - lowbound
    local real low = Pow(diff, 0.2)
    local integer i = lowbound
    local boolean exit = false
    loop
        exitwhen exit == true
        if GetRandomReal( 0.00, diff ) > low then
            if i == highbound then
                set exit = true
            else
                set i = i + 1
            endif
        else
            set exit = true
        endif
    endloop
    return i
endfunction

Okay, so that's the code for my current waning random function (a random between lowbound and highbound, but a higher chance of getting lowbound, with the chance decreasing as the number gets near highbound), and I was wondering if there was a more efficient way of doing this.


My interest in Wc3 editing is alive again, might not last, but while it does... I'll be posting here more often.
02-11-2010, 12:53 AM#2
Anitarf
What do you need this function for?
02-11-2010, 01:14 AM#3
grim001
You haven't defined how much the chance should decrease as the number approaches the highbound. Also, you probably shouldn't need a function like this in the first place. It would make more sense to apply a lower probability to less likely results.
02-14-2010, 09:18 AM#4
Themerion
A more common approach to weighted random is to use multiple random values...

Collapse JASS:
function WaningRandom takes integer low, integer high returns integer

    local integer random1 = GetRandomInt(0,high-low)
    local integer random2 = GetRandomInt(0,high-low)

// Has the lagest probability at 0, least at -(high-low) and (high-low)
    local integer random = random1 - random2

// Move negative numbers to the positive side.
    if random < 0 then
        set random = random*(-1)
    endif

    return low + random

endfunction
02-14-2010, 09:54 AM#5
Iron_Doors
Here's one way to do it:
Collapse JASS:
function WaningRandom takes integer low, integer high returns real

    // Get a random value in [0, 1].
    real x = GetRandomReal(0.0, 1.0)
    
    // Process the value through a non-linear function,
    // for which f(0) = 0 and f(1) = 1.
    set x = Pow(x, 1.5)
    
    // Scale the result to the requested range.
    return low + I2S(x * (high - low) + 0.5)
endfunction
where the 1.5 determines how weighted the result is. 1 would be linear and anything above would give a lower chance for higher values, and vice versa.