Randomly select an array element - vb.net

So I'm trying to select a random element and then save said element, not quite knowing as to how I would go about doing this. The first thing that came to mind, although messy to write was:
Rnd(griddata(1), griddata(2), griddata(...))
I did receive an error however from this:
Overload resolution failed because no accessible 'Rnd' accepts this
number of arguments.
The plan is to store whatever random element it chooses as memory as well.
Any help would be greatly appreciated. Thanks!

Dim myArray() As Integer = {1, 10, 12, 11, 44, 23, 2, 1, 5, 6, 2, 7}
Dim rnd As New Random
Dim randomArrayElement = myArray(rnd.Next(0, myArray.Length - 1))
Or even you can try the same from a string also
Dim chars = "0123456789"
Dim random = New Random()
Dim result = New String(Enumerable.Repeat(chars, 1).[Select](Function(s) s(randomOtp.[Next](s.Length))).ToArray())

Dim rnd = new Random()
...
Dim randomIndex = rnd.Next(0, griddata.Length)
Dim randomValue = griddata(randomIndex)
This is assuming that your array is 0-based (as .NET arrays usually are).

Related

How to get a collection of elements in my dictionary that meet a given condition?

I am going through some pluralsight videos and I found this amazing one called "Beautiful C++ 14: STL Alorithms". In this video the instructor discusses using the a variation of find_if methods like the one below.
vector<int> v{ 4, 6, 6, 1, 3, -2, 0, 11, 2, 3, 2, 4, 4, 2, 4 };
//find the first zero in the collection
auto result = find(begin(v), end(v), 0);
These methods are fantastic and I will be using it for some of my C projects, but I am currently working in a VB project where I need some kind of the same functionality.
I have a dictionary and I need to get certain objects out of it based on an if statement.
Structure Example_Struct
Public ExampleItem1 As Integer
Public ExampleItem2 As Integer
End Structure
Private Example_Dictionary As New Generic.Dictionary(Of String, Example_Struct)
Private Sub PopulateDictionaryWithDummyData()
Dim dummyData1 As Example_Struct
Dim dummyData2 As Example_Struct
dummyData1.ExampleItem1 = 1
dummyData1.ExampleItem2 = 1
dummyData1.ExampleItem1 = 5
dummyData1.ExampleItem2 = 5
Example_Dictionary.Add("Data1", dummyData1)
Example_Dictionary.Add("Data2", dummyData2)
End Sub
Private Sub LoadData()
PopulateDictionaryWithDummyData()
Dim stIdx As Integer
Dim myStruct As New Example_Struct
Dim item1 As Integer = 5
Dim item2 As Integer = 5
Dim count As Integer = Example_Dictionary.Count
For stIdx = 1 To count
' Get the stand data
myStruct = Example_Dictionary.ElementAt(stIdx).Value
If (myStruct.ExampleItem1 = item1 And myStruct.ExampleItem1 = item2) Then
' Do Something
End If
Next
End Sub
Above is some sample code to test with were I populate my Example_Dictionary with some dummy data. Then loop through the dictionary and put the comment where I need to do some things.
I would like my code to take the for loop out of the picture completley, just grab the "Example_Struct" that matches my conditions.
If there are more than one "Example_Struct" that matches my condition, I would need it to return a collection of these.
To filter the dictionary values based on a certain condition, you may use something like the following:
Dim myStructs = Example_Dictionary.Values.
Where(Function(x) x.ExampleItem1 = item1 AndAlso x.ExampleItem2 = item2).ToList()
Note that when dealing with logical operations, it's always a good idea to use the short-circuit logical operators (i.e., AndAlso instead of And and OrElse instead of Or). You can learn more about the difference in this guide:
Logical and Bitwise Operators in Visual Basic

VB.Net equivalent of Javascript's .Map function

Given an array of strings, say: Dim array1 As String() = {"1", "2", "3"} what is the best way to copy that array and perform an action on each element?
In other words, what is the best way to copy that array to come up with: array2 as integer() = {1, 2, 3}
For example, something similar to JavaScript's .Map function:
var numbers = [4, 9, 16, 25];
function myFunction() {
x = document.getElementById("demo")
x.innerHTML = numbers.map(Math.sqrt);
}
// Result: 2, 3, 4, 5
If it isn't possible in one line - as I suspect it isn't - what is your quickest alternative? Thanks!
If you don't want to use any LINQ extension methods, but you are okay with using lambda expressions, you can still do it in one line using Array.ConvertAll:
Dim input() As String = {"1", "2", "3"}
Dim output() As Integer = Array.ConvertAll(input, Function(x) Integer.Parse(x))
However, it does beg the question: why not just use LINQ, at that point, since it's effectively the same thing:
Dim input() As String = {"1", "2", "3"}
Dim output() As Integer = input.Select(Function(x) Integer.Parse(x)).ToArray()
The classic imperative way to do this in VB, without using LINQ or lambdas, would be a for-loop:
Dim input() As String = {"1", "2", "3"}
Dim output(LBound(input) To UBound(input)) As Integer
For i As Integer = LBound(input) To UBound(input)
output(i) = Integer.Parse(input(i))
Next
I would like to add that, similar to JavaScript, .NET's map equivalent Select also supports method groups as well as lambdas.
Here's an example using a lambda:
Dim output = input.Select(Function(x) SomeMethod(x)).ToArray()
Here's an example using a method group. Since parenthesis on method invocations are optional in VB.NET, the additional AddressOf keyword is required:
Dim output = input.Select(AddressOf SomeMethod).ToArray()
For completeness, here's an example using the LINQ query syntax, which is just syntactic sugar for the first example:
Dim output = (From x In input Select SomeMethod(x)).ToArray()
If you don't want to use LINQ here is the classic way, a loop:
Dim numbers = {4, 9, 16, 25}
For i As Int32 = 0 To numbers.Length - 1
numbers(i) = CInt(Math.Sqrt(numbers(i)))
Next

Object reference not set to an instance of an object while assinging value to byte object

I am trying to read byte array and i want to store first value of array in list. I tried one small console application example but i got above issue. I searched a lot on internet but didnt get answer
Sub Main()
Dim lData As New List(Of Byte)
Dim lBuffer() As Byte = {5, 99, 4, 7}
Dim a() As Byte
For ReadValue As Integer = 0 To lBuffer.Length
a(0) = lBuffer(ReadValue)
Exit For
Next
lData.AddRange(a)
End Sub
Your problem here is that you have declared the array but you have not initialized it. By declaring a variable with Dim a() As Byte, you have said "This thing exists and here's what it looks like". However, you haven't actually provided anything that will occupy the definition of a(), or in other words you haven't instantiated it yet.
Think of it this way. I tell you that apples exist and that they look like oddly shaped red orbs, there are seeds inside of them, and they are edible. Now I'm going to tell you to take all of the seeds out of the apple and eat the apple. Picking seeds out of an apple is completely possible, and eating apples is also possible. One problem though, you can't do what I told you. Why? Because I never gave you an apple to do those things with.
To be more specific in regards to you question, You have created an array of bytes with Dim a() As Byte. That's the first step, you told it "Hey, this is going to be a collection of things and all of those things are going to be a Byte". The main problem with arrays in the way you used it is that arrays need to know how big they are when you use them. So you have two options, you can either a) declare the array with a size which will create an empty array where all elements are null or b) you can do it like you did and then assign an array that has already been defined to it.
I'll give you examples of both the methods:
Sub Main()
Dim lData As New List(Of Byte)
Dim lBuffer() As Byte = {5, 99, 4, 7}
' Tell the array how big to be in the first place
Dim a(lBuffer.Length - 1) As Byte
For ReadValue As Integer = 0 To lBuffer.Length - 1
a(ReadValue) = lBuffer(ReadValue)
Next
lData.AddRange(a)
End Sub
Sub Main()
Dim lData As New List(Of Byte)
Dim lBuffer() As Byte = {5, 99, 4, 7}
Dim a() As Byte
' Lets create a temporary list and then use the .ToArray function
' which will return an already instantiated array.
Dim byteList as new List(of Byte)
For ReadValue As Integer = 0 To lBuffer.Length - 1
' Add each item to the list
byteList.Add(lBuffer(ReadValue))
Next
' Now, convert the list to an array and set it to a()
a = byteList.ToArray
lData.AddRange(a)
End Sub
Either of those options should stop the NullReferenceException error you are receiving. However you already have a List(of Byte) defined and instantiated, so the easiest option would probably be just assigning the values to the list directly:
Sub Main()
Dim lData As New List(Of Byte)
Dim lBuffer() As Byte = {5, 99, 4, 7}
For ReadValue As Integer = 0 To lBuffer.Length - 1
lData.Add(lBuffer(ReadValue))
Next
End Sub
Or even shorter code would be to use a Lambda expression:
Sub Main()
Dim lData As New List(Of Byte)
Dim lBuffer() As Byte = {5, 99, 4, 7}
lBuffer.ToList.ForEach(Sub(x) lData.Add(x))
End Sub
However the shortest possible answer to achieve the same thing would be to use the .ToList extension directly:
Sub Main()
Dim lData As List(Of Byte)
Dim lBuffer() As Byte = {5, 99, 4, 7}
lData = lBuffer.ToList()
End Sub
After re-reading this, I thought of an even shorter version. You can cut out the middleman of the byte array completely and just instantiate the List(Of Byte) from your array list.
Sub Main()
Dim lData As New List(Of Byte) From {5, 99, 4, 7}
End Sub
And I believe that's the shortest possible way to do it. If someone can prove me wrong though, I'd love to learn.

Convert integer array to string array

whats the easiest way to convert an array of integers into string form? I'm trying to copy the whole array of integers into strings.
{1, 2, 3}
to
{"1", "2", "3"}
The easiest method would be to use the Select extension method which is provided by LINQ:
Dim intArray() As Integer = {1, 2, 3}
Dim strArray() As String = intArray.Select(Function(x) x.ToString()).ToArray()
If you don't want to, or cannot use LINQ, you can use the Array.ConvertAll method, which is almost as easy:
Dim strArray() As String = Array.ConvertAll(Of Integer, String)(intArray, Function(x) x.ToString())
EDIT
Based on your comments, below, it looks like you need to convert from an ArrayList of integers to an ArrayList of strings. In that case, you could do it like this:
Dim intArray As New ArrayList({1, 2, 3})
Dim strArray As New ArrayList(intArray.ToArray().Select(Function(x) x.ToString()).ToArray())
Although, at that point, it's starting to get a bit messier. It's probably easier to just do a standard loop, like this:
Dim myArray As New ArrayList({1, 2, 3})
For i As Integer = myArray.Count - 1 To 0 Step -1
myArray(i) = myArray(i).ToString()
Next
For what it's worth, though, unless you are still on a really old version of the .NET Framework, you really ought to be using the List(Of T) class rather than the ArrayList class, in most cases.

VB.NET - Array of Integers needs to be instantiated, how to?

First try
Dim holdValues() As Integer 'Doesn't Work
holdValues(1) = 55
Second try
Dim holdValues(-1) As Integer 'Gives me Index was outside the bounds of the array.
holdValues(1) = 55
I'm trying to do something similar to
Dim myString(-1) As String
But apparently this doesn't apply to integer arrays. I don't know what the size of the array will be, it wont get smaller but it will grow larger.
Any help will be appreciated, thank you!
You could use the Initializers shortcut:
Dim myValues As Integer() = New Integer() {55, 56, 67}
But if you want to resize the array, etc. then definately have a look at a List(Of Integer):
'Initialise the list
Dim myValues As New System.Collections.Generic.List(Of Integer)
'Shortcut to pre-populate it with known values
myValues.AddRange(New Integer() {55, 56, 57})
'Add a new value, dynamically resizing the array
myValues.Add(32)
'It probably has a method do do what you want, but if you really need an array:
myValues.ToArray()
you add the number to
holdValues(x) //x+1 will be size of array
so something like this
Dim array(2) As Integer
array(0) = 100
array(1) = 10
array(2) = 1
you can re-allocate the array to be bigger if needed by doing this.
ReDim array(10) as Integer
you'll have to add in your code when you should make your array bigger. You can also look into lists. Lists take care of this issue automatically.
here's some info on Lists: http://www.dotnetperls.com/list-vbnet
Hope this helps.
Also a link for general knowledge on arrays http://www.dotnetperls.com/array-vbnet