How to calculate average of arrays from array list? - vb.net

I have an ArrayList in VB.NET.
For example ArrayList has two arrays: AList(arr,arr):
Dim AList As ArrayList = New ArrayList((1,2,3,4,5,6,7,8,9,10)
(2,3,4,5,6,7,8,9,10,11))
All I want is average of given arrays so:
So final Array will be (1.5,2.5,3.5,4.5,5.5.........10.5)
Note: Arraylist count and length of arrays will variable.
I tried the following code:
For k = 0 To 9
Dim sum As Short
Dim a As Array
For z = 0 To 1
sum = sum + AList.Item(a(k))
Next
finalarr(k) = sum / 2
RichTextBox1.AppendText(finalarr(k))
Next

Dim i As Integer = 0
Dim count As Inetger = 0
Dim avgList As List(Of Integer) = New List(Of Integer)()
For Each arr As Integer() In AList
i = 0
count += 1
For Each thing as Integer In arr
i += 1
If avgList.Count >= i Then
avgList.Item(i) = ((avgList.Item(i) + thing) / count)
Else
avgList.Add(i)
End If
Next
Next

Related

Unable to edit array data in For Each Loop

Like title, running this code shows an array with all 0 values in it.
I have tried using integer array too but I can't
Dim woohoo(9) As String
Dim count As Integer = 2
For Each number As String In woohoo
number = CStr(count)
count += 2
Next
For Each number As Integer In woohoo
Console.WriteLine(number)
Next
2,4,6,8,10...20
You need to do this to SET the values of an array:
Dim wooho(9) As Integer
Dim count As Integer = 2
For i As Integer = 0 To wooho.Count - 1
wooho(i) = count
count += 2
Console.WriteLine(wooho(i))
Next
And this to GET the values:
For Each number As Integer In wooho
Console.WriteLine(number)
Next
I suggest using a list of Integers for this.
Try this:
Dim woohoo As New List (Of Integer)
Dim count As Integer = 2
For i As Integer = 0 To 9
woohoo.Items.Add (count)
count += 2
Next
For Each number As Integer In woohoo
Console.WriteLine(CStr(number))
Next

Count a specific string in a multiline textbox (VB.Net)

I very much want to count the values in a multiline textbox each time each value appears in descending order> in ascending order. I tried a lot but nothing works as it should. (VB.Net)
Textbox1.Lines
2
3
2
2
4
7
7
7
28
28
Expected Output: Textbox2.Lines
2 = Count = 3
7 = Count = 3
28 = Count = 2
3 = Count = 1
4 = Count = 1
What i try and dind't worked.
#1
Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
Dim cnt As Integer = 0
For Each c As Char In value
If c = ch Then
cnt += 1
End If
Next
Return cnt
End Function
#2
Dim a As String = "this is test"
Dim pattern As String = "t"
Dim ex As New System.Text.RegularExpressions.Regex(pattern)
Dim m As System.Text.RegularExpressions.MatchCollection
m = ex.Matches(a)
MsgBox(m.Count.ToString())
#3
Public Shared Function StrCounter(str As String, CountStr As String) As Integer
Dim Ctr As Integer = 0
Dim Ptr As Integer = 1
While InStr(Ptr, str, CountStr) > 0
Ptr = InStr(Ptr, str, CountStr) + Len(CountStr)
Ctr += 1
End While
Return Ctr
End Function
You need to remember which strings have already appeared and then count them. To do that, you can use a dictionary.
Dim dict_strCount As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)()
' Run over each line in the input
For Each line As String In tb_yourTextBox.Text.Lines
' Check if we have already counted the string in this line
If dict_strCount.ContainsKey(line) Then
dict_strCount(line) += 1 ' if so, increment that count
Else
dict_strCount.Add(line, 1) ' if not, add it to the dictionary (with count of 1)
End If
Next
tb_yourOutputTextBox.Text = String.Empty ' clear the output
' run over all the elements in the dictionary in ascending order by value
' and output to the output textbox
For Each kvp As KeyValuePair(Of String, Integer) In dict_strCount.OrderBy(Function(x) x.Value)
tb_yourOutputTextBox.Text += kvp.Key & ": " & kvp.Value.ToString() & vbNewLine
Next
You may test it here

