Back to Repositories

zh-hant/codes/go/chapter_backtracking/subset_sum_test.go

This test suite implements and validates subset sum algorithms in Go, focusing on finding subsets of numbers that sum to a target value. The tests cover three different implementations: naive, optimized, and handling duplicates.

Test Coverage Overview

The test suite provides comprehensive coverage of subset sum algorithm implementations:
  • TestSubsetSumINaive: Tests basic subset sum functionality with potential duplicates
  • TestSubsetSumI: Validates optimized subset sum implementation
  • TestSubsetSumII: Verifies handling of duplicate numbers in input array

Implementation Analysis

The testing approach utilizes Go’s native testing framework with targeted test cases. Each test function implements specific input validation scenarios using arrays and target sums, with clear output formatting and slice printing functionality.

The implementation leverages Go’s testing patterns with imported custom printing utilities from the hello-algo package.

Technical Details

Testing tools and configuration:
  • Go testing framework (testing package)
  • Custom PrintSlice utility from hello-algo package
  • strconv package for number conversion
  • fmt package for formatted output

Best Practices Demonstrated

The test suite exhibits several testing best practices:
  • Clear test function naming conventions
  • Isolated test cases for different implementations
  • Consistent input/output formatting
  • Proper package organization and imports
  • Comprehensive documentation with test purpose comments

krahets/hello-algo

zh-hant/codes/go/chapter_backtracking/subset_sum_test.go

            
// File: subset_sum_test.go
// Created Time: 2023-06-24
// Author: Reanon ([email protected])

package chapter_backtracking

import (
	"fmt"
	"strconv"
	"testing"

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

func TestSubsetSumINaive(t *testing.T) {
	nums := []int{3, 4, 5}
	target := 9
	res := subsetSumINaive(nums, target)

	fmt.Printf("target = " + strconv.Itoa(target) + ", 輸入陣列 nums = ")
	PrintSlice(nums)

	fmt.Println("所有和等於 " + strconv.Itoa(target) + " 的子集 res = ")
	for i := range res {
		PrintSlice(res[i])
	}
	fmt.Println("請注意,該方法輸出的結果包含重複集合")
}

func TestSubsetSumI(t *testing.T) {
	nums := []int{3, 4, 5}
	target := 9
	res := subsetSumI(nums, target)

	fmt.Printf("target = " + strconv.Itoa(target) + ", 輸入陣列 nums = ")
	PrintSlice(nums)

	fmt.Println("所有和等於 " + strconv.Itoa(target) + " 的子集 res = ")
	for i := range res {
		PrintSlice(res[i])
	}
}

func TestSubsetSumII(t *testing.T) {
	nums := []int{4, 4, 5}
	target := 9
	res := subsetSumII(nums, target)

	fmt.Printf("target = " + strconv.Itoa(target) + ", 輸入陣列 nums = ")
	PrintSlice(nums)

	fmt.Println("所有和等於 " + strconv.Itoa(target) + " 的子集 res = ")
	for i := range res {
		PrintSlice(res[i])
	}
}