I have an array of integers like these;
dim x as integer()={10,9,4,7,6,8,3}.
Now I want to pick a random number from it,how can I do this in visual basic?Thanks in advance...
First you need a random generator:
Dim rnd As New Random()
Then you pick a random number that represents an index into the array:
Dim index As Integer = rnd.Next(0, x.Length)
Then you get the value from the array:
Dim value As Integer = x(index)
Or the two last as a single statement:
Dim value As Integer = x(rnd.Next(0, x.Length))
Now, if you also want to remove the number that you picked from the array, you shouldn't use an array in the first place. You should use a List(Of Integer) as that is designed to be dynamic in size.
randomly choose an index from 0 to length-1 from your array.
Related
I want my application to populate random sets of numbers using a list of specific numbers that i chose. For example; I have a set of numbers (1,3,5,9,21,70,56). I want to be able to randomize the order in which these numbers are selected. Is that possible?
If you want to generate a list of 1000 numbers using only those you gave:
Dim r as New Random()
Dim thousand as New List(Of Integer)(1000)
'short way to create an array
Dim onlyFrom = {1,3,5,9,21,70,56}
For i = 1 to 1000
thousand.Add(onlyFrom(r.Next(0, onlyFrom.Length)))
Next i
It repeatedly asks a Random for a random integer between 0 and the array length. Next() may return the lower number, but never the upper number. Documentation
If you want to shuffle those numbers you gave into a random order, easy way to use LINQ:
Dim r as New Random()
Dim onlyFrom = {1,3,5,9,21,70,56}
Dim shuffled = onlyFrom.OrderBy(Function(x) r.Next()).ToArray()
Note: Do not use New Random() in a loop
Randomize()
Dim NumberList= {1,3,5,9,21,70,56}
' Generate random value between 1 and 7, or use NumberList length to make it generic
Dim value As Integer = CInt(Int(( 7 * Rnd()) + 1))
return NumberList(value-1)
* The above code may produce the same value multiple times in a series. so if the requirement is that a different value be produced from the array each time when the code is called seven times, this wouldn't work *
If the requirement is to have a different value from the array each time for the first 7 calls, you may use Shuffle function as laid out here Shuffling an array of strings in vb.net
I want to create a random number generator in VB.NET But from my own given list of numbers
Like Chose random numbers from [1,2,3,4,5,6] e.t.c
This is how you get a random natural number in the interval of [0, n - 1]:
CInt(Rnd() * n)
Let's suppose you have a List of n elements. This is how you get a random element from it:
MyList(CInt(Rnd() * n))
Already built into .NET base of 'Random' and then extending that into your existing choices. This is NOT the same as generating the number from a Random as you are specifying YOUR OWN list first and then merely getting positioning with the help of a new Rand and using your length as a ceiling for it.
Sub Main()
'Say you have four items in your list
Dim ls = New List(Of Integer)({1, 4, 8, 20})
'I can find the 'position' of where the count of my array could be
Dim rand = New Random().Next(0, ls.Count)
'This will give a different 'position' every time.
Console.WriteLine(ls(rand))
Console.ReadLine()
End Sub
I would create a random number generator to generate a random number in the range of the list/array length, then use the result to point to the index of your number list.
Dim numbers As Integer() = New Integer() {1,2,5,6,7,8,12,43,56,67}
Dim randomKey = numbers(CInt(Rnd() * numbers.length))
*Edited based on Lajos Arpad's answer of how to get the random number
Here is the function you can try, see more here Random integer in VB.NET
Public Function GetRandom(ByVal Min As Integer, ByVal Max As Integer) As Integer
Dim Generator As System.Random = New System.Random()
Return Generator.Next(Min, Max + 1)
End Function
I'm trying to randomize a number in VB.NET 3 times. And each time I randomize a number it should be different from the other two numbers.
For example I have 3 integers. Int1,Int2 and Int3. I will randomize Int1 between 1-10 , and then I will randomize Int2 between 1-10 however the value shouldn't be equal to the value I randomized in Int1 and the same goes for Int3 it shouldn't equal to Int1 and Int2.
I have figured out how to randomize a number, this is the code I'm using:
Dim RndNumber As Random
Dim num,num2 As Integer
RndNumber = New Random
num = RndNumber.Next(1, 11)
num2 = RndNumber.Next(1, 11)
Now I'm stuck on how I make num2 randomize a number between 1-10 that is not equals to num.
I appreciate any help, thanks.
In all the examples, RNG is a random number generator created from the NET Random class:
Private RNG = New Random()
Linq
If you only need two or three, you could loop until the current pick is not in the result set. But this is even simpler using some extension methods:
Dim nums = Enumerable.Range(1, 10).
OrderBy(Function(r) RNG.Next).
Take(3).
ToArray()
This starts with all numbers between 1 and 10, puts them in random order, takes the first 3 and stores them in the nums array. I used the multiline form, breaking after the .s to illustrate the steps.
Just change the range, size/count and Take() element as needed. For instance, for something like a lottery with 5 unique numbers 1-69 (condensed form):
Dim winners = Enumerable.Range(1, 69).OrderBy(Function(r) RNG.Next()).Take(5).ToArray()
Dim powerball = Enumerable.Range(1, 26).OrderBy(Function(r) RNG.Next()).Take(1).First
Since the Powerball can be a repeat of the first numbers, it comes from its own pool. Since we only want one, we dont need an array, just the First().
Manual
It is good to know the logic for these things, so this shows a manual version. This does it differently, by picking and actually checking random values:
' picked value storage
Dim picks As New List(Of Int32)
Dim pick As Int32 ' current candidate
Do
pick = RNG.Next(1, 11)
If picks.Contains(pick) = False Then
picks.Add(pick)
End If
Loop Until picks.Count = 3
Rather than loose vars, this uses a list to hold the picks. This makes it easy to see if the current pick has already been selected. For more than just a few values, use a HashSet(Of Int32) rather than a List for performance.
Random Pairs
To create a random sets of numbers with 2 of each, such as for a matching game, just double up the base pool of values then put them in random order:
' create pool of 2 values each for 1-13
Dim nums = Enumerable.Range(1, 13).ToArray()
' concat the set to make 2 of each value, randomize
Dim pool = nums.Concat(nums).OrderBy(Function(r) RNG.Next).ToArray()
For a manual method you would have to check the count of each value in the loop.
'Use up' Picks
One more variation is when you need a pool of randoms used periodically, but you don't know how many you will need in advance. Examples would be the balls for a BINGO game or a deck of cards.
Rather than a global indexer pointing to the last slot used (or next slot to use), a Stack(Of T) (or a Queue) will "use up" values as you need them:
' create, randomize pool of 100 ints
Dim nums = Enumerable.Range(1, 100).OrderBy(Function(r) RNG.Next).ToArray
' use array to create Stack<T>
Dim shoe As New Stack(Of Int32)(nums)
' same as:
Dim shoe = New Stack(Of Int32)(Enumerable.Range(1, 100).
OrderBy(Function(r) RNG.Next).ToArray())
This starts basically the same with 100 integers, randomized and stored in an array, but there is no Take(n) because we want them all. They values are then stored in a stack collection. Using it:
Console.WriteLine(shoe.Count)
For n As Int32 = 1 To 3
Console.WriteLine("Picked #{0}", shoe.Pop)
Next
Console.WriteLine(shoe.Count)
When you Pop a value it is removed from the collection automatically. If you use a lot of values from the shoe, you will want to check the count to make sure it is not empty.
100
Picked #12
Picked #69
Picked #53
97
After drawing 3 values, the shoe has only 97 values remaining.
Random Notes
In all cases your Random generator should be a form level object which you create once. Never create them in a loop or you will likely get the same value over and over.
The OrderBy(Function(r) RNG.Next) method of randomizing is usually good enough for casual use, but it is inefficient. If you will be randomizing large sets and/or using it frequently you should consider using a proper shuffle such as the Fisher-Yates shuffle shown here.
I want to make a random character generator with numbers in vb.net, I know how to make a random number generator but not numbers mixed with letters. I want it to be around 15-20 characters.
Something like this:
F53Gsfdsj637jfsj5kd8
Thanks ahead!
You're mostly there once you have a random number generator. From there, just pick a random character within a collection of valid characters. The simplest way would be something like:
dim validchars as string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
dim sb as new StringBuilder()
dim rand as new Random()
for i as Integer = 1 to 10
dim idx as Integer = rand.Next(0, validchars.Length)
dim randomChar as char = validchars(idx)
sb.Append(randomChar)
next i
dim randomString = sb.ToString()
Of course, clean up the syntax a bit, and maybe use a constant value for the chars and length, a variable value for the number of digits, etc.
I am using vb 2012 express (for desktop), and I was wonder how I can make unlimited variables.
For example
Dim Num1 as integer
Dim Num2 as integer
I want the application to go make a new variable with the Num3,4,5,6 etc.
Is this possible? If so, how?
Consider using and an array or a list:
Dim Num As New List(Of Integer) 'Create a list of integers
For i = 0 To Integer.MaxValue 'Add to the list as much as it can hold which is 2147483647 items, it is integer's maximum value.
Num.Add(0)
Next
'OR
Dim NumArray(Integer.MaxValue) As Integer 'Create an array of integers which holds maximum number of items, again 2147483647 items.
'Youy may access them both via their indexes:
Console.WriteLine(Num(0))
Console.WriteLine(Num(1))
Console.WriteLine(Num(2))
'or
Console.WriteLine(NumArray(0))
Console.WriteLine(NumArray(1))
Console.WriteLine(NumArray(2))
'and so on...
Btw, Console.WriteLine() converts integers to strings in this case.
This is something you need arrays for (or possibly a collection class, depending on other needs).
Something like:
Dim Idx As Integer
Dim Num(10) As Integer
' Now you can use Num(0) thru Num(10) '
For Idx = 0 To 10
Num(Idx) = 10 - Idx
Next