# Help with random() where only two values can be chosen

Hello. i have an assignment where i need to have a ball that when starting needs to go either left OR right.
my first thought was to give my “speed” variable at the setup “= random (-3 ||+3)”. But it still starts att different values between -3 and +3 as well as only being able to go one direction when i try to run the code.

wonder if anybody know how to solve this?

How about `3 * (1-2*Math.floor(2 * Math.random()))`?
`Math.floor(2 * Math.random())` returns 0 or 1.
`1-2*random` can be 1 or -1 then. Multiply by 3 and you are done.

1 Like

thank you so much! been trying for an eternity to solve it.

can i ask what 2 ** in 2 math.random() does?

Math.random() gives a random float in 0…1 (1 excluded). Multiplying by 2 gives a value in the range of 0…2, so for example 0.3, 1.34, 0.76, 1.76.
The floor function removes the part after the decimal point (at least for positive input values), making it 0 or 1.

Dirty trick:

``````let speed = [-3, +3][Math.floor(Math.random() * 2)];
``````

But if you have only 2 values you can also just use a ternary operator:

``let speed = Math.random() > 0.5 ? -3 : +3;``
1 Like