7

I am a little stuck with a simple Question: how to generate a simple random Boolean?
If am correct, a Boolean 0 = false and 1 = true, but how to suse that?

Current code:

Dim RandGen As New Random
Dim RandBool As Boolean
RandBool = Boolean.Parse(RandGen.Next(0, 1).tostring)
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
Christian Sauer
  • 10,351
  • 10
  • 53
  • 85
  • 1
    Generate a random number, multiply it by 2 and round down? `CInt(Math.Floor(Rnd() * 2))` should produce 0 or 1 which you could then use – dudledok Mar 10 '13 at 17:38
  • Also, see this previously asked question: [Random Int in VB.Net](http://stackoverflow.com/questions/18676/random-int-in-vb-net) – Paul J Hurtado Mar 10 '13 at 20:07
  • Dudledok it does work - but how does it work? Especially the multiplication with two is surprising for me. – Christian Sauer Mar 11 '13 at 07:48

3 Answers3

23

Or just simply:

Random rng = new Random();
bool randomBool = rng.Next(0, 2) > 0;

Saves some processing power of parsing text, whereas a simple compare is enough.

Edit: Second parameter is exclusive, so should be .Next(0, 2).

Caramiriel
  • 7,029
  • 3
  • 30
  • 50
  • That is neat, I will go with it, thanks. How does it work? Does it round the resultung random number to 0 / 1 and then tests if the value is greater than 0? – Christian Sauer Mar 11 '13 at 07:47
  • It generates either an integer 0 or 1. This number is checked if it is larger than zero. If it is, then it returns `true`, otherwise `false`. It's actually just in inline if-statement. Since the actual number generator already generates a 50% chance of being zero or one, it just need to be mapped from `[0,1]` to `[false,true]`. – Caramiriel Mar 11 '13 at 07:54
  • The first parameter of 0 is optional because that is the default. `rng.Next(2) > 0` is sufficient. – wensveen Dec 19 '18 at 11:45
1

Dim RandGen As New Random

    Dim RandBool As Boolean

    RandBool = RandGen.Next(0, 2).ToString

    TextBox1.Text = RandBool
0

Maybe something like this?

        string[] trueOrFalse = { "false", "true"};
        bool RandBool = bool.Parse(trueOrFalse[RandGen.Next(0,2)]);
  • 2
    Good idea, but why declare your array as a string array instead of a boolean array? You have one extra not necessary step. – Meta-Knight Mar 10 '13 at 20:33