Stacks and queues
Chunky is making pancakes and puts each fresh one on top of the pile. They get eaten from the top as well – the one baked last comes first. Such a stack is one of the most useful ideas in programming, and in Ruby every array is one: push puts something on top (at the end), pop takes the top one off, and last just looks at what is on top:
stack = []
stack.push("pancake 1")
stack.push("pancake 2")
stack.push("pancake 3")
p stack.last # just look
p stack.pop # take it off
stackLast in, first out – LIFO for short. That's why a stack turns everything round: put the letters of a word on one by one and take them off again until the stack is empty (pop on an empty stack would simply give nil):
stack = []
"bacon".chars.each { |ch| stack.push(ch) }
reversed = ""
until stack.empty?
reversed << stack.pop
end
reversedYou know the stack from every editor: undo. Before each change, the program puts the old state on a stack, and undo takes the top one off again – always the latest change first:
text = "Chunky"
history = []
%w[loves crispy bacon].each do |word|
history.push(text) # remember the old state
text = "#{text} #{word}"
end
puts text
text = history.pop # undo
puts text
text = history.pop # undo once moreRuby itself keeps a stack too: the call stack. When a method calls another, the new call goes on top; when it is done, it is taken off, and Ruby carries on where it was interrupted. caller_locations shows the stack from the inside, the top first:
def morning
make_coffee
end
def make_coffee
grind_beans
end
def grind_beans
caller_locations(0, 3).map(&:base_label) # the call stack, top first
end
morningThat is the room for waiting calls from lesson 30: a recursion without a base case puts call after call on the stack until it overflows – SystemStackError: stack level too deep. And that an error message knows in which method and line things went wrong (lesson 28) is thanks to the call stack too.
The counterpart of the stack is the queue, as at the bakery: whoever comes first is served first – first in, first out, FIFO. Newcomers join at the back (push), serving happens at the front (shift):
queue = []
queue.push("Chunky")
queue.push("Kaz")
queue.push("Isi")
p queue.shift # whoever came first is served first
queue.push("Bo")
queueKaz is at the front now, Bo at the very back. With a queue everyone takes their turn, in a circle too: whoever has had a turn joins the back again – queue.push(queue.shift). That is how a counting-out rhyme in a circle works: the first two join the back again, the third is out – until only one is left:
circle = %w[Chunky Kaz Isi Bo Mo]
until circle.size == 1
2.times { circle.push(circle.shift) } # two join the back again
puts "#{circle.shift} is out"
end
circle.firstBo wins. And now back to the stack, for a job every code editor does: do the brackets match? For one kind of bracket a counter is enough: ( counts up, ) counts down. It must never drop below 0 (a bracket would close that never opened), and at the end it must be 0:
def round_brackets_ok?(text)
open = 0
text.each_char do |ch|
open += 1 if ch == "("
open -= 1 if ch == ")"
return false if open < 0 # closed before it was opened
end
open == 0
end
p round_brackets_ok?("(bacon (and egg))")
p round_brackets_ok?("(bacon))(")
round_brackets_ok?("([)]")The last true is wrong: in ([)] the round brackets match on their own, but the ] closes while the ( inside is still open. With three kinds of bracket no counter helps any more – not even three counters. What matters is the order, and a stack remembers it: every opening bracket goes on top, and every closing one must match the top one.
The rule of thumb: if you always have to deal with the newest thing first – undo, brackets, calls, stepping back in the backtracking of lesson 36 – use a stack: push and pop. If the oldest comes first – customers, players, jobs – use a queue: push and shift.
balanced?(text): true when all round, square and curly brackets in the text match up properly, otherwise false. Everything else in the text doesn't count. Put every opening bracket on a stack; at a closing one, its partner must be on top – take it off. At the end the stack must be empty.# def balanced?(text)
# partner = { ")" => "(", "]" => "[", "}" => "{" }
# stack = []
# ... # an opening bracket: onto the stack
# ... # a closing one: its partner must be on top – take it off
# ... # at the end: is the stack empty?
# end
# balanced?("{bacon [and (egg)]}")
3 4 + 2 * means (3 + 4) · 2 = 14. It is worked out with a stack: a number goes on top; an operator takes the top two off, calculates, and puts the result back. At the end only the result is left. Write rpn(text) for +, -, * and / with whole numbers. Careful with - and /: the number you take off first is the right one – 10 4 - is 6.# def rpn(text)
# stack = []
# text.split.each do |part|
# ... # an operator: right = stack.pop, left = stack.pop, calculate
# ... # otherwise it is a number: part.to_i onto the stack
# end
# stack.last
# end
# rpn("3 4 + 2 *")