Adding All Numbers In a Array - arrays

I have a Array filled with 24 numbers an I would like all the numbers to be added together and then displayed in a text box. This is the code I have created for the array. but I'm not sure how to add all the numbers in the array together. thank You for Your Time.
'Calculating distances
Dim Game As String
Game = txtGameAdd.Text
SystemValueGame = SystemValueGame + 1
TotalGames(SystemValueGame) = Game
txtGameAdd.Text = ""
txtGameAdd.Focus()
'Keeping count with lables'
lblAmountNum.Text = SystemValueGame
'Double Checking SystemValue'
If SystemValueGame = 24 Then
'notify when array is full'
MsgBox("Entered Max Amount Of Surnames", MsgBoxStyle.Information)
txtGameAdd.Text = " "
txtGameAdd.Enabled = False
End If

You could probably do something very similar to this.
Dim ar As Array = Nothing
Dim sum As Integer = 0
For Each st As String In ar
sum = sum + CInt(st)
Next
A method such as this, will access every value of the array and add them together.

Related

How can I calculate the average of 1 variable of Array of Custom Type

This is a tricky one for me to explain, so I'll start with the code I have so far, and later with what I am trying to achieve.
Current Code
Option Explicit
Public eSigTickerArr As Variant
' Public type to save array
Type Watchlist
eSigTicker As String
Op As Double
Hi As Double
Lo As Double
Cl As Double
Vol As Double
BarTime As Variant
End Type
Public WatchlistArr() As Watchlist ' save an array of special type "Watchlist"
'====================================================================
Sub Mainr()
ReDim WatchlistArr(0) ' init array size
eSigTickerArr = Array("Part1", "Part2", "Part3")
For Each eSigTickerElem In eSigTickerArr
' check if first member of array is occupied
If WatchlistArr(0).eSigTicker <> "" Then ' not first time running this code >> increase array size by 1
ReDim Preserve WatchlistArr(UBound(WatchlistArr) + 1) ' increase array size by 1
End If
' ... Some Code, working fine ....
' populate array Type with data (also works)
With WatchlistArr(UBound(WatchlistArr))
.eSigTicker = eSigTickerElem
.Op = LastCSVLine(2)
.Hi = LastCSVLine(3)
.Lo = LastCSVLine(4)
.Cl = LastCSVLine(5)
.Vol = LastCSVLine(6)
.BarTime = LastCSVLine(1)
End With
Next eSigTickerElem
' ******* calculate the average of only "Hi" ******
Dim myAvg
myAvg = WorksheetFunction.Average(WatchlistArr.Hi) '<--- Getting an Error !
End Sub
I'm getting an error at the line above.
My Challenge: I want to get the average only of a certain variable of my type array WatchlistArr, and I don't want to use a loop, as there can be 10,000 records (or more).
Is there any way to get the value with the Average function ?
Should I switch to 2-D array ? or Maybe 3-D array ?
myAvg = WorksheetFunction.Average(WatchlistArr.Hi) '<--- Getting an Error !
Yep. What this code means to do is similar to this:
myAvg = watchListArr.Select(item => item.Hi).Average();
Where item => item.Hi is a selector function that is invoked for every item in watchListArr. The only problem is that this is LINQ / C#, not VBA. VBA doesn't support delegates and other funky stuff even C# couldn't dream to do in v1.0.
But VBA has control flow structures that let you perform an action for every item in an array: use a For loop!
Dim i As Long, total As Double, count As Long
For i = LBound(watchListArr) To UBound(watchListArr)
total = total + watchListArr(i).Hi
If watchListArr(i).Hi <> 0 Then count = count + 1 'assuming zeroes are excluded
Next i
If count <> 0 Then myAvg = total / count
If you want to use Application.WorksheetFunction.Average, you'll need to copy the Hi member of every item in your array into its own array, and give it that array - and that will require... a loop... which is wasted cycles if that loop isn't also computing the average as it goes.
As long as you're not using a For Each loop to iterate the array, you'll do fine. Iterating a 30K items array with a For loop is pretty much instant, no worries there.
You could define WatchlistArr as a 2-D array and then try this logic:
Dim myArray As Variant
myArray = Application.WorksheetFunction.Index(WatchlistArr, 0, 2)
This will return column 2 as as array, which can be passed into the Average method:
myAvg = WorksheetFunction.Average(myArray)

