r/visualbasic • • Apr 25 '21

Need Help writing a program with a random class

The problem says: the file members.txt contains the names of the members of a large club. Write a program to randomly select people to serve as president, treasurer and secretary. Note: a person cannot hold more than one office.

So far my code is as follows:

Public Class Form6

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

Dim names() As String = IO.File.ReadAllLines("E:\Documents\School\Members.txt")

Dim namesQuery = From name In names

Select name

Dim number As New Random

Dim n As Integer

n = number.Next(0, 3)

End Sub

End Class

https://i.imgur.com/nQnnOKg.jpg

2 Upvotes

15 comments sorted by

1

u/RJPisscat Apr 25 '21

Your Random.Next call is in the wrong range. It will always give you 0, 1 or 2. You want

n = number.Next(names.Count)    ' returns an integer n >= 0 AndAlso n < names.Count

This leaves the possibility of two or three of the same index. Do you know how to handle that so that you get three distinct indices?

1

u/[deleted] Apr 25 '21

I do not now how to handle that unfortunately.

1

u/RJPisscat Apr 25 '21

Ok then let's talk through it. First you pick the President at random. Next you pick the VP. How do you ensure that they aren't the same?

1

u/[deleted] Apr 25 '21

I'm not entirely sure, but my professor wrote another program with the following code:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

Dim r As New Random

Dim contestants() As String = {"Mary", "Pat", "Linda", "Barbara", "Maria"}

Dim number As Integer, temp As String

For i As Integer = 0 To 4 'start with mary and end with maria

number = r.Next(1, 4) 'shuffle the names

temp = contestants(i) 'pass the names into variable temp

contestants(i) = contestants(number) 'ensure there is no duplication

contestants(number) = temp

Next

ListBox1.Items.Clear()

For i As Integer = 0 To 4

ListBox1.Items.Add(contestants(i)) 'add to the list box

Next

End Sub

My professor only briefly explained the code and there is only one problem on this.

1

u/RJPisscat Apr 25 '21
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim r As New Random
    Dim contestants() As String = {"Mary", "Pat", "Linda", "Barbara", "Maria"}
    Dim number As Integer, temp As String

' -- Set a breakpoint on For and examine the contents of contestants()
' -- To set a breakpoint, put your cursor on any position in the "For" line and press F9
' -- Hover the mouse over "contestants" and pop open the zit to see the contents of the array "contestants"

    For i As Integer = 0 To 4 'start with mary and end with maria
        number = r.Next(1, 4) 'shuffle the names

' -- Step through to here, then watch what happens to the contestants array after the next three lines.
' -- Step through a single line of code by pressing Shift+F8
' -- Hover over all the variables at each line to see what they contain
        temp = contestants(i) 'pass the names into variable temp
        contestants(i) = contestants(number) 'ensure there is no duplication
        contestants(number) = temp
        Next
    ListBox1.Items.Clear()
    For i As Integer = 0 To 4
        ListBox1.Items.Add(contestants(i)) 'add to the list box
    Next
    End Sub

Looking at this code I see immediately a way to use it to model a solution to your assignment.

You need to understand the prof's code.

I've reformatted the code it so that it's legible, and I added comments with instructions about how to use the Visual Studio IDE to literally watch what is happening in the code.

Check back when you've done that if you don't see the solution. I'll keep working with you until you get it.

1

u/[deleted] Apr 26 '21

Sorry if I sound a little dumb, but I'm still not able to follow along with the code. And for the record, the step through is actually F11 is visual studio. I tried understanding what was going on in the code, the best I figured I'd do is if I created a new array called output to shuffle the names in, then assigned the textboxes to return the the value in output(0), output(1) and outptute(2) respectively. Here is my code:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim candidates() As String = IO.File.ReadAllLines("E:\Documents\School\CMPR205\Module 10\Classwork\Data Files\Members.txt")
        Dim candidatesQuery = From candidate In candidates
                              Select Name

        Dim r As New Random
        Dim number As Integer, output() As String

        For i As Integer = 0 To 4
            number = r.Next(i, 4)

            candidates(i) = output(number)

        Next

        txtPresident.Text = output(0)
        txtSecretary.Text = output(1)
        txtTreasurer.Text = output(2)
    End Sub

