im doing a simple code and i want the variable to be -5 or +5 but i dont understand how you can do that without the numbers in between, for exemple sometimes i get -3,4,2,-1,2 ect…
const rnd = random(1) > .5? 5 : -5;
- You want two values
- First you need to generate a random heads/tails to pick between those two values – like this:
random(1) > .5
- …then you need to convert that result into your two values.
This is what the ternary that @GoToLoop shared does – but you can also do this without the ternary operator.
- generate a random 0 or 1:
(int)random(1)
- map that to -5, 5:
map((int)random(1), -5, 5)
; - now if you give the map “0” you get -5, and if you give it “1” you get 5.
Or, you could do it like an equation:
int x = ((int)random(1) * 10 - 5
So, we get a 0 or 1, then it becomes 0 or 10, then it becomes -5 or 5.
Personally I prefer to use <
(less than) to >
(greater than) because it helps when you want one option to be more likely than the other option.
Some examples:
const rnd = random(1) < .3 ? 5 : -5; // 30% of the times you get 5, 70% you get -5
const rnd = random(1) < .5 ? 5 : -5; // both options same probability
const rnd = random(1) < .7 ? 5 : -5; // 70% of the times you get 5, 30% you get -5
or maybe more clear:
const rnd = random(100) < 30 ? 5 : -5; // 30% of the times you get 5, 70% you get -5
const rnd = random(100) < 50 ? 5 : -5; // both options same probability
const rnd = random(100) < 70 ? 5 : -5; // 70% of the times you get 5, 30% you get -5
If you use >
the percentages are inverted which may be harder to understand:
const rnd = random(100) > 30 ? 5 : -5; // 70% of the times you get 5, 30% you get -5
Update: I never thought about it like this, but maybe <
and >
can be equally easy to understand if you think that they point towards the item with the given probability. So > 30
means that the right item has 30% chances, and < 30
means that the left one has 30% chances.