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.
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.
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.
2007-2013
Why is my data not saved to my database? | Communicating between multiple forms | MSDN Data Walkthroughs
MSDN "How Do I?" Videos: VB | C#
VBForums Database Development FAQ
My CodeBank Submissions: VB (*NEW* Match Two Game, *NEW* More Random Random Numbers) | C# (*NEW* Match Two Game, *NEW* More Random Random Numbers)
My Blog: Using Parameters in ADO.NET | Keyboard Events | Assemblies & Namespaces
Here is how you can select a random String from an array and display it in a label:-
vbnet Code:
' Dim strings As String() = {"String 1", "String 2", "String 3", "String 4", "String 5", "String 6", "String 7", "String 8"} 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
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.
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.
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.
2007-2013
Why is my data not saved to my database? | Communicating between multiple forms | MSDN Data Walkthroughs
MSDN "How Do I?" Videos: VB | C#
VBForums Database Development FAQ
My CodeBank Submissions: VB (*NEW* Match Two Game, *NEW* More Random Random Numbers) | C# (*NEW* Match Two Game, *NEW* More Random Random Numbers)
My Blog: Using Parameters in ADO.NET | Keyboard Events | Assemblies & Namespaces
Using the examples in the prior post I would go this route:I kind of need a method to "eliminate" a certain string I randomed
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.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
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
Last edited by dday9; Aug 20th, 2012 at 11:31 AM.
Contributions:
Login | Let the user chose a connection string | Open/Close a Database Connection | Stick Notes | Slideable Controls | Circular Progressbar | Rounded Button | Random between 2 solutions | Custom Monthcalendar | Country Flags | XNA Control in Win-Form App | Textfile to Datatable | Syntax Highlighter
Game Contributions:
Slots | Tic-Tac-Toe | Pong | Bouncy Ball | Simon | Tron - Lightcycles | Connect4 | Hangman | Pure VB 2d Tile Based Map Engine | Plinko
XNA in Vb.Net Tutorials:
Getting Started | Setting up XNA Graphics | Displaying XNA Graphics
Links:
LegalShield | AUP
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
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
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.
2007-2013
Why is my data not saved to my database? | Communicating between multiple forms | MSDN Data Walkthroughs
MSDN "How Do I?" Videos: VB | C#
VBForums Database Development FAQ
My CodeBank Submissions: VB (*NEW* Match Two Game, *NEW* More Random Random Numbers) | C# (*NEW* Match Two Game, *NEW* More Random Random Numbers)
My Blog: Using Parameters in ADO.NET | Keyboard Events | Assemblies & Namespaces
2007-2013
Why is my data not saved to my database? | Communicating between multiple forms | MSDN Data Walkthroughs
MSDN "How Do I?" Videos: VB | C#
VBForums Database Development FAQ
My CodeBank Submissions: VB (*NEW* Match Two Game, *NEW* More Random Random Numbers) | C# (*NEW* Match Two Game, *NEW* More Random Random Numbers)
My Blog: Using Parameters in ADO.NET | Keyboard Events | Assemblies & Namespaces
Last edited by Legjendat; Aug 21st, 2012 at 08:26 AM.