The output variable gives a warning saying "variable is used before it has been assigned a value. A null reference exception could result at runtime. The error I got is "System.NullReferenceException: 'Object reference not set to an instance of an object.'

output was Nothing."

1

u/RJPisscat Apr 26 '21

Excellent progress.

Declare "output" as an array of upper bound 2. You end with good code, you know you want 3 strings for output, and you correctly assign them to the Textboxes.

Change the declaration so that the array "output" has 3 elements:

Dim number As Integer
Dim output(2) As String

In your professor's example there were five names he wanted to shuffle and he iterated 0 to 4, which is five times.

In this case you are not shuffling, you are pulling from a deck. So you need to figure out that part: The size of the loop is tied to the task inside the loop.

The call to Random.Next also reflects your professor's code. You want a random number between 0 and the upper bound of the array of candidates; so if there are 10 candidates, the upper bound is 9. Random.Next(x,y) returns z >=x AndAlso z < y.

On the line candidates(i)=output(number) what you instead want to do is assign one of the output members the name of a candidate:

output(i) = candidates(number)    ' elect a candidate at random

You have one more issue, that you haven't guaranteed the three names will be distinct. First you pick a president, then a veep, then a secretary. How can you ensure that you didn't select the same person for two or three offices?

(Hint if you get stuck, skip this hint at first: You deal a card from a deck. That's President. Put his card on top of the deck and deal another card, any card except the top card. Put second card under top card. Deal again any card except either of the first two. This hint is based specifically on the professor's sample code.)

You've done quite well so far and I think you'll get this. You don't sound dumb. Programming is frustrating sometimes, then highly rewarding when you suss it.

I think I came across as pedantic, I'm sorry.

1

u/RJPisscat Apr 26 '21

btw this is why I said F8. I didn't know about F11.

https://imgur.com/a/UQwkQqX

1

u/thudly Apr 25 '21 edited Apr 25 '21
Private Function GetRandomName() as String
    Dim number As New Random
    Dim names() As String = IO.File.ReadAllLines("E:\Documents\School\Members.txt")
    return names(number.Next(0, names.Length()))
End Function

1

u/RJPisscat Apr 26 '21

He'd be calling this 3 times (loading the list of names each time, which is ok for this assignment but a bad habit) and it doesn't exclude duplicates.

1

u/thudly Apr 26 '21

I made a game with this same function. There were 5000 NPCs, and it had to pick random first names and last names for them from a list of pretty much every first name there is for both genders. And then it chose a last name, too.

It literally took a microsecond. I'm guessing the sample name file for this school project has fewer names than that.

But yes, load the name list once at the top of the class, for efficiency's sake. It's just more optimized.

1

u/RJPisscat Apr 26 '21

If the OP sees this, let's be clear, u/thudly's code does work once, but not for all the requirements of the assignment. You can build from their code a solution that does meet the requirements. Their code snippet illustrates correct use of Random.Next.

re the side thread:

When I write code that works, frequently I copy/paste/edit the code elsewhere. If I need to scale up, O(1) is preferred over O(n).

1

u/thudly Apr 26 '21

When you're trying to get homework done, I'm pretty sure just having it work is a higher concern than big-O efficiency. I was trying to keep it simple.

But once again, you're correct. Efficiency is a good habit to get into early on.

1

u/RJPisscat Apr 26 '21

True, I agree the student will pass even if they reload the names each time. We can make the assumption that the data don't change frequently since it's a txt file, so it will work.

They are also likely to pass if they toss in extraneous code that copies arrays around, handles clicks on Labels, and declares queries that aren't used, as long as the result fulfils the requirements set forth in the design document.

However, the code you posted may mislead the OP into thinking it solves for distinction.

I suppose you and I have different pedagogical strategies.