Array Calculation with CSV file - vb.net

I am trying to work with taking in and parsing CSV files. Right now I have it taking in and producing something like this:
The program loads the csv and copies the data into an array as such:
ReDim strarray(num_rows, num_cols)
For x = 0 To num_rows
strline = strlines(x).Split(",")
For y = 0 To num_cols
strarray(x, y) = strline(y)
Next
Next
The CSV file data is very basic formatted with two columns and x number of rows:
212, 343
324, 232
etc. I guess my main problem is trying to perform calculations to all values in a specific column. To start I am just trying to figure out how to isolate the columns and found that by using MsgBox(strarray(x, num_cols)) it will msgbox everything in the second column twice. I just want to try and understand how I can perform a basic calculation like multiply every value in the first column by 2 and every value in the second column one by 3.

To start with: In VB arrays go from 0 to number of items minus 1. However you will have specify the maximum index, not the size:
Dim x As String() = new String(N-1) 'Where N is the number of items.
Dim y As String() = new String(MAX) 'Where MAX is the highest index.
And you have integer numbers. So you would have to declare:
Dim matrix As Integer(,) = new Integer(num_rows-1, num_cols-1)
And then fill it with:
For row As Integer = 0 To num_rows-1
Dim strline As String() = strlines(row).Split(",")
For col As Integer = 0 To num_cols-1
matrix(row, col) = Integer.Parse(strline(col))
Next
Next
Example calculation:
For row As Integer = 0 To num_rows-1
matrix(row,0) *= 2
matrix(row,1) *= 3
Next

Related

Ranking a dynamic table range by size

I have a dynamic table range of certain values (amounts). These amounts are generated into the table through a macro I've created.
What I want to do: Rank these amounts into the empty column by number.
eg. the cell in Column G next to 89k would be ranked as 1, one next to 77k would be 2 etc.
I also already have other functions defined, which I'm not going to explain here for readability reasons, but all you need to know: there are two variables obtained through functions
tbl_first = (int) Index of the ListRow of the first table item (so in this case it would be the row with 89k = 1st row so in this example 1)
tbl_last = (int) same as above, but indexes the last row (77k) in this example as 7
so my code is the following
' sets the tbl variable to the red table in the picture
Dim tbl As ListObject: Set tbl = Sheets("Summary").ListObjects("time_top")
Dim pos As Integer, diff as integer
diff = tbl_last - tbl_first
For j = tbl_first To tbl_last ' loops through all the added rows
For n = 1 to diff' indexing for the large function
' index the pos through the excel large function for our values (should return the k-th position from the largest value)
pos = Application.WorksheetFunction.Large(Range(Cells(tbl_first, 6), Cells(tbl_last, 6)), n)
With tbl.ListRows(1)
.Range(j, 6) = pos ' add the value to the column G to the right
End With
Next n
Next j
So the expected result would look like this:
I also keep getting the following error, which is caused by me incorrectly assigning the pos value.
Either way, probably multiple of things wrong here and much more elegant solution is out there, that just didn't hit me yet.
Think you need Rank (watch out for equal ranks). Large returns the nth largest value of a set.
Here is a simple example on a two column table which perhaps you can adapt. The rank is added in the second column.
Sub xx()
Dim tbl As ListObject: Set tbl = Sheets("Summary").ListObjects("time_top")
Dim r As Range
For Each r In tbl.ListColumns(1).DataBodyRange
r.Offset(, 1) = WorksheetFunction.Rank(r, tbl.ListColumns(1).DataBodyRange)
Next r
End Sub

Visual Basic- Random Numbers

I'm trying to generate 5 random numbers from 1-99 and display them in a ListBox. Can someone tell me where I'm going wrong? Right now my code is displaying all 99 numbers in the ListBox, but I only want 5 of them to display. Here is the code:
'list to store numbers
Dim numbers As New List(Of Integer)
'add desired numbers to list
For count As Integer = 1 To 99
numbers.Add(count)
Next
Dim Rnd As New Random
Dim SB As New System.Text.StringBuilder
Dim Temp As Integer
'select a random number from the list, add to listbox and remove it so it can't be selected again
For count As Integer = 0 To numbers.Count - 1
Temp = Rnd.Next(0, numbers.Count)
SB.Append(numbers(Temp) & " ")
ListBox2.Items.Add(numbers(Temp))
numbers.RemoveAt(Temp)
Next
Replace
For count As Integer = 0 To numbers.Count - 1
With
For count As Integer = 1 To 5
The above will work but, You need to add count just after your next statement as well. I recommend checking into learning more about loops as well. Clearly Visual Basic 2012 is great for that.

check if string contains specific integer

