Binary Search or Insertion Sort with list view [Visual Basic .net] - vb.net

Recently when creating a program for my client as part of my computing project in visual basic .net I've came across a problem, which looks like following; In order to receive additional marks for my program I must take an advantage of either Binary Search or Insertion Sort subroutine declared recursively, so far the only place I can use it on is my View form which displays all reports generated by program but the problem with this is since I'm using MS Access to store my data all of the data is downloaded and placed in listview in load part of form. So the only way I can use it is by running it on listview which is a major problem for me due to the fact that I'm not very experienced in vb.
For binary search I have tried downloading all of the items in specified by user column into an array but that's the bit I was struggling on the most because I'm unable to download all items from only one column into an array. Also instead of searching every single column user specifies in my form in which column item is located (For example "19/02/2013" In Column "Date"), In my opinion if I manage to download every single entry in specified column into an array it should allow me to run binary search later on therefore completing the algorithm. Here's what I've got so far.
Sub BinarySearch(ByVal Key As String, ByVal lowindex As String, ByVal highindex As String, ByVal temp() As String)
Dim midpoint As Integer
If lowindex > highindex Then
MsgBox("Search Failed")
Else
midpoint = (highindex + lowindex) / 2
If temp(midpoint) = Key Then
MsgBox("found at location " & midpoint)
ElseIf Key < temp(midpoint) Then
Call BinarySearch(Key, lowindex, midpoint, temp)
ElseIf Key > temp(midpoint) Then
Call BinarySearch(Key, midpoint, highindex, temp)
End If
End If
End Sub
Private Sub btnSearch_Click(sender As System.Object, e As System.EventArgs) Handles btnSearch.Click
Dim Key As String = txtSearch.Text
Dim TargetColumn As String = Me.lstOutput.Columns(cmbColumns.Text).Index
Dim lowindex As Integer = 0
Dim highindex As Integer = lstOutput.Items.Count - 1
'Somehow all of the items in Target column must be placed in temp array
Dim temp(Me.lstOutput.Items.Count - 1) As String
' BinarySearch(Key, lowindex, highindex, temp)
End Sub
For Insertion sort i don't even have a clue how to start, and the thing is that I have to use my own subroutine instead of calling system libraries which will do it for me.
Code which I have to use looks like following:
Private Sub InsertionSort()
Dim First As Integer = 1
Dim Last As Integer = Me.lstOutput.
Dim CurrentPtr, CurrentValue, Ptr As Integer
For CurrentPtr = First + 1 To Last
CurrentValue = A(CurrentPtr)
Ptr = CurrentPtr - 1
While A(Ptr) > CurrentValue And Ptr > 0
A(Ptr + 1) = A(Ptr)
Ptr -= 1
End While
A(Ptr + 1) = CurrentValue
Next
Timer1.Enabled = False
lblTime.Text = tick.ToString
End Sub
Any ideas on how to implement this code will be very appreciated, and please keep in my mind that I'm not very experienced in this language

Perhaps this might give you a place to begin. If you already have a ListView with "stuff" in it you could add a button to the form with the following code to copy the Text property for each item into an array:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim myArray(Me.ListView1.Items.Count - 1) As String
Dim i As Integer
' load array
For i = 0 To Me.ListView1.Items.Count - 1
myArray(i) = Me.ListView1.Items(i).Text
Next
' show the results
Dim s As String = ""
For i = 0 To UBound(myArray)
s &= String.Format("myArray({0}): {1}", i, myArray(i)) & vbCrLf
Next
MsgBox(s, MsgBoxStyle.Information, "myArray Contents")
' now go ahead and manipulate the array as needed
' ...
End Sub

Related

How to use Nested Loop in Visual Basic for all unrepeated combinations of characters?

I am trying to get the combinations of all possible unrepeated character sets from the user input.
As I am just beginning to learn the programming, it is obvious that I don't properly understand how those nested loops work.
Here is my code:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1.Items.Clear()
Dim c1 As String = TextBox1.Text
Dim i, j As Integer
Dim str As String()
Dim k As Integer = 0
For i = 0 To c1.Length - 1
For j = 0 To i
ListBox1.Items.Add(c1(i) & c1(j))
Next
Next
End Sub
End Class
As you can see in the picture attached, I cannot get the rest. How can I get the character pairs I put in the red box on notepad?
Can someone help me, please.enter image description here
You had the right idea. However, expand your logic so that for every letter of the outer loop you spin through every letter again. And if you don't want repeated letter pairs, add an If statement:
For i = 0 To c1.Length - 1
For j = 0 To c1.Length - 1
If i <> j Then ListBox1.Items.Add(c1(i) & c1(j))
Next
Next

How I can set the index of Datagridview to 0

How I can set the index of DataGridView to 0?
I developed a pharmacy software where I want to add values from TextBoxes into DataGridView with adding a new row. It is working but the problem is when I clear the value of DataGridView by using this code
dgvSoldMedicineInfo.Rows.Clear()
then when I try the previous procedure it show this error in VB.NET
Index was out of range, Must be non-negative and less than the size of the collection. Parameter name:index
Code:
Dim rowcounter As Integer = 0
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
dgvSoldMedicineInfo.Rows.Add()
dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnBarcodeNo").Value = txtBarcodeNo.Text
dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnName").Value = dgvSale.CurrentRow.Cells(2).Value
dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnQuantity").Value = txtQuantity.Text
dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnSalePrice").Value = txtSalePrice.Text
dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnAmount").Value = txtTotalAmount.Text
dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnReject").Value = "Reject"
dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnStockID").Value = dgvSale.CurrentRow.Cells(0).Value
dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnStockQuantity").Value = dgvSale.CurrentRow.Cells(3).Value
System.Math.Max(System.Threading.Interlocked.Increment(rowcounter), rowcounter - 1)
End Sub
There's really no point to that rowcounter variable in that context and it's bad form to keep using dgvSoldMedicineInfo.Rows(rowcounter) over and over again. The proper way to do that would be like so:
Dim rowIndex = dgvSoldMedicineInfo.Rows.Add()
Dim row = dgvSoldMedicineInfo.Rows(rowIndex)
Dim cells = row.Cells
cells("ColumnBarcodeNo").Value = txtBarcodeNo.Text
cells("ColumnName").Value = dgvSale.CurrentRow.Cells(2).Value
'etc.
That said, why do that when the Add method is overloaded and will accept all the cell values up front?
dgvSoldMedicineInfo.Rows.Add(txtBarcodeNo.Text,
dgvSale.CurrentRow.Cells(2).Value,
...)

Encode and Decode VBA Program

in my programming class I have to create a program which allows the user in order to enter a sentence, with the buttons "Encode" and "Decode" as options. So, for "Encode", you have to translate the sentence into Asc numbers (already did this). However, I'm currently stuck on the "Decode" section, for you have to use a For loop and an array to separate the Asc numbers by spaces, then translate them into characters one by one. Here's what I have so far:
Public Class Form1
Dim Message As String
Dim NewMessage As String
Dim Part As String
Dim Part2 As Integer
Dim Letter As String
Dim Length As String
Dim ints() As Integer
Dim intlength As Integer
Private Sub btn_Enter_Click(sender As Object, e As EventArgs) Handles btn_Enter.Click
Message = txt_Message.Text
Length = Message.Length() - 1
If rbn_Encode.Checked = True Then
For Num As Integer = 0 To Length
Letter = Message(Num)
Me.lbl_Code.Text = lbl_Code.Text & Asc(Letter) & " "
Next
End If
If rbn_Decode.Checked = True Then
For Num As Integer = 0 To intlength Step 1
If Message(Num) <> " " Then
Part = Part & Message(Num)
Else
NewMessage = NewMessage & ChrW(Part) & " "
End If
Next
Me.lbl_Code.Text = NewMessage
End If
End Sub
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
Application.Exit()
End Sub
End Class
I've been stuck on this for about 2 week, and I'm still clueless. Thank you for your help and have a wonderful day.
This might seem to veer off the topic of the question, but it all meanders towards a better answer.
OK there are a few issues with your code. Firstly, make sure that "Option Strict" is on - have a look here. This will force you to convert types properly and reduce the potential for problems. Bearing the above in mind,
Dim Length As String
should be
Dim Length As Integer
on to the next bit
Each procedure should have a single responsibility. Your btn_Enter.Click event handler includes code for encoding text and decoding numbers. These should be separated out into their own procedures. In a relatively short bit of code like yours, it's not too much of a problem, but even here, it makes things a little fuzzier. Have a look at the code below. There are more issues, but we'll look at them in a moment. The code below is a bit clearer and more maintainable.
Private Sub btn_Enter_Click(sender As Object, e As EventArgs) Handles btn_Enter.Click
Message = txt_Message.Text
Length = Message.Length() - 1
If rbn_Encode.Checked = True Then
EncodeTextToAscii()
End If
If rbn_Decode.Checked = True Then
DecodeToText()
End If
End Sub
Private Sub DecodeToText()
For Num As Integer = 0 To intlength Step 1
If Message(Num) <> " " Then
Part = Part & Message(Num)
Else
NewMessage = NewMessage & ChrW(Part) & " "
End If
Next
Me.lbl_Code.Text = NewMessage
End Sub
Private Sub EncodeTextToAscii()
For Num As Integer = 0 To Length
Letter = Message(Num)
Me.lbl_Code.Text = lbl_Code.Text & Asc(Letter) & " "
Next
End Sub
Next.
In your code to encode the string as ASCII, you store the resulting data directly in the label lbl_Code's text property. The user interface should never be used as the primary store for data. It's bad practice and potentially allows the user to change data accidentally - in textboxes for example. In the case of a label, it's not to important, but it's far better to get into the good habits.
To store your encoded ASCII numbers, you can use the array ints, but as your code stands, the declaration of ints is just that. There is no space in the array to store data. So, in the Encode procedure, you need to resize ints to the same as the number of characters in the string.
So now we have ..
Private Sub EncodeTextToAscii()
ReDim ints(Length)
For Num As Integer = 0 To Length
Letter = Message(Num)
ints(Num) = Asc(Letter)
Next
End Sub
Finally onto the meat of your question. The Decode procedure can now be written as this ..
Private Sub DecodeToText()
NewMessage = ""
For Each asciiNumber As Integer In ints
NewMessage = NewMessage & ChrW(asciiNumber) & " "
Next
Me.lbl_Code.Text = NewMessage
End Sub
Instead of mucking around getting the length of a loop and getting the ascii number in each element of an array, you can simplyfy it using a For Each statement. You dont need to know the length of the array. It just loops over the whole length. Much easier.
As an excercise, try applying the For Each idea to the Encode procedure. :-)

Sorted List in Array Visual Basic [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I have a program that creates a list of 25 random numbers from 0 to 1,000. I have to buttons the first button will load a list box with the random numbers and the second button will sort the list of numbers from the smallest to largest which is where I implemented bubble sort code. Now the other list box that is supposed to hold the sorted numbers doesn't work properly it only shows one number instead of all of them.
Here is my code:
Option Strict On
Public Class Form1
Dim rn As Random = New Random
Dim Clicked As Long = 0
Dim numbers, sort As Long
Private Sub GenerateBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GenerateBtn.Click
Clicked += 1
For x = 0 To 25
numbers = rn.Next(0, 1000)
RandomBox.Items.Add(numbers)
If Clicked >= 2 Then
RandomBox.Items.Clear()
Clicked = 1
End If
Next
End Sub
Private Sub SortBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SortBtn.Click
Dim Sorted() As Long = {numbers}
Dim Swapped As Boolean
Dim endOfArray As Integer = Sorted.Length - 1
Dim Tmp As Byte
While (Swapped)
Swapped = False
For I = 0 To endOfArray - 1
If Sorted(I) > Sorted(I + 1) Then
Tmp = CByte(Sorted(I))
Sorted(I) = Sorted(I + 1)
Sorted(I + 1) = Tmp
Swapped = True
End If
endOfArray = endOfArray - 1
Next
End While
SortBox.Items.Clear()
For I = 0 To Sorted.Count - 1
SortBox.Items.Add(Sorted(I))
Next
End Sub
End Class
Change your:
Dim Sorted() As Long = {numbers}
to
Sorted(x) = numbers
edit: Since you changed your code. You need to put back in the line that loads the Sorted Array.
For x = 0 To 25
numbers = rn.Next(0, 1000)
RandomBox.Items.Add(numbers)
Sorted(x) = numbers
If Clicked >= 2 Then
RandomBox.Items.Clear()
Clicked = 1
End If
Next
and remove the:
Dim Sorted() As Long = {numbers}
from the second part and put this declaration back in the beginning like you had:
Dim Sorted(26) as Long
The way you have will only show the latest random number. It is not any array but a single entity. Therefore only the latest will be add into the array. You need to load each number into the array as you create each one. Thus the (x) which loads it into position x.
You didn't use any arrays at all in your project...you're using the ListBox as your storage medium and that's a really bad practice.
I recommend you set it up like this instead:
Public Class Form1
Private rn As New Random
Private numbers(24) As Integer ' 0 to 24 = 25 length
Private Sub GenerateBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GenerateBtn.Click
For x As Integer = 0 To numbers.Length - 1
numbers(x) = rn.Next(0, 1000)
Next
' reset the listbox datasource to view the random numbers
RandomBox.DataSource = Nothing
RandomBox.DataSource = numbers
' empty out the sorted listbox
SortBox.DataSource = Nothing
End Sub
Private Sub SortBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SortBtn.Click
' make a COPY of the original array that we will sort:
Dim sorted(numbers.Length - 1) As Integer
Array.Copy(numbers, sorted, numbers.Length)
Dim Swapped As Boolean = True
Dim endOfArray As Integer = Sorted.Length - 1
Dim Tmp As Integer
While (Swapped)
Swapped = False
For I As Integer = 0 To endOfArray - 1
If sorted(I) > sorted(I + 1) Then
Tmp = sorted(I)
sorted(I) = sorted(I + 1)
sorted(I + 1) = Tmp
Swapped = True
End If
Next
endOfArray = endOfArray - 1
End While
' reset the listbox datasource to view the sorted numbers
SortBox.DataSource = Nothing
SortBox.DataSource = sorted
End Sub
End Class
Also, note that you were decrementing endOfArray inside your for loop. You should only decrement it after each pass; so outside the for loop, but inside the while loop.
Additionally, you were using a Tmp variable of type Byte, but generating numbers between 0 and 999 (inclusive). The Byte type can only hold values between 0 and 255 (inclusive).
Your Bubble Sort implementation was very close to correct!

Loop through contents in the text file

New TechGuy on this site. Thought i'd make this resourceful since im getting ready to graduate and want more programming practice. I have a question:
I tried looping through a text file I created and I wanted to replace each multiple of 3 with the word "changed". I created a text file and entered numbers 1-15 on each line. My code is below but for some reason it would only change the number 3 and 13. I tried using this link as a resource (Loop through the lines of a text file in VB.NET) but that wasnt to helpful. Anyway here is my code, can someone help with what i'm doing wrong?
Public Class numbers
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim OpenFilePrompt As New OpenFileDialog
openFilePrompt.ShowDialog()
Dim currentReader As New System.IO.StreamReader(OpenFilePrompt.FileName)
txtInput.Text = currentReader.ReadToEnd
Dim a As String
Dim numbers As New List(Of String)
a = txtInput.Text
numbers.Add(a)
Dim b As Integer
For i = 0 To numbers.Count Step 3
b = b + 3
TextBox2.Text = (numbers.Item(i).Replace(b.ToString, "Changed"))
Next
End Sub
End Class
You are setting numbers (the first item) to a, which is txtInput.Text.
Then you have a one size list which is completely useless!
You should use Mod instead.
Divides two numbers and returns only the remainder.
So just check if Integer Mod 3 equals 0.
Also consider using File.ReadAllLines(String), Val(String), String.Join(String, String()) and File.WriteAllLines(String, String()).
Dim Content() As String = File.ReadAllLines(OpenFilePrompt.FileName)
For Index As Integer = 0 To Content.Length - 1
Dim Number As Integer = Val(Content(Index))
If Number Mod 3 = 0 Then
Content(Index) = "changed"
End If
Next
txtInput.Text = String.Join(vbCrLf, Content)
File.WriteAllLines(OpenFilePrompt.FileName, Content)