Pawel
Pawel

Reputation: 1297

VBA: compare two strings logic and return true or false

I want to compare two strings in a specific way.

Strings are logical sentences made from words, operators("+" = AND, "/" = OR) and brackets. Each word can be true or false. There is no particular pattern for a sentence - any combination of words and operators can be given

I need to work out function that will return true or false depending if both compared sentences are the same or not.

Let me evaluate few examples:

Example 1:

s1 = "A+B+C"
s2 = "A+B+C"
compare(s1, s2) 'will result True

Example 2:

s1 = "A+B+C"
s2 = "A+C+B"
compare(s1, s2) 'will result True

Example 3:

s1 = "(A/B)+C"
s2 = "A/B/C"
compare(s1, s2) 'will result False

Example 4:

s1 = "(A/B)+C"
s2 = "A/(B+C)"
compare(s1, s2) 'will result False

Example 5:

s1 = "(B/A)+(B/C)"
s2 = "(C/B)+(B/A)"
compare(s1, s2) 'will result True

Example 6:

s1 = "A+B"
s2 = "A+W"
compare(s1, s2) 'will result False

Example 7:

s1 = "A/B+C"
s2 = "A/(B+C)"
compare(s1, s2) 'will result False

Example 8:

s1 = "A/B+C"
s2 = "(A/B)+C"
compare(s1, s2) 'will result True

Thanks a lot for any tips

Upvotes: 2

Views: 2110

Answers (1)

MP24
MP24

Reputation: 3200

I'd do a two-step approach inside the compare function. First, I'd replace each word with a number. Second, I'd evaluate the formula to see whether results are equal for both inputs.

Partly pseudo-code:

Function compare(s1 As String, s2 As String) As Boolean
    compare = parseAndEvaluate(s1) = parseAndEvaluate(s2)
End Function

Function parseAndEvaluate(str As String) As Long
    ' parse() needs to be implemented
    For Each charOrWord in parse(str)
        Select Case charOrWord
            Case "+", "/", "(", ")":
                parsedStr = parsedStr + charOrWord
            Case Else:
                ' map() needs to be implemented
                parsedStr = parsedStr + map(charOrWord)
        End Select
    Next

    parseAndEvaluate = Application.Evaluate(parsedStr)
End Function

The map() function could also be some kind of dictionary, assigning a new number (such as 1024, 2048, ...) to new words and mapping previously used words to the previously returned number.

The parse() function will read in the string and split at word boundaries.

If your operations + and / are more difficult, you'll need a slightly more complex parsing code, writing OR(..., ...) or AND(..., ...) into the string handed to Application.Evaluate.

Upvotes: 1

Related Questions