Randomly pick one variable

This thread is assuming that you meant this as a state condition. But I suspect you just mean that these are the ranges you want. Does the value of a ever change?

Or do you just mean that you want to flip a coin, heads = -1, tails = 1? Possibly with arbitrary values on the coin?

Consider:

random(1) : 0.41… 0.74… 0.22… 0.52… 0.10… 0.87…
round(random(1)) : 0 1 0 0 1 1 1 0 1 0 1 1 0 0 …
…or (int)random(2) : 0 1 0 0 1 1 1 0 1 0 1 1 0 0 …
2 * round(random(1)) : 0 2 0 0 2 2 2 0 2 0 2 2 0 0 …
2 * round(random(1)) - 1 : -1 1 -1 -1 1 1 1 -1 1 -1 1 1 -1 -1 …

Now, this is just computing a random 1 or -1 – it isn’t picking a variable at random. However, there are many ways to connect a choice between two and a random number. For example:

int[] vars = new int[] { -1, 1 };

Now we have a vars[0] and a vars[1] holding our values. Let’s pick one at random.

println( vars[ (int)random(2) ] )

This will look up either vars[0] (= -1) or vars[1] (= 1). Now you could put any values in there, like { -13, 4 } and vars[ (int)random(2) ] would always return one of those two values at random.

1 Like