Improve day 5

This commit is contained in:
2022-12-05 19:48:13 +01:00
parent 6dd91762e4
commit bbaafe0164
3 changed files with 14 additions and 9 deletions

View File

@@ -16,11 +16,15 @@ func (stack *Stack) Push(crate byte) {
*stack = append(*stack, crate) *stack = append(*stack, crate)
} }
func (stack *Stack) Pop() byte { func (stack *Stack) Pop() (byte, bool) {
last := len(*stack) - 1 last := len(*stack) - 1
if last >= 0 {
top := (*stack)[last] top := (*stack)[last]
*stack = (*stack)[:last] *stack = (*stack)[:last]
return top return top, true
} else {
return 0, false
}
} }
func (stack *Stack) Peek() byte { func (stack *Stack) Peek() byte {

View File

@@ -12,7 +12,7 @@ func main() {
for _, movement := range(movements) { for _, movement := range(movements) {
for i := 0; i < movement.GetN(); i++ { for i := 0; i < movement.GetN(); i++ {
top := stacks[movement.GetStart() - 1].Pop() top, _ := stacks[movement.GetStart() - 1].Pop()
stacks[movement.GetEnd() - 1].Push(top) stacks[movement.GetEnd() - 1].Push(top)
} }
} }

View File

@@ -11,12 +11,13 @@ func main() {
stacks, movements := common.Parse(*bufio.NewScanner(os.Stdin)) stacks, movements := common.Parse(*bufio.NewScanner(os.Stdin))
for _, movement := range(movements) { for _, movement := range(movements) {
top := []byte{} topStack := common.Stack{}
for i := 0; i < movement.GetN(); i++ { for i := 0; i < movement.GetN(); i++ {
top = append(top, stacks[movement.GetStart() - 1].Pop()) top, _ := stacks[movement.GetStart() - 1].Pop()
topStack.Push(top)
} }
for i := len(top) - 1; i >= 0; i-- { for top, left := topStack.Pop(); left; top, left = topStack.Pop() {
stacks[movement.GetEnd() - 1].Push(top[i]) stacks[movement.GetEnd() - 1].Push(top)
} }
} }