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)
3
  • 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
    Commented Mar 10, 2013 at 17:38
  • Also, see this previously asked question: Random Int in VB.Net Commented Mar 10, 2013 at 20:07
  • Dudledok it does work - but how does it work? Especially the multiplication with two is surprising for me. Commented Mar 11, 2013 at 7:48

3 Answers 3

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).

3
  • 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? Commented Mar 11, 2013 at 7: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
    Commented Mar 11, 2013 at 7:54
  • The first parameter of 0 is optional because that is the default. rng.Next(2) > 0 is sufficient.
    – wensveen
    Commented Dec 19, 2018 at 11:45
1

Dim RandGen As New Random

    Dim RandBool As Boolean

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

    TextBox1.Text = RandBool
1
  • Does that mean that we can assign a string value to a variable of type Booelan, in VB.NET? Commented Jul 5, 2018 at 14:28
0

Maybe something like this?

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.