Modal Value, and Repetition

I want to make a modal value calculator, So it calculates the Modal value and its repetition
The idea is to make a list of data and its repetition like shown in any Graph.
This is code you I start with:
Public Class
Dim a1(100), a2(100), Rep(100), RepMer(100), AMer(100) As Single, n, count, m As Single, z, k, c, mars As Integer
n = InputBox("How many data?", "RepTest")
count = 0
For count = 0 To n - 1
a1(count) = InputBox("Add Value", "RepTest")
Next
z = n
For run = 0 To n - 1
mars = c
z = z - 1
k = 0
For moon = 0 To (n - 1)
If a1(z) = a1(moon) Then
k = k + 1
a2(run) = a1(z)
Rep(run) = Rep(run) + k
If Rep(run) > 2 Then
Rep(run) = Rep(run) - 1
End If
End If
Next
MsgBox(a2(run)), , "Modal Value")
MsgBox(Rep(run)),, "Repetition")
Next
End Class
However, If you make the massage box outside the main 2nd loop, you have to make another loop with the same value 0 To (n-1), to match data position in an Array.
what I want you to help me please is:
I have to save the modal value and the repetition of one value in same position in the array, because if you use this code the output of n = 5 and enter value 2 ,2 ,2 ,1,1. the output will be 5 massage box with 3 equal for value 2, and 2 equal for value 1.
you can test by yourself copy the code and insert it to a form in VB.net.
With pictures:
see this link: Picture that describe the result
You can see that the output is more than one for each value, so How can I store the value and its repetition in one position in an array?
Thank you for reading, please I want a code answer. :)
UPDATE
If you want count duplicates(repetitions) of values and then use it for your needs:
Create custom class where you can keep information about value and amount of repetitions
Public Class RepetitionValue
Public Property Value As Single
Public Property RepetitionAmount As Int32
Public Sub New(value As Single)
Me.Value = value
Me.RepetitionAmount = 1
End Sub
End Class
Collect values and count duplicates, save it in then Directory collection
With Directory you will easy get object by value
Use collection for manipulating data
Public Sub YourSybName()
Dim values As New List(Of Single)()
Dim numberOfData As Int32
numberOfData = Int32.Parse(InputBox("How many data?", "RepTest"))
For count As Int32 = 0 To numberOfData - 1
values.Add(InputBox("Add Value", "RepTest"))
Next
Dim modals As New Dictionary(Of Single, RepetitionValue)()
For Each value As Single In values
If modals.ContainsKey(value) = True Then
modals(value).RepetitionAmount += 1
Else
modals.Add(New RepetitionAmount(value))
End If
Next
'Use collection for your needs
'For example if I have 5 data, then I enter 1 . 5 . 1 . 2 . 1.
'then I want to divide repetition of value 1 by repetition of value 5.
Dim valueOf1 As RepetitionValue = modals(1)
Dim valueOf5 As RepetiotionValue = modals(5)
Dim divideResult As Decimal = valueOf1.RepetitionAmount/valueOf5.RepetitionAmount
End Public

VBA - struggling to calc and write StDev data into an array with a For Next loop

