I am currently doing an A-level in Visual Basic and have had to create code that can take an inputted equation and translate it into reverse polish notation (postfix). The program works if the user enters their own brackets around the equation but does not work if they don’t. EG: entering ((5*5)+2) will return the correct answer, however 5*5+2 will simply return 552.

Could anybody help me create a subprocedure or function that takes an inputed equation and adds the brackets around it. so the input could be 5*5+2 and the return would be ((5*5)+2) so order of operations is kept!

Thank you so much for any help!!

Oh and so far I have created this, but it does not work and I am not sure why 🙁

`Public Sub AddBrackets(ByRef ExpressionIn As String) Dim startBracket As Integer Dim endBracket As Integer Dim signPosition As Integer Dim signs() As Char = {"/", "*", "+", "-"} Dim bracketCount As Integer Dim positionFound As Boolean = False If CountPairsOfBrackets(ExpressionIn) <> (CountOperands(ExpressionIn) - 1) Then For looper = 0 To signs.Length() - 1 Do While signPosition < ExpressionIn.Length - 1 If ExpressionIn(signPosition) = signs(looper) Then If IsNumeric(ExpressionIn(signPosition - 1)) Then startBracket = signPosition - 1 Else For looper2 = signPosition To 0 Step -1 If ExpressionIn(looper2) = ")" Then bracketCount += 1 ElseIf ExpressionIn(looper2) = "(" Then bracketCount -= 1 If bracketCount = 0 And positionFound = False Then startBracket = looper2 positionFound = True End If End If Next End If ExpressionIn = ExpressionIn.Insert(startBracket, "(") signPosition += 1 bracketCount = 0 positionFound = False If IsNumeric(ExpressionIn(signPosition + 1)) Then endBracket = signPosition + 2 Else For looper2 = signPosition To ExpressionIn.Length - 1 If ExpressionIn(looper2) = "(" Then bracketCount += 1 ElseIf ExpressionIn(looper2) = ")" Then bracketCount -= 1 If bracketCount = 0 And positionFound = False Then endBracket = looper2 positionFound = True End If End If Next End If ExpressionIn = ExpressionIn.Insert(endBracket, ")") End If signPosition += 1 bracketCount = 0 positionFound = False Loop signPosition = 0 Next End If `

End Sub

submitted by /u/elliot-ellzo

[link] [comments]