forked from bjssacademy/stackmachine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstackmachine.go
More file actions
69 lines (52 loc) · 1.15 KB
/
Copy pathstackmachine.go
File metadata and controls
69 lines (52 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package main
import (
"errors"
"strings"
)
const MAX_NUMBER_LIMIT = 50000
const MIN_ELEMENTS_FOR_SINGLE_OPS = 1
const MIN_ELEMENTS_FOR_DOUBLE_OPS = 2
type Machine struct {
stack []int
}
func StackMachine(commands string) (int, error) {
if len(commands) == 0 {
return 0, errors.New("empty command")
}
commandSlice := strings.Split(commands, " ")
machine := Machine{
stack: []int{},
}
for _, command := range commandSlice {
operation := CreateOperation(command, &machine)
err := operation.Execute()
if err != nil {
return 0, err
}
}
if machine.isStackEmpty() {
return 0, nil
}
firstNumInStack := machine.stack[0]
return firstNumInStack, nil
}
func CreateOperation(command string, m *Machine) Operation {
switch command {
case "POP":
return &PopOperation{machine: m}
case "DUP":
return &DupOperation{machine: m}
case "CLEAR":
return &ClearOperation{machine: m}
case "SUM":
return &SumOperation{machine: m}
case "+":
return &AddOperation{machine: m}
case "-":
return &MinusOperation{machine: m}
case "*":
return &MultiplyOperation{machine: m}
default:
return &NumbersOperation{machine: m, args: command}
}
}