Solved

Working with random numbers

Posted on 2004-10-20
10
232 Views
Last Modified: 2010-04-23
This may be a bit tricky; I’ll try to explain what I am trying to do and hope that there is a way to do it with some code I can use in VB.NET 2002.  For this part of my program I need to take a number of known numbers then mix them with random numbers in a range to make a set of numbers in a specific format.  

The number of known numbers is unknown: Example…there may be 1 known number, 3 known numbers or 10 known numbers…. I think something like having some type of input to add the known numbers to an array and then randomly pick the rest of the needed numbers from a range that the user sets and then randomly mix them all up and display them in a label or something best explains what it is I am looking for.

3 known numbers, needs to have total of 6 numbers, enter the 3 known numbers and they are added to an array, set the range of numbers 0 to 40 and have the program pick 3 numbers that are then added to the array, the numbers are randomly mixed together and then displayed in double digit format for numbers 0 to 9 so that 1 is 01 etc…. the label display might look like this: 08 – 25 – 14 – 07 – 06 – 34

Anyone have a working example of how this can be done?
0
Comment
Question by:teamdad
10 Comments
 
LVL 4

Expert Comment

by:eozz_2000
ID: 12366152
Well... I understand that you want to create random number between 2 numbers given by de user?

MsgBox(rnd.Next(CInt(Me.TextBox1.Text), CInt(Me.TextBox2.Text)).ToString.PadLeft(2, "0"))
0
 

Author Comment

by:teamdad
ID: 12366220
Almost.... the user will have some number of numbers they already know and the rest they will need random numbers for.  

Example:

