Random boolean howto

edited November 2013 in How To...

Hi,

I need the expression to get a random boolean value, and how to use the result as a negative or positive integer 1. Can someone please help?

Answers

  • boolean randomBool() {
      return random(1) > .5;
    }
    
  • static final int sigBool(boolean b) {
      return b? 1:-1;
    }
    
  • edited November 2013 Answer ✓

    -1 + (int)random(2) * 2

    (int)random(2) returns either a 0 or a 1 with equal probability

    if it's 0 then you get -1 + (0 * 2) = -1

    if it's 1 then t=you get -1 + (1 * 2) = 1

    doesn't use the boolean you mention, doesn't need to.

  • edited November 2013

    Nice trick, koogs! =D>

    int randomSignum() {
      return (int) random(2) * 2 - 1;
    }
    
  • Nice trick for sure! Thanks!

    Question to GoToLoop, what is the purpose of using int before the function name?

  • edited November 2013

    So it can return an int value! 3:-O
    Likewise variables, methods must have a returning data-type declaration.
    Including any arguments passed as well.

  • Okay then using only return inside the method isn't enough? Still quite noob to java as you guessed already...

  • edited November 2013

    When a method is declared to ignore a returned value, that is, void; there's not even a need to have return in it.
    Unless of course, we wish to abort it before reaching its scope ending! ^#(^

    Now, for anything other than void, we gotta return that corresponding data-type somewhere within it! L-)

Sign In or Register to comment.