Visual Basic- Random Numbers - vb.net

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.

Related

Dim n variables where n is a user defined number

I have to dim n variables in my software, where n is a number that user types in the interface. I'd start with a for loop, in order to declare these variables, with something like:
for i = 0 to n
dim r.i as IRow = worksheet.CreateRow(i)
next
This is what I think but obviously I know that's wrong. Does anyone knows if this is possible? I can't create neither List(Of) nor arrays because these are rows of an excel file I'm trying to export, otherwise NPOI returns me error.
What does Excel have anything to do with not using a List? You can absolutely use worksheet.CreateRow() with a list:
Dim rows As New List(Of IRow)
For i As Integer = 0 to n - 1
rows.Add(worksheet.CreateRow(i))
Next
Now the name of each row is row(0), row(1), row(2) ... row(n - 1)
If you've tried this and NPOI is giving you an error, you should show that code around where the error is thrown and tell us what the error is.
Based on comments:
'Assuming everything has the same number of entries as ListBox1, per the comments
Dim rows As New List(Of IRow)
Dim row As IRow = worksheet.CreateRow(0)
row.CreateCell(0).SetCellValue("Time")
row.CreateCell(1).SetCellValue("hrr")
For i As Integer = 0 To ListBox1.Items.Count - 1
row = worksheet.CreateRow(i+1)
row.CreateCell(0).SetCellValue(ListBox1.Items(i))
row.CreateCell(1).SetCellValue(ListBox2.Items(i))
rows.Add(row)
Next i

Visual Basic- random number

I have some VB code that gives me a random number, 1 between 20 (X). However, within 20 attempts, I will get the same number twice. How can I get a sequence of random numbers without any of them repeating? I basically want 1-20 to show up up in a random order if I click a button 20 times.
Randomize()
' Gen random value
value = CInt(Int((X.Count * Rnd())))
If value = OldValue Then
Do While value = OldValue
value = CInt(Int((X.Count * Rnd())))
Loop
End If
For 1 to 20, use a data structure like a LinkedList which holds numbers 1 to 20. Choose an index from 1 to 20 at random, take the number at that index, then pop out the number in that location of the LinkedList. Each successive iteration will choose an index from 1 to 19, pop, then 1 to 18, pop, etc. until you are left with index 1 to 1 and the last item is the last random number. Sorry for no code but you should get it.
The concept is, you have to add the generated random number into a list, and before adding it into the list, make sure that the new number is not contains in it. Try this code,
Dim xGenerator As System.Random = New System.Random()
Dim xTemp As Integer = 0
Dim xRndNo As New List(Of Integer)
While Not xRndNo.Count = 20
xTemp = xGenerator.Next(1, 21)
If xRndNo.Contains(xTemp) Then
Continue While
Else
xRndNo.Add(xTemp)
End If
End While
[Note: Tested with IDE]
for that purpose, you need to store all previous generated number, not just one, as u did in OldValue named variable. so, store all previously generated numbers somewhere (list). and compare the newly generated number with all those in list, inside ur while loop, and keep generating numbers, while number is not equal to any of one in list..
Add the numbers to a list and then pick them in a random order, deleting them as they are picked.
Dim prng As New Random
Dim randno As New List(Of Integer)
Private Sub Button1_Click(sender As Object, _
e As EventArgs) Handles Button1.Click
If randno.Count = 0 Then
Debug.WriteLine("new")
randno = Enumerable.Range(1, 20).ToList 'add 1 to 20 to list
End If
Dim idx As Integer = prng.Next(0, randno.Count) 'pick a number
Debug.WriteLine(randno(idx)) 'show it
randno.RemoveAt(idx) 'remove it
End Sub

How to count string occurences in a list(Of String)

I am looking to dynamically count from a list, how many times items have occured. I can do it below if I specify the value I am looking for, but what I am really looking to do is to iterate through my list, count occurences, and total them out. My current code is below:
Dim itemlist As New List(Of String)
itemlist.add("VALUE1")
itemlist.add("VALUE2")
itemlist.add("VALUE3")
Dim count As Integer = 0
For Each value In itemlist
If value.Equals("VALUE1") Then count += 1
Next
Msgbox(count.tostring)
So my point would be instead of searching for the value, let the app total them up and display the counted occurences it to the user, similar to a "COUNTIF" in excel. I cant find much on this without using LINQ, Thanks
You can do this very easily with LINQ:
Msgbox(itemlist.Where(Function(value) value = "VALUE1").Count)
To count duplicates, once again it's easy with LINQ:
Dim itemlist As New List(Of String)
itemlist.Add("RED")
itemlist.Add("RED")
itemlist.Add("RED")
itemlist.Add("GREEN")
dim groups = itemList.GroupBy(Function(value) value)
For Each grp In groups
Console.WriteLine(grp(0) & " - " & grp.Count )
Next
Output:
RED - 3
GREEN - 1

Array Calculation with CSV file

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

adapting combination code for larger list

I have the following code to generate combinations of string for a small list and would like to adapt this for a large list of over 300 string words.Can anyone suggest how to alter this code or to use a different method.
Public Class combinations
Public Shared Sub main()
Dim myAnimals As String = "cat dog horse ape hen mouse"
Dim myAnimalCombinations As String() = BuildCombinations(myAnimals)
For Each combination As String In myAnimalCombinations
''//Look on the Output Tab for the results!
Console.WriteLine("(" & combination & ")")
Next combination
Console.ReadLine()
End Sub
Public Shared Function BuildCombinations(ByVal inputString As String) As String()
''//Separate the sentence into useable words.
Dim wordsArray As String() = inputString.Split(" ".ToCharArray)
''//A plase to store the results as we build them
Dim returnArray() As String = New String() {""}
''//The 'combination level' that we're up to
Dim wordDistance As Integer = 1
''//Go through all the combination levels...
For wordDistance = 1 To wordsArray.GetUpperBound(0)
''//Go through all the words at this combination level...
For wordIndex As Integer = 0 To wordsArray.GetUpperBound(0) - wordDistance
''//Get the first word of this combination level
Dim combination As New System.Text.StringBuilder(wordsArray(wordIndex))
''//And all all the remaining words a this combination level
For combinationIndex As Integer = 1 To wordDistance
combination.Append(" " & wordsArray(wordIndex + combinationIndex))
Next combinationIndex
''//Add this combination to the results
returnArray(returnArray.GetUpperBound(0)) = combination.ToString
''//Add a new row to the results, ready for the next combination
ReDim Preserve returnArray(returnArray.GetUpperBound(0) + 1)
Next wordIndex
Next wordDistance
''//Get rid of the last, blank row.
ReDim Preserve returnArray(returnArray.GetUpperBound(0) - 1)
''//Return combinations to the calling method.
Return returnArray
End Function
End Class
'
CHANGES//
For wordDistance = 1 To inputList.Count.ToString / 2
Dim count = inputList.Count.ToString
'Go through all the words at this combination level...
For wordIndex As Integer = 0 To inputList.Count.ToString - wordDistance
'Get the first word of this combination level
combination.Add(inputList.Item(wordIndex))
'And all all the remaining words a this combination level
For combinationIndex As Integer = 1 To wordDistance
combination.Add(" " & inputList.Item(wordIndex + combinationIndex))
Next combinationIndex
'Add this combination to the results
If Not wordsList.Contains(combination) Then
wordsList.Add(combination.ToString)
End If
'Add a new row to the results, ready for the next combination
'ReDim Preserve returnArray(returnArray.GetUpperBound(0) + 1)
Next wordIndex
Next wordDistance
One obvious thing in your code is the usage of ReDim Preserve. That can be quite a slow operation since I think it copies the whole array into a new array every time the size is changed, and since you're doing that inside loops I assume that could be a significant issue.
The simplest way of fixing that is to stop using those kinds of arrays and instead use List with it's Add method.
I want to make sure I understand what you are trying to do first. Your problem seems to be:
Given a list of strings,
Return every possible combination of n items from the list,
where n = 2 to length of list
For example, in a list of 5 strings, you would want all combinations of 2 strings, of 3 strings, of 4 strings, and of 5 strings.
If that is an accurate statement of your problem, there is one glaring issue to point out. The number of items you will be generating is on the order of 2 ^ (length of list). This means that trying to generate all combinations of 300 items will never be fast no matter what. Also, for any but the tiniest of lists, you will need to generate items lazily or you will run out of memory.
If you do not want all combinations of all lengths, you may want to clarify your question to better state your desired goal.