• 🏆 Texturing Contest #33 is OPEN! Contestants must re-texture a SD unit model found in-game (Warcraft 3 Classic), recreating the unit into a peaceful NPC version. 🔗Click here to enter!
  • It's time for the first HD Modeling Contest of 2024. Join the theme discussion for Hive's HD Modeling Contest #6! Click here to post your idea!

Choosing between a positive and negative number

Status
Not open for further replies.
Level 23
Joined
Oct 12, 2008
Messages
1,783
Quick question, Im trying to randomize a fixed number to either be positive or negative.
(eg. Roll either +30 or -30, which is not the same as range from -30 to +30).

- Cant use 30*(-1 to 1) as it can roll 0.
- Is there a way to do this that does not involve (if then else) conditions?
 
Level 38
Joined
Feb 27, 2007
Messages
4,951
30*((Random Int 0,1)-0.5)*2

But I’m not sure that’s more clear. You could write a custom function and just call it:
JASS:
function RandSpread takes real val returns real
  return val*(GetRandomInt(0,1)-0.5)*2
endfunction

//for example
set udg_SomeVar = RandSpread(30.)
 
One also could fill an array with possible results and then roll an index. Then one reads the array's value from the rolled index.
JASS:
Int[0] = 30
Int[1] = -30

set value = Int[GetRandomInt(0,1)]


If you just don't want to write the "if then else" in your code, there is a function in Blizzard.j that returns one of two values based on the given boolean.

JASS:
function IntegerTertiaryOp takes boolean flag, integer valueA, integer valueB returns integer
    if flag then
        return valueA
    else
        return valueB
    endif
endfunction

set value = IntegerTertiaryOp(GetRandomInt(0,1) == 0, 30, -30)
 

Dr Super Good

Spell Reviewer
Level 63
Joined
Jan 18, 2005
Messages
27,178
Roll two numbers. Your random number and a random integer between 0 and 1 inclusive which one can call random sign. Use a global constant array which one can call sign map to map the random sign to either -1 or 1. Multiply your random number by the value of sign map contained at random sign.

This is likely the most efficient implementation in JASS.
 
Status
Not open for further replies.
Top