Search code examples
javascriptprocessingp5.js

How to randomly pick number of 2 numbers. p5js


I think it is a very simple question, but I can't find an answer. How to randomly pick one number out of 2 numbers. In my situation, I need to pick numbers {-2, 2}. Just one out of these two numbers.


Solution

  • You can pass an array of items into random() if you need to randomly choose from a predetermined set.

    In your case, the following code will always pick (-2 or 2), nothing else or anything in-between.

    random([-2, 2]);
    

    You can read more about the random function here https://p5js.org/reference/#/p5/random