Last active
May 17, 2023 02:55
-
-
Save caelifer/951ae91ca18bf7674033ed217cbcb025 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
const height = 5 | |
func main() { | |
a := NewStack("Src. ", height) | |
b := NewStack("Dst. ", height) | |
c := NewStack("Spare", height) | |
// Add initial disk | |
for i := 0; i < height; i++ { | |
a.AddDisk(height - i - 1) | |
} | |
t0 := time.Now() | |
moves := 0 | |
moveTower(a.Len()-1, a, b, c, func() { | |
moves++ | |
fmt.Printf("--- Move #%d ---\n", moves) | |
fmt.Println(a) | |
fmt.Println(b) | |
fmt.Println(c) | |
fmt.Println() | |
}) | |
fmt.Printf("Moving tower of height %d took %d moves in %v\n", height, moves, time.Since(t0)) | |
} | |
func moveDisk(src, dst *Stack, trace func()) { | |
dst.AddDisk(src.RemoveDisk()) | |
trace() | |
} | |
func moveTower(idx int, src, dst, spare *Stack, trace func()) { | |
if idx == 0 { | |
moveDisk(src, dst, trace) | |
return | |
} | |
moveTower(idx-1, src, spare, dst, trace) | |
moveDisk(src, dst, trace) | |
moveTower(idx-1, spare, dst, src, trace) | |
} | |
type Stack struct { | |
name string | |
stack []int | |
} | |
func NewStack(name string, size int) *Stack { | |
return &Stack{ | |
name: name, | |
stack: make([]int, 0, size), | |
} | |
} | |
func (st *Stack) AddDisk(idx int) { | |
l := len(st.stack) | |
if l == cap(st.stack) { | |
panic("Too many disk on stack " + st.name) | |
} | |
if l != 0 && st.stack[l-1] <= idx { | |
panic("Cannot add smaller disk to stack " + st.name) | |
} | |
st.stack = append(st.stack, idx) | |
} | |
func (st *Stack) RemoveDisk() int { | |
l := len(st.stack) | |
if l == 0 { | |
panic("Empty stack " + st.name) | |
} | |
res := st.stack[l-1] | |
st.stack = st.stack[0 : l-1] | |
return res | |
} | |
func (st *Stack) Len() int { | |
return len(st.stack) | |
} | |
func (st *Stack) String() string { | |
return fmt.Sprintf("%q: %v", st.name, st.stack) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Live code - https://play.golang.org/p/rNLlO2VTK_
Output: