< up >
2022-12-06

aoc2022-5 - generic stack

This puzzle can be solved straight forward by implementing a stack and process the move instructions properly. Since it is past august 20221, let’s implement it with generics to make it type-independent:

type Stack[T any] struct {
  items []T
}

The first array element of item is the bottom of the stack, while the last item represents the top. For completeness, during initialization, the items are read in reverse order, so a PushAhead function is needed which adds an item at the beginning of the array.

func (s *Stack[T]) PushAhead(item T) {
  s.items = append([]T{item}, s.items...)
}

star 1 - business as usual

Problem: The first star requires to move each item separately between the stacks.

Solution: Iteratively pop each item from the source stack and push it onto the destination one.

func (s *Stack[T]) Push(item T) {
  s.items = append(s.items, item) 
}

func (s *Stack[T]) Pop() T {
  item := s.items[len(s.items)-1]
  s.items = s.items[:len(s.items)-1]
  return item
}

star 2 - chain the supplies

Problem: All items contained in an move instruction should be pushed at once (chained) to the destination stack, remaining in the same order.

Solution: Pop and Push multiple items at once via PushN and PopN.

func (s *Stack[T]) PushN(items []T) {
  s.items = append(s.items, items...)
}

func (s *Stack[T]) PopN(l int) []T{
  items := append([]T{},s.items[len(s.items)-l:]...)
  s.items = s.items[:len(s.items)-l]
  return items
}

  1. Generics got finally introduced with go 1.19.