3

How can i choose random number smaller than "1000" or "n"?

Do While ddd <> 1
    Static staticRandomGenerator As New System.Random

    max += 1
    dd = staticRandomGenerator.Next(If(min > max, max, min), If(n > max, min, max))
    ddd = ee * dd Mod z
Loop

How can i add this condition to this code? Any idea?

reduckted
  • 2,358
  • 3
  • 28
  • 37
Goma
  • 53
  • 2
  • 10
  • 1
    `dd = RNG.Next(min, 1000)` will pick a value between whatever the min is and less than 1000 every time. Dont create the RNG in the loop though - guarantees they will all be the same – Ňɏssa Pøngjǣrdenlarp Mar 26 '16 at 19:12
  • I have to put random number in loop, because i have another condition, i need random number to put it in this _Math_ and **ddd** must be equal **1** `ddd = ee * dd Mod z` – Goma Mar 26 '16 at 19:19
  • 2
    No. `Static staticRandomGenerator As New System.Random` that line IN the loop almost guarantees that the same seed will be used. Why is it static anyway? – Ňɏssa Pøngjǣrdenlarp Mar 26 '16 at 19:22
  • Sorry, I don't understand what you mean, that code is correct, but i need to add another condition. – Goma Mar 26 '16 at 19:31
  • 2
    The question/answer is in C# but the principle is the same. The Random variable initialization should be outside of the loop: http://stackoverflow.com/questions/767999/random-number-generator-only-generating-one-random-number – Steve Mar 26 '16 at 19:52
  • 3
    @Plutonix: his code doesn't in fact initialise the RNG inside the loop. The initialisation on a _static_ variable is only executed the first time it is encountered. I'm not saying it's a good way of writing it, but his code will initialise the RNG once and reuse the same one each time henceforth (even reusing the same one without re-initialisation if the function is called again) – Stuart Whitehouse Mar 26 '16 at 20:52

1 Answers1

0

There are two ways to generate a random number in VB.NET (that I am familiar with).

Technique 1:

randomNumber = CInt(Math.Floor((n - 0 + 1) * Rnd())) + 0

n = Upperbound value, otherwise known as the highest value randomNumber can be, which in your case you would have already defined as 1000.

0 = Lowerbound value, otherwise known as the lowest value the randomNumber can be.

You can find more info about this technique here.

Technique 2:

Dim rn As New Random
randomNumber = rn.Next(0, n)

Again, n = Upperbound value, otherwise known as the highest value randomNumber can be, which in your case you would have already defined as 1000.

And again, 0 = Lowerbound value, otherwise known as the lowest value randomNumber can be.

I cannot find a link to an official post about this on the Microsoft MSDN site, but if anyone can find a good post about this technique, please comment, or message me.

I hope this helps!

Nic
  • 76
  • 1
  • 1
  • 7