Back to Repositories

Testing Hanoi Tower Algorithm Implementation in hello-algo

This test suite validates the implementation of the Hanoi Tower algorithm in Go, focusing on the recursive divide-and-conquer solution. It verifies 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 execution of the Hanoi Tower puzzle solution, verifying disk movements between three towers (A, B, and C).

  • Tests initialization of towers with 5 disks
  • Validates proper disk transfer operations
  • Verifies final state of all three towers
  • Ensures maintenance of disk size ordering rules

Implementation Analysis

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

  • Implements list operations for disk movement simulation
  • Uses fmt package for state visualization
  • Leverages custom PrintList utility for tower state verification
  • Employs recursive algorithm validation

Technical Details

Testing infrastructure includes:

  • Go testing framework (testing package)
  • container/list for data structure implementation
  • Custom hello-algo package utilities
  • Console output validation for state verification

Best Practices Demonstrated

The test implementation showcases several testing best practices in Go.

  • Clear test state initialization and cleanup
  • Visual state verification through formatted output
  • Modular test structure with focused test cases
  • Integration with custom utility functions for enhanced readability

krahets/hello-algo

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)
}