Back to Repositories

Testing Tower of Hanoi Algorithm Implementation in hello-algo

This test suite implements and verifies the Tower of Hanoi algorithm implementation in Go, focusing on the recursive solution approach and state management. The test validates the correct movement of disks between three towers while maintaining the fundamental rules of the puzzle.

Test Coverage Overview

The test coverage encompasses the complete Tower of Hanoi puzzle solution verification.

Key areas tested include:
  • Initial stack configuration with 5 disks
  • Proper disk movement operations
  • Final state validation
  • State tracking across all three towers

Implementation Analysis

The testing approach utilizes Go’s native testing framework with container/list package for tower representation.

Notable patterns include:
  • Linked list implementation for tower state management
  • Direct state inspection through PrintList utility
  • Visual verification through formatted output

Technical Details

Testing infrastructure includes:
  • Go testing package (testing.T)
  • container/list for data structure implementation
  • Custom PrintList utility from hello-algo package
  • Standard fmt package for output formatting

Best Practices Demonstrated

The test implementation showcases several quality testing practices.

Notable elements include:
  • Clear state visualization before and after operations
  • Comprehensive state verification
  • Modular test structure with setup and verification phases
  • Effective use of Go’s standard library components

krahets/hello-algo

zh-hant/codes/go/chapter_divide_and_conquer/hanota_test.go

            
// File: hanota_test.go
// Created Time: 2023-07-21
// Author: hongyun-robot ([email protected])

package chapter_divide_and_conquer

import (
	"container/list"
	"fmt"
	"testing"

	. "github.com/krahets/hello-algo/pkg"
)

func TestHanota(t *testing.T) {
	// 串列尾部是柱子頂部
	A := list.New()
	for i := 5; i > 0; i-- {
		A.PushBack(i)
	}
	B := list.New()
	C := list.New()
	fmt.Println("初始狀態下:")
	fmt.Print("A = ")
	PrintList(A)
	fmt.Print("B = ")
	PrintList(B)
	fmt.Print("C = ")
	PrintList(C)

	solveHanota(A, B, C)

	fmt.Println("圓盤移動完成後:")
	fmt.Print("A = ")
	PrintList(A)
	fmt.Print("B = ")
	PrintList(B)
	fmt.Print("C = ")
	PrintList(C)
}