VB.net Histogram - how to bin data

I'm working on a histogram class and in particular a binning method.
In relation hereto I have two questions:
Is it a right/appropriate algorithm seen from a logic/statistical point of view
Is the code optimal or at least decent - please tell me how to improve it
Any help is highly appreciated - thx in advance.
Here is my code so far...
Public Class Histo
Dim data() As Double
Dim bins As Integer = 0
Dim bw As Double = 0
Dim _min As Double = 0
Dim _max As Double = 0
Dim arrMax As Double = 0
Dim cht As Chart
Public shared Decimals As Integer
Public Sub New(_arr() As Double, _cht As Chart)
'One-dimensional array as data
data = _arr
'No of bins with Sturges method
bins = NoBin_ST(data)
'calculate bin width
bw = Range(data) / bins
'bin boundries for first bin
_min = Min(data)
_max = _min + bw
'max of data
arrMax = Max(data)
'chart object
cht = _cht
'no of decimals on x-axis
Decimals = Dec
End Sub
Public Function Binning() As Integer()
'Binning "algorihtm" for continuous data
'
'RETURN: one-dimensional array with n bins
'
Array.Sort(data)
Dim j As Integer = 0
Dim mn As Double = _min
Dim mx As Double = _max
Dim counter(bins-1) As Integer
For i As Integer = 0 To data.GetLength(0)-1
'check if data point is within the boundries of the current bin
If data(i) >= mn AndAlso data(i) < mx Then
'add counter in current bin
counter(j) += 1
Else
'special case: at the end at least one data point will equal max of the last bin
' and must be counted in that bin
If data(i) = arrMax Then
counter(j) += 1
Continue For
End If
'the data point has exceeded the boundries of the previous bin
' and must be counted in the next bin
'min and max is increased with the bin width
mn += bw
mx += bw
'go to next bin
j += 1
'count data point in this bin and loop again
counter(j) += 1
End If
Next
Return counter
End Function
.....
Not sure if this is any more performant, but I think it is a bit simpler.
Function CreateBins(values As IEnumerable(Of Double), numberOfBins As Integer) As IGrouping(Of Integer, Double)()
If values Is Nothing Then Throw New Exception("Values cannot be null")
If values.Distinct.Count < 2 Then Throw New Exception("Values must contain at least two ditinct elements")
If numberOfBins < 1 Then Throw New Exception("numberOfBins must be an integer > 1")
Dim min = values.Min
Dim max = values.Max
Dim binSize = (max - min) / numberOfBins
' Checking for two distinct elements should eliminate possibility of min=max and therefore binsize=0
Dim bins = values.GroupBy(Function(x) Convert.ToInt32(Math.Floor((x - min) / binSize))).ToArray
' Group counts available using the ienumerable Count function
' Dim counts = bins.Select(Function(x) x.Count)
' Or retaining the group key
' Dim counts = bins.Select(Function(x) New With {Key x.Key, x.Count})
Return bins
End Function
Each bin is now a group. The original values are retained as part of the group, allowing potential follow up analysis. Count is available using the group function Count()

VB.net Error when storing lists in array