I have a grid view that has a column containing strings (Middle column).
On the rowDataBound event I want to loop through the column looking for the integer it contains and then display a value in the first column.
I know that the integer range will be 1 to 63 so I can use a FOR loop to loop through the numbers. Here is what I have so far.
For x As Integer = 1 To 63
If CType(e.Row.Cells(2).FindControl("lblTagName"), Label).Text Then
End If
Next
The problem I am having is using contains. I cant use the following as it would also be true for the number 1, 10, 11 etc when x = 1.
For x As Integer = 1 To 63
If CType(e.Row.Cells(2).FindControl("lblTagName"), Label).Text.Contains(x) Then
End If
Next
How do I make sure it only gets one result per number? i.e x = 6 would return UMIS.75OPTR6GROSSMARGIN.F_CV and not all the other strings that contain the number 6.
UPDATE - based on some answers I may not of explained this very well. I want to loop through the gridview and if the number 1 is found and only the number 1 in the second column, not 10 etc then I want to display "Run 1" in the first column. So when x = 10 it will show "Run 10" and so on.
UPDATE 2 - its definatley my explanation, apologies.
The resultant grid view would look like this.
The order of the second column is not set and is not in order.
You'd have to check the entire text of the label to determine whether it is only 1, and not 10, 11, 12, 13, ... as well.
Also, in this case you should use DirectCast rather than CType. CType is only used when converting to different types that include conversion operators, here you are always dealing with a label.
For x As Integer = 1 To 63
If String.Equals(DirectCast(e.Row.Cells(2).FindControl("lblTagName"), Label).Text, "UMIS.75OPTR" & x & "GROSSMARGIN.F_CV", StringComparison.OrdinalIgnoreCase) Then
'Do your stuff.
End If
Next
You might want to think if doing it the other way around. Get the list of numbers in your string with a regular expression match.
Dim s As String = "asd12asdasd.sdf3sdf"
For Each m As System.Text.RegularExpressions.Match In System.Text.RegularExpressions.Regex.Matches(s, "[\d]*")
If m.Success AndAlso Not String.IsNullOrEmpty(m.Value) Then
' m.Value
End If
Next
With that list of number, you can check if it's between 1 and 63.
If your string have the same suffix/prefix, just remove them to show you what the number is.
Dim s As String = "UMIS.75OPTR12GROSSMARGIN.F_CV"
Dim number As String = s.Replace("UMIS.75OPTR", "").Replace("GROSSMARGIN.F_CV", "")
Go backwards in a Do Until Loop:
Dim bolFoundMatch As Boolean = False
Dim intCursor As Integer = 63
Do Until (bolFoundMatch OrElse intCursor = 0)
If CType(e.Row.Cells(2).FindControl("lblTagName"), Label).Text.Contains(intCursor) Then
'Anything you want to do when you find your match.
'This will ensure your loop exits.
bolFoundMatch = True
End If
intCursor -= 1
Loop

Random shuffling of elements in an array between 2 indexes VB.NET

I'm trying to shuffle elements between a certain number of indexes.
Dim rng As New Random()
For placeHolder As Integer = min To max Step -1
Dim swapIndex As Integer = rng.Next(min, max)
Dim temp As Object = myList(placeHolder)
myList(placeHolder) = myList(swapIndex)
myList(swapIndex) = temp
Next
Where 'min' is the value of the lowest index and 'max' is the value of the highest index. However each time I have tried it doesn't seem to be shuffling randomly (it always comes out alphabetically instead).
Try this:
Dim rng As New Random()
For placeHolder as Integer = min To max-1 Step 1
Dim swapIndex as Integer = rng.Next(placeHolder +1, max)
Dim temp as Object = myList(placeHolder)
myList(placeHolder) = myList(swapIndex)
myList(swapIndex) = temp
Next
The changes?
I changed the max value being stepped over to 1 less than the end so that you don't waste time trying to swap the end with itself. I also changed the Step to +1 because min < max from your description. I changed the minimum random value to placeholder + 1 because I don't want to re-swap what I've already swapped. This last change is optional though.
if min is the lowest and max is the highest, then your loop should not have Step -1 in it. That will cause the loop to never execute.

working with arrays

I am working with Visual Basic and i need to Find the total of each column in the last row
Find the grand total in the last cell(the bottom right corner). I know how to do the total thing for this class. But this subject I am working with Arrays. I am sure if that will work with the arrays or will it. I need to have a total at the bottom for this. I am not to sure on how to do it. So if maybe someone might have website i can read on about or something I would be happy. Thanks.
Again this is what I am suppose to do:Find the total of each column in the last row
Find the grand total in the last cell(the bottom right corner).
Module Module1
Sub Main()
Dim sum(5, 4) As Integer
Dim row, col As Integer
Dim total As Integer
For row = 0 To 4
For col = 0 To 3
sum(row, col) = row + col
sum(row, 4) += row + col
Next col
Next row
For row = 0 To 5
For col = 0 To 4
Console.Write(sum(row, col) & vbTab)
Next col
Console.WriteLine()
Next row
End Sub
End Module
One big problem is that you're traversing the array by ROWS then columns.
Doing that, you'll sum up each ROW not each COLUMN.
First step would be to reverse that.
Second, you appear to be storing the col totals on row 4, so you can't step down to row 4, just row 3.
Finally, you appear to be adding the value of the row and col vars, instead of the array entry pointed to by those vars.
Something more like this
For col = 0 to 3
for row = 0 to 3
sum(4, 4) += Sum(row, col)
sum(4, col) += Sum(row, col)
...