Click here to Skip to main content
15,886,199 members

Random, Randomize, Rnd, seed values

OneInNineMillion asked:

Open original thread
Hey all,

I've been wondering about generating random numbers within a certain range for a while.
Recently I've been using something like this a lot:
VB
Dim Generator As New Random
Generator.Next(1, 30)

(this generates numbers ranging from 1 up to and including 29)

In the past I was told to use Rnd and that I needed to call Randomize first, but because I can easily generate a random number within a range with Random I've been using that. It was long ago that I used Rnd and Randomize.

What I'm trying to do is something like this:
I want to shuffle 2 decks of cards as I load a form.
To shuffle one deck I do this:
VB
Dim DeckBefore As New Collection
Dim DeckAfter As New Collection
Dim Position As New Random
Dim ChosenCard As Integer

While DeckBefore.Count > 0
    ChosenCard = Position.Next(1, DeckBefore.Count + 1)
    DeckAfter.Add(DeckBefore.Item(ChosenCard))
    DeckBefore.Remove(ChosenCard)
End While

Imagine DeckBefore to be a list of cards like this: Ace of Spaces, Two of Spades, Three of Spades .. and so on
DeckAfter could be something like this: Jack of Hearts, Seven of Clubs, Three of Diamonds, King of Spades .. and so on

The problem I encounter is that if I use this code for 2 separate decks, they end up identically (although not the same each time). I understand this has to do with the seed value of the Random, and that is automatically picks the date/time for a seed value if I don't give it one.

All I want really is for my program to order cards "randomly" each time so that a player won't be able to predict (out of the top of his/her head) what card comes next.

any help would be appreciated.
Tags: Visual Basic

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900