I have the following code, the objective of it is to take an initial list and to take each element within the list and store it in an array of lists, with each list in the array, holding each element in its own list. For instance
The list 2, 2, 3, 3, 3, 3, 5, 5, 7, 9, 9. Would create five lists:
List 1: 2, 2
List 2: 3, 3, 3, 3,
List 3: 5, 5
list 4: 7
List 5: 9, 9
This is my current code:-
Dim cnt As Integer = 0
Dim lists(uniqueFactors.Count) As List(Of Integer)
Dim saver As Integer = factors.Item(0)
Console.WriteLine(saver)
For Each i In factors
lists(cnt).Add(i)
If saver <> i Then
cnt = cnt + 1
End If
saver = i
Next
Thanks all in advance!
You'd probably be better off using a Dictonary<TKey, TValue>.
Dim storage As New Dictionary(Of Integer, Integer)
' Number Occurrences
' | |
storage.Add(2, 2)
storage.Add(3, 4)
storage.Add(5, 2)
storage.Add(7, 1)
storage.Add(9, 2)
You can iterate the list like this:
For Each item As KeyValuePair(Of Integer, Integer) In storage
Dim number As Integer = item.Key
Dim occurrences As Integer = item.Value
Next
Get the number of occurrences for a given number like this:
Dim number As Integer = 9
Dim occurrences As Integer = storage(number) 'Return: 2
Change the number of occurrences:
storage.Item(number) = 4 'Set to 4
storage.Item(number) += 1 'Increase from 2 to 3
storage.Item(number) -= 1 'Decrease from 2 to 1
Create an enumerator, array and/or list of occurrences for a given number:
Dim iterator As IEnumerable(Of Integer) = Enumerable.Repeat(number, occurrences).ToList()
Dim array As Integer() = Enumerable.Repeat(number, occurrences).ToArray()
Dim list As List(Of Integer) = Enumerable.Repeat(number, occurrences).ToList()
You can also write an extension method:
Public Module Extensions
<System.Runtime.CompilerServices.Extension()>
Public Function ToList(Of TKey)(source As Dictionary(Of TKey, Integer), key As TKey) As List(Of TKey)
Return Enumerable.Repeat(key, source.Item(key)).ToList()
End Function
End Module
Now you create a list by simply writing:
Dim occurrences As List(Of Integer) = storage.ToList(number)
Why not use a List of Lists like this?
Dim last As Integer
Dim first As Boolean = True
Dim ints As List(Of Integer)
Dim lists As New List(Of List(Of Integer))
For Each i In factors
If first Then
first = False
ints = New List(Of Integer)
ints.Add(i)
lists.Add(ints)
last = i
ElseIf i = last Then
ints.Add(i)
Else
ints = New List(Of Integer)
ints.Add(i)
lists.Add(ints)
last = i
End If
Next

For loop make new variables for you - VB.Net

I'm trying to make a for loop for will make a new variable for me, every step. I want something like this. What ever step I am on, say, x = 2, it Dims newVar2, if x = 3: Dim newVar3
Is there any way to do that? I was hoping something like, Dim newVar & x would work, but of course now.
I was trying to do it as an array, but I'm not sure how to do that, or ReDimming, so examples would be great!
To create a collection of variable values inside a for loop, you should use a List(Of t) object or something similar (For Example Dictionary).
To do this with a List(Of t) you can do the following :
Dim varList As New List(Of Integer)
For i As Integer = 0 To 10
varList.add(i)
Next
Or if you want to do it with the variable names you mentioned, try :
Dim varList As New List(Of String)
For i As Integer = 0 To 10
varList.add("newVar" & i)
Next
To retrieve the value from a List use the following : Dim result As String = varList(0)
Alternatively you can use a Dictionary object to store Key/Value pairs :
Dim varList As New Dictionary(Of String, Integer)
For i As Integer = 0 To 10
Dim k As Integer = 0
varList.add("newVar" & i, k)
Next
Becareful though as a Dictionary object can only contain unique Keys. To return the value find it as : Dim result As Integer = varList("newVar0")
basic array:
Dim Arr(1000) As Integer
For i As Integer = 0 To 999
Arr(i) = YYYYY
Next
trick for dynamic size:
Dim max As Integer = XXXXXX
Dim Arr(1000) As Integer
For i As Integer = 0 To max
'if too small, Increasing array without loss old data
If Arr.Length = i Then
ReDim Preserve Arr(Arr.Length + 1000)
End If
Arr(i) = YYYYY
Next
or, use list:
Dim max As Integer = XXXXXX
Dim list As New List(Of Integer)
For i As Integer = 0 To max
list.Add(YYYYY)
Next
The other answers are technically correct, but you probably don't need the iteration loops. You can probably do this in a single line of code:
Dim varList As Dictionary(Of String, String) = Enumerable.Range(0, 10).ToDictionary(Function(k) "newVar" & k, Function(v) "Some value for newVar" & v)
Dim myInts As New List(Of Int)
For i = 0 To 10
myInts.Add(i)
Next