fix evaluator
This commit is contained in:
		
							parent
							
								
									7de370e3f9
								
							
						
					
					
						commit
						323fd70370
					
				
					 1 changed files with 8 additions and 8 deletions
				
			
		|  | @ -10,8 +10,8 @@ import ( | ||||||
| 
 | 
 | ||||||
| // Dijkstra's two stack algorithm for equation evaluation | // Dijkstra's two stack algorithm for equation evaluation | ||||||
| func Evaluate(exression string) int { | func Evaluate(exression string) int { | ||||||
| 	operations := stack.NewStack() | 	operations := stack.NewStack[string]() | ||||||
| 	values := stack.NewStack() | 	values := stack.NewStack[int]() | ||||||
| 
 | 
 | ||||||
| 	for _, part := range strings.Split(exression, " ") { | 	for _, part := range strings.Split(exression, " ") { | ||||||
| 		isOperation := part == "+" || part == "-" || part == "*" || part == "/" || part == "sqrt" | 		isOperation := part == "+" || part == "-" || part == "*" || part == "/" || part == "sqrt" | ||||||
|  | @ -20,17 +20,17 @@ func Evaluate(exression string) int { | ||||||
| 			continue | 			continue | ||||||
| 		} else if part == ")" { | 		} else if part == ")" { | ||||||
| 			lastOperation := operations.Pop() | 			lastOperation := operations.Pop() | ||||||
| 			lastValue := values.Pop().(int) | 			lastValue := values.Pop() | ||||||
| 
 | 
 | ||||||
| 			switch lastOperation { | 			switch lastOperation { | ||||||
| 			case "+": | 			case "+": | ||||||
| 				lastValue = values.Pop().(int) + lastValue | 				lastValue = values.Pop() + lastValue | ||||||
| 			case "-": | 			case "-": | ||||||
| 				lastValue = values.Pop().(int) - lastValue | 				lastValue = values.Pop() - lastValue | ||||||
| 			case "*": | 			case "*": | ||||||
| 				lastValue = values.Pop().(int) * lastValue | 				lastValue = values.Pop() * lastValue | ||||||
| 			case "/": | 			case "/": | ||||||
| 				lastValue = values.Pop().(int) / lastValue | 				lastValue = values.Pop() / lastValue | ||||||
| 			case "sqrt": | 			case "sqrt": | ||||||
| 				lastValue = int(math.Sqrt(float64(lastValue))) | 				lastValue = int(math.Sqrt(float64(lastValue))) | ||||||
| 			} | 			} | ||||||
|  | @ -43,5 +43,5 @@ func Evaluate(exression string) int { | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
| 
 | 
 | ||||||
| 	return values.Pop().(int) | 	return values.Pop() | ||||||
| } | } | ||||||
|  |  | ||||||
		Loading…
	
	Add table
		
		Reference in a new issue