• Listen to a special audio message from Bill Roper to the Hive Workshop community (Bill is a former Vice President of Blizzard Entertainment, Producer, Designer, Musician, Voice Actor) 🔗Click here to hear his message!
  • Read Evilhog's interview with Gregory Alper, the original composer of the music for WarCraft: Orcs & Humans 🔗Click here to read the full interview.
  • The Hive's 22nd Icon Contest: Creep Abilities is now concluded, time to vote for your favourite set of icons! Click here to vote!
  • ✅ The POLL for Hive's Texturing Contest #34 is OPEN! Vote for the TOP 3 SKINS! 🔗Click here to cast your vote!
  • ✅ The POLL for Hive's Techtree Contest #20 is OPEN! Vote for the TOP 3 FACTIONS! 🔗Click here to cast your vote!

Choosing between a positive and negative number

Status
Not open for further replies.
Level 24
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?
 
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)
 
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.
Back
Top