I need the user to enter the numbers they already have (not everyone will have the same amount of numbers) once they enter what they have already I need the program to take a pre defined (by the user) range of numbers that it will pick the rest of the numbers from, it will take what the user entered and what it calculated (randomly on it's own) then randomly mix all the numbers again and display the set of numbers.

Still example:

Say a user knows that the range of numbers is between 0 and 54, they only need to have 6 numbers in all, they already know they have number 4, 20, and 32 but they still need to have the program come up with the other three numbers randomly to make them then have the 6 numbers.  The program will pick the other 3 numbers from the user set range of 0 and 54, the program say picks 18, 50, and 7... now they have 4, 20, 32, 18, 50, 7 as their 6 numbers.  The program then needs to take those numbers and mix their order up and then display the 6 numbers in a format like 18 - 7 - 4 - 20 - 50 - 32 to the user.
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 12366265
The following function getNumbers() should do the trick:

Public Class Form1
    Inherits System.Windows.Forms.Form

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim knownValues() As Integer = {4, 20, 32}
        Label1.Text = getNumbers(knownValues, 6, 0, 54)
    End Sub

    Private Function getNumbers(ByVal known() As Integer, ByVal requiredNumber As Integer, _
            ByVal minRange As Integer, ByVal maxRange As Integer) As String

        Dim output As String
        Dim i As Integer
        Dim tmp As Integer
        Dim rndIndex As Integer
        Dim tmpArray(requiredNumber - 1) As Integer
        Dim r As New Random
        Dim randomPool As New ArrayList

        ' build the random pool
        For i = minRange To maxRange
            ' don't include any of the known values
            If Array.IndexOf(known, i) = -1 Then
                randomPool.Add(i)
            End If
        Next

        ' shuffle the random values
        For i = 0 To (randomPool.Count - 1)
            rndIndex = r.Next(0, randomPool.Count)
            tmp = randomPool(i)
            randomPool(i) = randomPool(rndIndex)
            randomPool(rndIndex) = tmp
        Next

        ' populate tmpArray with the known values
        ' and fill in any remaining slots
        ' with values from the shuffled randomPool
        For i = 0 To (requiredNumber - 1)
            If i <= known.GetUpperBound(0) Then
                tmpArray(i) = known(i)
            Else
                tmpArray(i) = randomPool.Item(0)
                randomPool.RemoveAt(0)
            End If
        Next

        ' shuffle the set by swapping
        ' each position with another
        For i = 0 To tmpArray.GetUpperBound(0)
            rndIndex = r.Next(0, tmpArray.GetUpperBound(0))
            tmp = tmpArray(i)
            tmpArray(i) = tmpArray(rndIndex)
            tmpArray(rndIndex) = tmp
        Next

        ' build the output string from
        ' the shuffled set
        For i = 0 To tmpArray.GetUpperBound(0)
            If output = "" Then
                output = Format(tmpArray(i), "00")
            Else
                output = output & " - " & Format(tmpArray(i), "00")
            End If
        Next
        Return output
    End Function

End Class
0
 

Author Comment

by:teamdad
ID: 12366488
That got me thinking...... I know how to better explain now.  The user is given a piece of paper that has some numbers on it.... it may have just one number or any amount of numbers on it, the paper also has a range of numbers on it that could be anything and it has how many numbers you need in total, the user don't know what any of these are till they get their piece of paper. They need to enter the range of numbers that is on the paper with two NumericUpDown controls and they have to enter the number of numbers total they need with a textbox and they need to enter the numbers one at a time with another textbox to add to the pool and then push a button.  The program will know how many numbers they need total and the range of numbers it needs to pick the rest from to make the total amount of numbers they entered, it takes what they have entered plus what it picks from the pool and combines them in a random order and displays them on a label.  

It's kinda like you know some of the numbers you want/need but you want the rest of the unknown numbers to be randomly picked from a pool or range of numbers then have them mixed up and displayed so they aren't in any order from the ones you knew and the ones the program picked for you.
0
 
LVL 11

Expert Comment

by:Babycorn-Starfish
ID: 12368283
Hi,

hope i'm not asking the obvious but... how many numbers are ever needed in total? e.g. you mentioned that with three known numbers that another three are needed for a total of six, how many for n known numbers?

Cheers

BC
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 12369914
Hi teamdad, the algorithm I posted will work for your requirements.  Do you need help putting an interface on it?

~IM
0
 

Author Comment

by:teamdad
ID: 12373846
Babycorn-Starfish, it's another tricky part.  The most would be 6 total but the user may have one of the six, two of the six, three of the six, four of the six or five of the six numbers.

Idle Mind, in your code I saw that it hard coded the numbers and the known numbers will not be the same every time.  Another working example would be great if it will still work.
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 12376096
The numbers were hard coded into an array only for the example.

The getNumbers() function itself receives an array of integers so it is flexible.  Just build the array of values as the user enters them and pass them into the function along with the other parameters.

Do I need to build an entire GUI to show how to use it?

~IM
0
 

Author Comment

by:teamdad
ID: 12376551
If you wouldn't mind, I would like an example to see how it works.  I only put a label and a button on the GUI I made for it.
0
 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 500 total points
ID: 12377248
Here is an example of the function being used via a GUI.  There isn't any error checking present.  This is simply an example of one way to use it.

~IM

Public Class Form1
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents Label1 As System.Windows.Forms.Label
    Friend WithEvents Button1 As System.Windows.Forms.Button
    Friend WithEvents requiredNumber As System.Windows.Forms.NumericUpDown
    Friend WithEvents minRange As System.Windows.Forms.NumericUpDown
    Friend WithEvents maxRange As System.Windows.Forms.NumericUpDown
    Friend WithEvents addKnownValue As System.Windows.Forms.Button
    Friend WithEvents Label2 As System.Windows.Forms.Label
    Friend WithEvents Label3 As System.Windows.Forms.Label
    Friend WithEvents Label4 As System.Windows.Forms.Label
    Friend WithEvents knownValue As System.Windows.Forms.NumericUpDown
    Friend WithEvents reset As System.Windows.Forms.Button
    Friend WithEvents knownValuesList As System.Windows.Forms.ListBox
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.Label1 = New System.Windows.Forms.Label
        Me.Button1 = New System.Windows.Forms.Button
        Me.addKnownValue = New System.Windows.Forms.Button
        Me.requiredNumber = New System.Windows.Forms.NumericUpDown
        Me.minRange = New System.Windows.Forms.NumericUpDown
        Me.maxRange = New System.Windows.Forms.NumericUpDown
        Me.Label2 = New System.Windows.Forms.Label
        Me.Label3 = New System.Windows.Forms.Label
        Me.Label4 = New System.Windows.Forms.Label
        Me.knownValue = New System.Windows.Forms.NumericUpDown
        Me.reset = New System.Windows.Forms.Button
        Me.knownValuesList = New System.Windows.Forms.ListBox
        CType(Me.requiredNumber, System.ComponentModel.ISupportInitialize).BeginInit()
        CType(Me.minRange, System.ComponentModel.ISupportInitialize).BeginInit()
        CType(Me.maxRange, System.ComponentModel.ISupportInitialize).BeginInit()
        CType(Me.knownValue, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.SuspendLayout()
        '
        'Label1
        '
        Me.Label1.Location = New System.Drawing.Point(16, 120)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(232, 32)
        Me.Label1.TabIndex = 0
        Me.Label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
        '
        'Button1
        '
        Me.Button1.Location = New System.Drawing.Point(256, 120)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(104, 24)
        Me.Button1.TabIndex = 1
        Me.Button1.Text = "Generate Set"
        '
        'addKnownValue
        '
        Me.addKnownValue.Location = New System.Drawing.Point(208, 16)
        Me.addKnownValue.Name = "addKnownValue"
        Me.addKnownValue.Size = New System.Drawing.Size(72, 24)
        Me.addKnownValue.TabIndex = 3
        Me.addKnownValue.Text = "Add Known"
        '
        'requiredNumber
        '
        Me.requiredNumber.Location = New System.Drawing.Point(72, 16)
        Me.requiredNumber.Name = "requiredNumber"
        Me.requiredNumber.Size = New System.Drawing.Size(48, 20)
        Me.requiredNumber.TabIndex = 4
        Me.requiredNumber.Value = New Decimal(New Integer() {6, 0, 0, 0})
        '
        'minRange
        '
        Me.minRange.Location = New System.Drawing.Point(72, 48)
        Me.minRange.Name = "minRange"
        Me.minRange.Size = New System.Drawing.Size(48, 20)
        Me.minRange.TabIndex = 5
        '
        'maxRange
        '
        Me.maxRange.Location = New System.Drawing.Point(72, 80)
        Me.maxRange.Name = "maxRange"
        Me.maxRange.Size = New System.Drawing.Size(48, 20)
        Me.maxRange.TabIndex = 6
        Me.maxRange.Value = New Decimal(New Integer() {54, 0, 0, 0})
        '
        'Label2
        '
        Me.Label2.Location = New System.Drawing.Point(8, 48)
        Me.Label2.Name = "Label2"
        Me.Label2.Size = New System.Drawing.Size(56, 16)
        Me.Label2.TabIndex = 7
        Me.Label2.Text = "Minimum:"
        Me.Label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight
        '
        'Label3
        '
        Me.Label3.Location = New System.Drawing.Point(8, 80)
        Me.Label3.Name = "Label3"
        Me.Label3.Size = New System.Drawing.Size(56, 16)
        Me.Label3.TabIndex = 8
        Me.Label3.Text = "Maximum:"
        Me.Label3.TextAlign = System.Drawing.ContentAlignment.MiddleRight
        '
        'Label4
        '
        Me.Label4.Location = New System.Drawing.Point(8, 16)
        Me.Label4.Name = "Label4"
        Me.Label4.Size = New System.Drawing.Size(56, 16)
        Me.Label4.TabIndex = 9
        Me.Label4.Text = "Required:"
        Me.Label4.TextAlign = System.Drawing.ContentAlignment.MiddleRight
        '
        'knownValue
        '
        Me.knownValue.Location = New System.Drawing.Point(152, 16)
        Me.knownValue.Name = "knownValue"
        Me.knownValue.Size = New System.Drawing.Size(48, 20)
        Me.knownValue.TabIndex = 10
        '
        'reset
        '
        Me.reset.Location = New System.Drawing.Point(288, 16)
        Me.reset.Name = "reset"
        Me.reset.Size = New System.Drawing.Size(72, 24)
        Me.reset.TabIndex = 11
        Me.reset.Text = "Reset"
        '
        'knownValuesList
        '
        Me.knownValuesList.Location = New System.Drawing.Point(152, 48)
        Me.knownValuesList.Name = "knownValuesList"
        Me.knownValuesList.Size = New System.Drawing.Size(208, 56)
        Me.knownValuesList.TabIndex = 12
        '
        'Form1
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(368, 158)
        Me.Controls.Add(Me.knownValuesList)
        Me.Controls.Add(Me.reset)
        Me.Controls.Add(Me.knownValue)
        Me.Controls.Add(Me.Label4)
        Me.Controls.Add(Me.Label3)
        Me.Controls.Add(Me.Label2)
        Me.Controls.Add(Me.maxRange)
        Me.Controls.Add(Me.minRange)
        Me.Controls.Add(Me.requiredNumber)
        Me.Controls.Add(Me.addKnownValue)
        Me.Controls.Add(Me.Button1)
        Me.Controls.Add(Me.Label1)
        Me.Name = "Form1"
        Me.Text = "Partial Random Set"
        CType(Me.requiredNumber, System.ComponentModel.ISupportInitialize).EndInit()
        CType(Me.minRange, System.ComponentModel.ISupportInitialize).EndInit()
        CType(Me.maxRange, System.ComponentModel.ISupportInitialize).EndInit()
        CType(Me.knownValue, System.ComponentModel.ISupportInitialize).EndInit()
        Me.ResumeLayout(False)

    End Sub

#End Region

    Private knownValues As New ArrayList

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Label1.Text = getNumbers(knownValues, requiredNumber.Value, minRange.Value, maxRange.Value)
    End Sub

    Private Function getNumbers(ByVal known As ArrayList, ByVal requiredNumber As Integer, _
            ByVal minRange As Integer, ByVal maxRange As Integer) As String

        Dim output As String
        Dim i As Integer
        Dim tmp As Integer
        Dim rndIndex As Integer
        Dim tmpArray(requiredNumber - 1) As Integer
        Dim r As New Random
        Dim randomPool As New ArrayList

        ' build the random pool
        For i = minRange To maxRange
            ' don't include any of the known values
            If Not known.Contains(i) Then
                randomPool.Add(i)
            End If
        Next

        ' shuffle the random values
        For i = 0 To (randomPool.Count - 1)
            rndIndex = r.Next(0, randomPool.Count)
            tmp = randomPool(i)
            randomPool(i) = randomPool(rndIndex)
            randomPool(rndIndex) = tmp
        Next

        ' populate tmpArray with the known values
        ' and fill in any remaining slots
        ' with values from the shuffled randomPool
        For i = 0 To (requiredNumber - 1)
            If i <= (known.Count - 1) Then
                tmpArray(i) = known(i)
            Else
                tmpArray(i) = randomPool.Item(0)
                randomPool.RemoveAt(0)
            End If
        Next

        ' shuffle the set by swapping
        ' each position with another
        For i = 0 To tmpArray.GetUpperBound(0)
            rndIndex = r.Next(0, tmpArray.GetUpperBound(0))
            tmp = tmpArray(i)
            tmpArray(i) = tmpArray(rndIndex)
            tmpArray(rndIndex) = tmp
        Next

        ' build the output string from
        ' the shuffled set
        For i = 0 To tmpArray.GetUpperBound(0)
            If output = "" Then
                output = Format(tmpArray(i), "00")
            Else
                output = output & " - " & Format(tmpArray(i), "00")
            End If
        Next
        Return output
    End Function

    Private Sub reset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles reset.Click
        knownValues = New ArrayList
        knownValuesList.Items.Clear()
        Label1.Text = ""
    End Sub

    Private Sub addKnownValue_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles addKnownValue.Click
        knownValues.Add(knownValue.Value)
        knownValuesList.Items.Add(knownValue.Value)
    End Sub

End Class
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Well, all of us have seen the multiple EXCEL.EXE's in task manager that won't die even if you call the .close, .dispose methods. Try this method to kill any excels in memory. You can copy the kill function to create a check function and replace the …
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now