Dalibor Boldis Dalibor Boldis - 1 year ago 47
Vb.net Question

Comparing arrays with numbers in vb.net

I need a way to compare two arrays in vb.net and save result in third array:

Dim KonRes(3) As Integer
Dim UserRes(3) As Integer
Dim YelRed(3) As Integer

KonRes(0) = 1
KonRes(1) = 2
KonRes(2) = 3
KonRes(3) = 4

UserRes(0) = 4
UserRes(1) = 3
UserRes(2) = 2
UserRes(3) = 1

How to compare those arrays so in declared variable YelRed I should have results like this:

If UserRes(0) = KonRes(0) Then
YelRed(0) = 2
If UserRes(0) = KonRes(1 or 2 or 3) Then
YelRed(0) = 1

If UserRes(0) does not contain any number like in KonRes then YelRed(0) should be 0. Also it should not make duplicate results, in other words if it already checked UserRes(0) = KonRes(0) then it should not check KonRes(0) in next check. It's not a problem to compare if those arrays are completely same, my problem is comparing each value of one array with other one, and collect results. Any suggestions?

Answer Source

There are a few basic ways of checking for a value in an integer array. The first is to manually search by looping through each value in the array, which may be what you want if you need to do complicated comparisons.

Second is the .Contains() method. It is simpler to use but will only give you a Boolean indicating whether the value is in the array or not. Example:

If KonRes.Contains(UserRes(0)) Then YelRed(0) = 1

Lastly, there's the IndexOf() function. It searches for a match and returns the index of a match if found, or one below the lower bound of the array if not (-1 for typical 0-based arrays). As I understand your needs from your comments above, this code should do the trick:

For i As Integer = 0 To 3
    Select Case IndexOf(KonRes, UserRes(i))
        Case i   'Matching postion
            YelRed(i) = 2
        Case -1   'No match found
            YelRed(i) = 0
        Case Else   'Match found at another position
            YelRed(i) = 1
    End Select
Next i

EDIT: I misunderstood the qualification about duplicates until @Sastreen clarified it. Here's a rewrite tailored to not count the same index as a match twice:

Dim processed(3) As Boolean
For i As Integer = 0 To 3
    YelRed(i) = 0
    If KonRes(i) = UserRes(i) And Not processed(i) Then
        processed(i) = True
        YelRed(i) = 2
        For j As Integer = 0 To 3
            If KonRes(j) = UserRes(i) Then
                processed(j) = True
                YelRed(i) = 1
                Exit For
            End If
        Next j
    End If
Next i