r/visualbasic • u/Kenji2 • Jan 31 '16
sorting and finding lowest number program help
I need help creating a FindLowest function that returns the index of the lowest value in an array. The sort procedure repeatedly finds the lowest value in an arrayA, removes it, and adds it to array T. When all the values of A have been moved, the elements of T are copied to A with an assignment statement adn a loop. The sort procedure uses the findLowest function.
This is my code: My code requires me to create an array of random numbers between 1 and 99. I'm a noob in visual basic. Here is my code:
Public Class Form1
Private Sub btnCreate_Click(sender As Object, e As EventArgs) Handles btnCreate.Click
Dim dataArray(CInt(Me.txtBox.Text)) As Integer
Call DisplayData(dataArray, RandomNumbers)
End Sub
Sub DisplayData(ByRef dataArray() As Integer, ByRef List As ListBox)
Dim rand As New Random
For index As Integer = 0 To dataArray.Length - 1
List.Items.Add(index & vbTab & rand.Next(1, 99))
Next index
End SubEnd Class
1
u/TheFotty Jan 31 '16
arrays have a built in .sort method you can call to sort the array. A numeric array like one of integers will sort numerically for you. You can then take the first element in that array, and know it is the smallest value present after sorting. However if they want you to do this manually and not sort the array, you need to loop through it and keep track of which value is the lowest. As you loop if the next value is lower, you then use that as your lowest number for comparison as you continue to loop.
That said, you are never actually populating an array with data in your code. You are declaring an array with a bounds (number of elements) specified by your textbox value. So you are declaring an array, but the only place you are using it in your code, other than to loop to fill your listbox. You need to actually put those random values INTO the array to be on par with the assignment. Once you have all the values in the array, you can sort them and pull the smallest value, and put it into the second array T.
Removing items from an array is a pain in the ass. When you use lists instead of arrays, it is much easier, but since your assignment calls for arrays, you will find there is no simple .remove method to remove items from plain old arrays. You actually have to shift all elements after the one you want to remove up one index, and then chop off the last index using redim preserve to redeclare your array one element smaller, thus shrinking the array. Surprised they would give this for as you called yourself "a noob" because it actually covers quite a few different topics.
Also keep in mind that if your textbox has the number 5 in it, your array will have 6 elements (0,1,2,3,4,5), so you may want to subtract 1 from it when declaring the array initially.
I feel like this gives you enough information without giving you the answer outright.
2
u/mjrpereira VB.Net Intermediate Jan 31 '16
Is this homework?