Results 1 to 12 of 12

Thread: Call a random string?

  1. #1
    Lively Member
    Join Date
    Apr 10
    Posts
    107

    Call a random string?

    The question is simple I think. I have declared 25 strings with random names, and I need to call these names randomly, like label1.text = NameX

    I have declared the string names like Name1, Name2, Name3 and so on.

  2. #2
    .NUT jmcilhinney's Avatar
    Join Date
    May 05
    Location
    Sydney, Australia
    Posts
    80,868

    Re: Call a random string?

    Those would be sequential names, not random names. I think that you're going about this the wrong way. Don't use individual variables. Use an array with 25 elements. You then use a Random object to generate a random number less than 25 and use that as an index into the array.

  3. #3
    Angel of Code Niya's Avatar
    Join Date
    Nov 11
    Posts
    3,144

    Re: Call a random string?

    Here is how you can select a random String from an array and display it in a label:-
    vbnet Code:
    1. '
    2.         Dim strings As String() = {"String 1", "String 2", "String 3", "String 4", "String 5", "String 6", "String 7", "String 8"}
    3.  
    4.         Label1.Text = strings((New Random).Next(0, strings.GetUpperBound(0)))

    EDIT:-

    Oh Jmc posted while I was writing that.....well consider it an example of what he was talking about.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | Create Sortable BindingList(not mine) | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading


    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. -jmcilhinney

  4. #4
    Lively Member
    Join Date
    Apr 10
    Posts
    107

    Re: Call a random string?

    Yeah, I was definitely going at it the wrong way, but given that I just started, replacing all those declarations with the array makes things much much easier.

    That being said, I need to ask something else, and any mods if a new thread is required for that, tell me. I kind of need a method to "eliminate" a certain string I randomed, since I want to call the random again on another label but don't want the same name twice.

    What comes into my mind is like checking the label1.text, and if it's the same as label2.text, then I reRandom on label2.text. Any better way to accomplish that?

    Thanks btw.

  5. #5
    Lively Member
    Join Date
    Apr 10
    Posts
    107

    Re: Call a random string?

    Yeah, I was definitely going at it the wrong way, but given that I just started, replacing all those declarations with the array makes things much much easier.

    That being said, I need to ask something else, and any mods if a new thread is required for that, tell me. I kind of need a method to "eliminate" a certain string I randomed, since I want to call the random again on another label but don't want the same name twice.

    What comes into my mind is like checking the label1.text, and if it's the same as label2.text, then I reRandom on label2.text. Any better way to accomplish that?

    Thanks btw.

  6. #6
    .NUT jmcilhinney's Avatar
    Join Date
    May 05
    Location
    Sydney, Australia
    Posts
    80,868

    Re: Call a random string?

    Quote Originally Posted by Niya View Post
    Here is how you can select a random String from an array and display it in a label:-
    vbnet Code:
    1. '
    2.         Dim strings As String() = {"String 1", "String 2", "String 3", "String 4", "String 5", "String 6", "String 7", "String 8"}
    3.  
    4.         Label1.Text = strings((New Random).Next(0, strings.GetUpperBound(0)))
    EDIT:-

    Oh Jmc posted while I was writing that.....well consider it an example of what he was talking about.
    While the principle of the code is OK there are two issues there:

    1. Creating the Random object within the code that uses it is not a good idea. Doing so mean that executing the code more than once in quick succession, e.g. in a loop, will lead to the same selection every time. You should generally use a member variable for a single Random object.
    2. The maxValue parameter of the Next method is exclusive, so that code would never select the last element in the array. It should be using Length, not GetUpperBound.

  7. #7
    .Net Member dday9's Avatar
    Join Date
    Mar 11
    Location
    South Louisiana
    Posts
    2,205

    Re: Call a random string?

    I kind of need a method to "eliminate" a certain string I randomed
    Using the examples in the prior post I would go this route:
    Code:
    'Declare a new list of strings
        Dim strings As New List(Of String)
    
        Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
            'Add text string1 - string25
            For i As Integer = 1 To 25 Step 1
                strings.Add("String" & i.ToString)
            Next
        End Sub
    
        Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
            'Declare a new random and integer
            Dim r As New Random
    
            'The integer will equal a random number inbetween 0 and the number of number of items in the list(of string) - 1
            'So long as there are items in the list(of string)
            If strings.Count > 0 Then
                Dim int As Integer = r.Next(0, strings.Count - 1)
            Else
                MessageBox.Show("There is nothing left in the list")
            End If
    
            'The label's text will be the item number that is randomly chose above
            Label1.Text = strings.Item(Int)
    
            'Remove the string from the list so that it will never be used again
            strings.Remove(Label1.Text)
    
        End Sub
    The reason I would use a list(of string) is because the item can be removed fairly easily by removing the item that has label1's text.

    Edit - this uses the random at the form scope as suggested by shaggy and mentioned by JMc in other post:

    Code:
    Option Strict On
    Option Explicit On
    Public Class Form1
        'Declare a new list of strings
        Dim strings As New List(Of String)
        Dim r As New Random
    
        Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
            'Add text string1 - string25
            For i As Integer = 1 To 25 Step 1
                strings.Add("String" & i.ToString)
            Next
        End Sub
    
        Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
            'Declare a new random and integer
    
            'The integer will equal a random number inbetween 0 and the number of number of items in the list(of string) - 1
            'So long as there are items in the list(of string)
            Dim int As Integer
            If strings.Count > 0 Then
                int = r.Next(0, strings.Count - 1)
            Else
                MessageBox.Show("There is nothing left in the list")
            End If
    
            'The label's text will be the item number that is randomly chose above
            Label1.Text = strings.Item(Int)
    
            'Remove the string from the list so that it will never be used again
            strings.Remove(Label1.Text)
    
        End Sub
    
    End Class

  8. #8
    Loquacious User Shaggy Hiker's Avatar
    Join Date
    Aug 02
    Location
    Idaho
    Posts
    20,410

    Re: Call a random string?

    To get at the second question:

    As a general rule, if you have a follow-up question closely tied to the original question, it makes sense to ask it in the original thread. If the question is different, then start a new thread. The reason for doing this is that you will get more eyeballs on a new thread than you will on an existing thread, so you might get better answers, and possibly quicker answers. There is no solid rule about it, though. In this case, you could really go whichever way you felt like, as the follow-up question is fairly well related to the original question, but it's also distinctly different. It's your call, and you've made it. In the future, you will be able to make a different choice or the same one. It's up to you.

    As for the question. There are a couple approaches you might consider. If you used a List(of String) rather than an array, you could simply remove each element as it was used, then select a random number from the remaining elements. This would not be particularly efficient if you will be doing it many times, as you would have to keep on re-populating the List. Another alternative would be to clear out a slot in the array when you use the item from that slot. Then the code would have to keep selecting random items until it found one that was not empty. If you will be using ALL the items from the array, or even most of them, this second alternative will have horrible performance, since a mostly empty array will result in LOTS of hits on already empty array slots before it finds one to use. There is a variation on that design that will guarantee that some item will be chosen each time, but it gets more complicated to implement. Furthermore, this design has the same problem as the List in that you will have to keep re-populating the array if you will be doing this often.

    A third alternative would be to have two arrays of the same size. The first array holds the strings, while the second array is an array of Boolean values. Whenever you use an item from the first array, you set the Boolean in the other array to True. An item in the first array can only be used if the Boolean is False. This has the same performance issues as setting the array element to an empty string in that the performance will degrade if you use most of the strings from the array. I'd go into a design that would avoid that performance hit, except that I'm pretty sure JMC has an even better way to do it. The goal is to select unique items from a set of items, which is much the same as dealing cards, and that has better solutions.
    My usual boring signature: Nothing

  9. #9
    Loquacious User Shaggy Hiker's Avatar
    Join Date
    Aug 02
    Location
    Idaho
    Posts
    20,410

    Re: Call a random string?

    I see that dday implemented the List (of String) approach, and I think I would tend to go that way, too. The one quibble I have with that is that the Random object should be declared at form scope and not local to the method.
    My usual boring signature: Nothing

  10. #10
    .NUT jmcilhinney's Avatar
    Join Date
    May 05
    Location
    Sydney, Australia
    Posts
    80,868

    Re: Call a random string?

    Quote Originally Posted by Legjendat View Post
    Yeah, I was definitely going at it the wrong way, but given that I just started, replacing all those declarations with the array makes things much much easier.

    That being said, I need to ask something else, and any mods if a new thread is required for that, tell me. I kind of need a method to "eliminate" a certain string I randomed, since I want to call the random again on another label but don't want the same name twice.

    What comes into my mind is like checking the label1.text, and if it's the same as label2.text, then I reRandom on label2.text. Any better way to accomplish that?

    Thanks btw.
    So what you're saying is that you want to make two unique random selections from a list, right? In that case, follow the CodeBank link in my signature and check out my threads on randomisation. There's one on Unique Random Selections and there's one on Randomising A List.

  11. #11
    .NUT jmcilhinney's Avatar
    Join Date
    May 05
    Location
    Sydney, Australia
    Posts
    80,868

    Re: Call a random string?

    Quote Originally Posted by Shaggy Hiker View Post
    I see that dday implemented the List (of String) approach, and I think I would tend to go that way, too. The one quibble I have with that is that the Random object should be declared at form scope and not local to the method.
    I have two quibbles with it and I mentioned them both in post #6. dday9 has also written code that will never select the last item.

  12. #12
    Lively Member
    Join Date
    Apr 10
    Posts
    107

    Re: Call a random string?

    Quote Originally Posted by dday9 View Post
    Using the examples in the prior post I would go this route:
    Code:
    'Declare a new list of strings
        Dim strings As New List(Of String)
    
        Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
            'Add text string1 - string25
            For i As Integer = 1 To 25 Step 1
                strings.Add("String" & i.ToString)
            Next
        End Sub
    
        Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
            'Declare a new random and integer
            Dim r As New Random
    
            'The integer will equal a random number inbetween 0 and the number of number of items in the list(of string) - 1
            'So long as there are items in the list(of string)
            If strings.Count > 0 Then
                Dim int As Integer = r.Next(0, strings.Count - 1)
            Else
                MessageBox.Show("There is nothing left in the list")
            End If
    
            'The label's text will be the item number that is randomly chose above
            Label1.Text = strings.Item(Int)
    
            'Remove the string from the list so that it will never be used again
            strings.Remove(Label1.Text)
    
        End Sub
    The reason I would use a list(of string) is because the item can be removed fairly easily by removing the item that has label1's text.

    Edit - this uses the random at the form scope as suggested by shaggy and mentioned by JMc in other post:

    Code:
    Option Strict On
    Option Explicit On
    Public Class Form1
        'Declare a new list of strings
        Dim strings As New List(Of String)
        Dim r As New Random
    
        Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
            'Add text string1 - string25
            For i As Integer = 1 To 25 Step 1
                strings.Add("String" & i.ToString)
            Next
        End Sub
    
        Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
            'Declare a new random and integer
    
            'The integer will equal a random number inbetween 0 and the number of number of items in the list(of string) - 1
            'So long as there are items in the list(of string)
            Dim int As Integer
            If strings.Count > 0 Then
                int = r.Next(0, strings.Count - 1)
            Else
                MessageBox.Show("There is nothing left in the list")
            End If
    
            'The label's text will be the item number that is randomly chose above
            Label1.Text = strings.Item(Int)
    
            'Remove the string from the list so that it will never be used again
            strings.Remove(Label1.Text)
    
        End Sub
    
    End Class


    Haven't checked the first method, but the second one seems to have a problem I think. I get an IndexOutOfRange exception

    EDIT:
    My mistake, the problem was with some changes I made, code works fine.
    Last edited by Legjendat; Aug 21st, 2012 at 08:26 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •