Reducing repetition when accessing an array in VB.NET - vb.net

for i = 0 to array.length
if array(i) = 2 and array (i+1) = 3 and .. and .. .. then
do xx on array (i+20)
..
..
end if
next
i need to check an array for a specific combination of numbers before i perform an operation, and i need to know the start point of the array as well. does anybody know how i can remove repetition because it's kind of hard to read when you have so many conditions?
array will be typically something like 02 0101 0000 so i need to check 10 consecutive values before i perform any operation

Dim j As Integer = 0
Dim b() = {1, 1}
Dim tempFlg As Boolean = False
Dim a() As Integer = {0, 2, 0, 1, 0, 1, 0, 0, 0, 0}
For i As Integer = 0 To a.Length - 1
If a(i) = b(0) Then
For j = 1 To b.Length - 1
If a(i + j) = b(j) Then
tempFlg = True
End If
Next
End If
Next
If tempFlg = True Then
MsgBox("Item present")
End If

Related

Im having problems figuring out how to print in an array

Not sure how to output the numbers, once they are in ascending order.
This is the task in the pseudocode that I am trying to move into VB.
Dim a() = {2,3,1,4}
Dim swapped = False
Output the values of a()
Do Swapped 🡨 False
For I = 1 to end of the array Compare a(i-1) with a(i) if they are not in ascending order pass them to swapped (from task 1)
Swapped(a(i-1),a(i)) assign the returned value to the
variable swapped.
While swapped = True
Output the values of a()
Dim num = New Integer() {2, 3, 1, 4}
Dim swapped As Boolean = False
While swapped = False
For i = 1 To 4
If num(i - 1) > num(i) Then
temp = num(i)
num(i) = num(i - 1)
num(i - 1) = temp
swapped = True
Else
swapped = False
End If
Next
End While
While swapped = True
Console.WriteLine(num)
End While
Console.ReadLine()
Here you go:
For Each n As Integer In num
Console.WriteLine(n.ToString)
Next
Btw there's a problem with your swapping algorithm: if they are already in the right you will enter an infinite loop, and if there's a swap on the last number you'll exit the loop even if they are not in the right order. If it puzzles you let me a comment and we'll sort this out.
Although, #laancelot showed you how to output the array, I thought I would show you a simple way to sort an array.
Private Sub OrderArray()
Dim num As Integer() = {2, 3, 1, 4}
Array.Sort(num)
Console.WriteLine("Ascending")
For Each i In num
Console.WriteLine(i.ToString)
Next
'If you want it the other way around
Array.Reverse(num)
Console.WriteLine("Descending")
For Each i In num
Console.WriteLine(i.ToString)
Next
Console.ReadLine()
End Sub
If you don't want to use vb net generic array order method, and you prefer use the swap concept, here you can try:
Private Sub TestOrderSwap()
Dim num = New Integer() {9, 7, 0, 11, 12, 10, 6, 2, 3, 1, 4}
If OrderSwap(num, "ASC") Then
For a = 0 To num.Length - 1
Debug.Print(num(a))
Next
End If
If OrderSwap(num, "DESC") Then
For a = 0 To num.Length - 1
Debug.Print(num(a))
Next
End If
End Sub
Private Function OrderSwap(ByRef myArray As Integer(), OrderType As String) As Boolean
Dim swp As Integer = 0
Dim swpFlg As Boolean = False
For a = 1 To myArray.Length - 1
swp = myArray(a)
For b = 0 To a - 1
If (myArray(b) > swp And OrderType = "ASC") Or (myArray(b) < swp And OrderType = "DESC") Then
For c = a - 1 To b Step -1
myArray(c + 1) = myArray(c)
Next
myArray(b) = swp
swpFlg = True
Exit For
End If
Next
Next
Return swpFlg
End Function

vb.net array.sort() parameters why 1 short?

I'm sorting an array using code like this:
Array.Sort(arr, 0, intEndingPosition, New myIComparer)
I want the sorting to start with index 0 and end with index intEndingPosition. However, the last element arr(intEndingPosition) was left out and did not get sorted. Why?
intEndingPosition is calculated beforehand like this:
Dim StringOfConcern As String
Dim OneChar(65534), FrqOne(65534) As String
Dim CntNewOnes, CntRptOnes As Integer
Dim c As Char
Dim i, j As Integer
Dim isNew As Boolean
StringOfConcern = TextBox1.Text
OneChar(0) = CStr(StringOfConcern(0))
FrqOne(0) = 1
i = 0
j = 0
For Each c In StringOfConcern.Substring(1)
isNew = True
For j = 0 To i Step 1
If CStr(c) = OneChar(j) Then
isNew = False
FrqOne(j) += 1
Exit For
End If
Next j
If isNew = True Then
i += 1
OneChar(i) = CStr(c)
FrqOne(i) = 1
End If
Next c
CntNewOnes = i + 1
CntRptOnes = 0
For i = 0 To CntNewOnes - 1 Step 1
If FrqOne(i) > 1 Then CntRptOnes += 1
Next i
The sorting follows here. The code in my original question is only illustrative. The actual sorting is:
Array.Sort(FrqOne, OneChar, 0, CntNewOnes - 1)
Array.Reverse(FrqOne, 0, CntNewOnes - 1)
Array.Reverse(OneChar, 0, CntNewOnes - 1)
Note the method declaration for Array.Sort
Public Shared Sub Sort (
array As Array,
index As Integer,
length As Integer,
comparer As IComparer
)
The third parameter is the number of elements in the range to sort (length) not the end index as you suggest.
So let's assume for a minute that your intEndingPosition is 4. This means you're expecting to sort 5 elements i.e. elements at indices 0, 1, 2, 3, 4. However, the number 4 is the length and not the end index thus you're only sorting elements at indices 0, 1, 2, 3.
This explains why you're observing that the elements being sorted is one shorter than you expected.
Put it simply the third parameter should specify the length of elements to sort and not the end index.
Another Example:
Consider the Substring method of the String class:
Public Function Substring (
startIndex As Integer,
length As Integer
) As String
Then assume we have this piece of code:
Dim temp As String = "testing"
Dim result As String = temp.Substring(0, 4)
result is now a string containing 4 characters as 4 in the Substring call indicates the length that should be retrieved as opposed to the end index.
Had 4 been the end index then you'd expect result to contain 5 characters.

Simple sort algortihm not working - Index issues

I am trying to sort an array using an algorithm, but I am having trouble with my index.
Sub Main()
Dim List() As Integer = {9, 8, 5, 6}
Dim InnerPointer As Integer = 0
Dim CurrentValue As Integer
For OutPointer = 1 To List.Length - 1
CurrentValue = List(OutPointer)
While InnerPointer > 0 And List(InnerPointer) > CurrentValue
List(InnerPointer + 1) = List(InnerPointer)
InnerPointer = InnerPointer - 1
End While
List(InnerPointer + 1) = CurrentValue
Next
For Each element In List
Console.WriteLine(element)
Next
Console.ReadKey()
End Sub
I define InnerPointer as 0 because my array is 0 index based, but this means my While Loop wont kick in...and yet I do want to compare index 0 with index 1 to determine which number is bigger. I cant for the life of me work out where the logical fallacy is

Longest common substring large strings?

I need some help with this function. I am trying to find the longest common string between 2 strings. Here is the function that I am currently using:
Public Shared Function LCS(str1 As Char(), str2 As Char())
Dim l As Integer(,) = New Integer(str1.Length - 1, str2.Length - 1) {}
Dim lcs__1 As Integer = -1
Dim substr As String = String.Empty
Dim [end] As Integer = -1
For i As Integer = 0 To str1.Length - 1
For j As Integer = 0 To str2.Length - 1
If str1(i) = str2(j) Then
If i = 0 OrElse j = 0 Then
l(i, j) = 1
Else
l(i, j) = l(i - 1, j - 1) + 1
End If
If l(i, j) > lcs__1 Then
lcs__1 = l(i, j)
[end] = i
End If
Else
l(i, j) = 0
End If
Next
Next
For i As Integer = [end] - lcs__1 + 1 To [end]
substr += str1(i)
Next
Return substr
End Function
This works great on strings of up to around 600 words or so. If I try to compare strings with a larger word count than that it starts to throw system.outofmemoryexception. Obviously, this is hitting the memory pretty hard. Is there any way to fine tune this function or is there possibly another way of doing this that is more streamlined?

How to compare Strings for Percentage Match using vb.net?

I am banging my head against the wall for a while now trying different techniques.
None of them are working well.
I have two strings.
I need to compare them and get an exact percentage of match,
ie. "four score and seven years ago" TO "for scor and sevn yeres ago"
Well, I first started by comparing every word to every word, tracking every hit, and percentage = count \ numOfWords. Nope, didn't take into account misspelled words.
("four" <> "for" even though it is close)
Then I started by trying to compare every char in each char, incrementing the string char if not a match (to count for misspellings). But, I would get false hits because the first string could have every char in the second but not in the exact order of the second. ("stuff avail" <> "stu vail" (but it would come back as such, low percentage, but a hit. 9 \ 11 = 81%))
SO, I then tried comparing PAIRS of chars in each string. If string1[i] = string2[k] AND string1[i+1] = string2[k+1], increment the count, and increment the "k" when it doesn't match (to track mispellings. "for" and "four" should come back with a 75% hit.) That doesn't seem to work either. It is getting closer, but even with an exact match it is only returns 94%. And then it really gets screwed up when something is really misspelled. (Code at the bottom)
Any ideas or directions to go?
Code
count = 0
j = 0
k = 0
While j < strTempName.Length - 2 And k < strTempFile.Length - 2
' To ignore non letters or digits '
If Not strTempName(j).IsLetter(strTempName(j)) Then
j += 1
End If
' To ignore non letters or digits '
If Not strTempFile(k).IsLetter(strTempFile(k)) Then
k += 1
End If
' compare pair of chars '
While (strTempName(j) <> strTempFile(k) And _
strTempName(j + 1) <> strTempFile(k + 1) And _
k < strTempFile.Length - 2)
k += 1
End While
count += 1
j += 1
k += 1
End While
perc = count / (strTempName.Length - 1)
Edit: I have been doing some research and I think I initially found the code from here and translated it to vbnet years ago. It uses the Levenshtein string matching algorithm.
Here is the code I use for that, hope it helps:
Sub Main()
Dim string1 As String = "four score and seven years ago"
Dim string2 As String = "for scor and sevn yeres ago"
Dim similarity As Single =
GetSimilarity(string1, string2)
' RESULT : 0.8
End Sub
Public Function GetSimilarity(string1 As String, string2 As String) As Single
Dim dis As Single = ComputeDistance(string1, string2)
Dim maxLen As Single = string1.Length
If maxLen < string2.Length Then
maxLen = string2.Length
End If
If maxLen = 0.0F Then
Return 1.0F
Else
Return 1.0F - dis / maxLen
End If
End Function
Private Function ComputeDistance(s As String, t As String) As Integer
Dim n As Integer = s.Length
Dim m As Integer = t.Length
Dim distance As Integer(,) = New Integer(n, m) {}
' matrix
Dim cost As Integer = 0
If n = 0 Then
Return m
End If
If m = 0 Then
Return n
End If
'init1
Dim i As Integer = 0
While i <= n
distance(i, 0) = System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)
End While
Dim j As Integer = 0
While j <= m
distance(0, j) = System.Math.Max(System.Threading.Interlocked.Increment(j), j - 1)
End While
'find min distance
For i = 1 To n
For j = 1 To m
cost = (If(t.Substring(j - 1, 1) = s.Substring(i - 1, 1), 0, 1))
distance(i, j) = Math.Min(distance(i - 1, j) + 1, Math.Min(distance(i, j - 1) + 1, distance(i - 1, j - 1) + cost))
Next
Next
Return distance(n, m)
End Function
Did not work for me unless one (or both) of following are done:
1) use option compare statement "Option Compare Text" before any Import declarations and before Class definition (i.e. the very, very first line)
2) convert both strings to lowercase using .tolower
Xavier's code must be correct to:
While i <= n
distance(i, 0) = System.Math.Min(System.Threading.Interlocked.Increment(i), i - 1)
End While
Dim j As Integer = 0
While j <= m
distance(0, j) = System.Math.Min(System.Threading.Interlocked.Increment(j), j - 1)
End While