11/24/14 - as per below.....
Still trying to figure this out - might it be easier by creating a smaller array which could roll through the larger array? ...then any necessary calcs could be done on the entirety of the small array.
I cannot figure out how to isolate just a (rolling) subset of an array. The rolling subset could be used for moving averages, standard devs, max/min, etc.
11/21/14 - I have made several attempts, this is the latest iteration. It shouldn't produce meaningful output until the minimum periods have been looped thru (stdev_periods = 10).
--pct_chg_array() is an array which holds percent change data from i=2 to i = 2541... declared as variant
--stdev_periods = 10 ...declared as integer
--i is a counter ...declared as integer
--stdev_array() is an empty array which I hope to populate with a standard deviation calculation for a rolling n period range ...declared as variant
--Option Base 1 and Option Explicit are on
For i = 2 To 2541
If IsNumeric(i) And i <> 0 Then
stdev_array(i, 1) = Application.WorksheetFunction.stdev(Range(pct_chg_array(i, 1).Offset(-stdev_periods, 0), pct_chg_array(i, 0)))
Else
stdev_array(i, 1) = 0
End If
Next i
Any guidance would be immensely appreciated. Thanks!
----EDIT----
Just to simplify, this is how I would express it in a worksheet formula...
=IF(ISNUMBER(OFFSET($E3,-stdev_periods+1,0)),STDEV(OFFSET($E3,0,0,-stdev_periods)),0)
...with "stdev_periods" = 10 and column E holding 1 period %chg data (ie =$E3/$E2-1).
Put this function in the module:
Public Function Slice(vntInputArray As Variant, lngStartIndex As Long, lngEndIndex As Long)
'Use to return an arbitrary-sized subset from a 1 dimensional array.
'Assumes developer is using Option Base 1
Dim vntSubArray() As Variant, lngInputIndex As Long
Dim lngElementCountIndex As Long: lngElementCountIndex = 1
For lngInputIndex = lngStartIndex To lngEndIndex
ReDim Preserve vntSubArray(lngInputIndex)
vntSubArray(lngElementCountIndex) = vntInputArray(lngInputIndex)
lngElementCountIndex = (lngElementCountIndex + 1)
Next lngInputIndex
Slice = vntSubArray
End Function
Adding the function to your code:
For i = 2 To 2541
If IsNumeric(i) And i > stdev_periods Then 'Using greater than to account for Option Base 1
stdev_array(i, 1) = WorksheetFunction.stdev(Slice( pct_chg_array, (i -stdev_periods), i))
Else
stdev_array(i, 1) = 0
End If
Next i

convert saved string of numbers into an array of integers

i have a comma separated string of numbers inside of a var named num_str
the contents of num_str looks like this: "1,2,3,4,5" etc
i am looking for a way to add num_str to an expression to convert the sting of numbers contained therein to an array of integers
i want to make sure i can simply reference 'num_str' to get the numbers from instead of spelling it out like {"1,2,3,4,5"}
i have tried this, where 'num_str' contains the numbers
Dim test As String = Nothing
Dim result() As Integer = Int32.TryParse(num_str.Split(","c))
For i = 0 To result.Length - 1
test += result(i)
Next
but that doesn't work
what i am looking for is a result with an array of numbers
Dim totalValue = str.
Split(","c).
Select(Function(n) Integer.Parse(n)).
Sum()
Try this to create integer array
Dim numbers = str.Split(","c).[Select](Function(n) Integer.Parse(n)).ToList()
Then you can use the loop you are using at the moment to append value to string
You can do it like this:
Dim num_str As String = ...
Dim str() As String = num_str.Split(",")
Dim result(str.Length - 1) As Integer
For i = 0 To str.Length - 1
result(i) = str(i)
Next
I was just working on this for a client, and I found an elegant little piece of code that will replace your single string value and effectively convert it to integer (or more precisely "double") very easily, and can be used for "find and convert" just as easily. I wrote a bunch of these into a GPA calculator that changes the letter grade entered into the GPA number format for math conversion and display without anything else but these three lines and a little loop.
For m = 0 To UBound(myArray)
myArray(m) = Replace(myArray(m), "thisstring", 0.0) 'integer 0.0 can be any
Next m

How to join strings together

I have a string array called hexsub, each "instance" of the array holds 2 characters. I made a new array called finalhex, i wanted that each "instance" of the new array held 2 of the previous, so: hexsub(0)=06, hexsub(1)=AF, then finalhex(0)=06AF. How can i do this?
The join function will join all the elements of the array regardless of how many there are within reason of course.
finalhex(0) = Join(hexsub,"")
or to split them up in pairs, something like this might work:
For I = 0 to hexsub.Count-1 Step 2
finalhex(I/2) = hexsub(I).Trim + hexsub(I+1).Trim
Next
Now each element of finalhex will contain 2 concatenated elements of hexsub
'assuming an even number of array elements
Dim NumberOfCombinedElements as Integer = hexsub.count / 2
Dim FinalHex(NumberOfCombinedElements ) as string
for I as integer = 0 to NumberOfCombinedElements - 1
finalhex(I) = hexsub(I*2) & hexsub(I*2 + 1)
next

Resources