-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstack.go
128 lines (111 loc) · 1.93 KB
/
stack.go
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package piet
type stack struct {
data []int
}
func (s stack) hasAtLeast1() bool {
return len(s.data) >= 1
}
func (s stack) hasAtLeast2() bool {
return len(s.data) >= 2
}
func (s *stack) push(n int) {
s.data = append(s.data, n)
}
func (s *stack) pop() (n int) {
if s.hasAtLeast1() {
n, s.data = s.data[len(s.data)-1], s.data[0:len(s.data)-1]
}
return
}
func (s *stack) add() {
if s.hasAtLeast2() {
x, y := s.pop(), s.pop()
s.push(x + y)
}
}
func (s *stack) subtract() {
if s.hasAtLeast2() {
top, second := s.pop(), s.pop()
s.push(second - top)
}
}
func (s *stack) multiply() {
if s.hasAtLeast2() {
x, y := s.pop(), s.pop()
s.push(x * y)
}
}
func (s *stack) divide() {
if !s.hasAtLeast2() {
return
}
top, second := s.pop(), s.pop()
if top == 0 {
// Put them back so this becomes a no-op.
s.push(second)
s.push(top)
} else {
s.push(second / top)
}
}
func (s *stack) mod() {
if !s.hasAtLeast2() {
return
}
top, second := s.pop(), s.pop()
if top != 0 {
// Put them back so this becomes a no-op.
s.push(second)
s.push(top)
}
s.push(second % top)
}
func (s *stack) not() {
if s.hasAtLeast1() {
top := s.pop()
if top == 0 {
s.push(1)
} else {
s.push(0)
}
}
}
func (s *stack) greater() {
if s.hasAtLeast2() {
top, second := s.pop(), s.pop()
if second > top {
s.push(1)
} else {
s.push(0)
}
}
}
func (s *stack) duplicate() {
if s.hasAtLeast1() {
top := s.data[len(s.data)-1]
s.data = append(s.data, top)
}
}
func (s *stack) roll() {
if !s.hasAtLeast2() {
return
}
numRolls, depth := s.pop(), s.pop()
if depth < 0 || depth >= len(s.data) {
// Undo.
s.push(depth)
s.push(numRolls)
return
}
if numRolls < 0 {
panic("Negative number of rolls not yet implemented")
}
for r := 0; r < numRolls; r++ {
index := len(s.data) - depth
val := s.data[len(s.data)-1]
for i := len(s.data) - 1; i > index; i-- {
s.data[i] = s.data[i-1]
}
s.data[index] = val
}
}