From a515a19ad7f250f60e630c07563cf39d53c30a79 Mon Sep 17 00:00:00 2001 From: VicRen Date: Sun, 13 Aug 2023 20:15:04 +0800 Subject: [PATCH] code kata 230813 --- code_kata_230812/prime_factors_test.go | 47 ++++++++++++++++++++++++++ code_kata_230813/int_to_string_test.go | 32 ++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 code_kata_230812/prime_factors_test.go create mode 100644 code_kata_230813/int_to_string_test.go diff --git a/code_kata_230812/prime_factors_test.go b/code_kata_230812/prime_factors_test.go new file mode 100644 index 0000000..c915c21 --- /dev/null +++ b/code_kata_230812/prime_factors_test.go @@ -0,0 +1,47 @@ +package main + +import ( + "reflect" + "testing" +) + +func PrimeFactorsOf(n int) []int { + ret := make([]int, 0) + d := 2 + for d < n { + for n%d == 0 { + ret = append(ret, d) + n /= d + } + d++ + } + if n > 1 { + ret = append(ret, n) + } + return ret +} + +func TestPrimeFactorsOf(t *testing.T) { + tt := []struct { + name string + input int + want []int + }{ + {"1", 1, []int{}}, + {"2", 2, []int{2}}, + {"3", 3, []int{3}}, + {"4", 4, []int{2, 2}}, + {"8", 8, []int{2, 2, 2}}, + {"9", 9, []int{3, 3}}, + {"a very large number", 2 * 3 * 17 * 37 * 71 * 73, []int{2, 3, 17, 37, 71, 73}}, + } + + for _, tc := range tt { + t.Run(tc.name, func(t *testing.T) { + got := PrimeFactorsOf(tc.input) + if !reflect.DeepEqual(got, tc.want) { + t.Errorf("PrimeFactorsOf(%d) = %v, want %v\n", tc.input, got, tc.want) + } + }) + } +} diff --git a/code_kata_230813/int_to_string_test.go b/code_kata_230813/int_to_string_test.go new file mode 100644 index 0000000..01e82c0 --- /dev/null +++ b/code_kata_230813/int_to_string_test.go @@ -0,0 +1,32 @@ +package main + +import "testing" + +func IntToString(n int) string { + ret := make([]byte, 0) + for n > 0 { + ret = append([]byte{byte('0' + n%10)}, ret...) + n /= 10 + } + return string(ret) +} + +func TestIntToString(t *testing.T) { + tt := []struct { + name string + input int + want string + }{ + {"1", 1, "1"}, + {"12345678", 12345678, "12345678"}, + } + + for _, tc := range tt { + t.Run(tc.name, func(t *testing.T) { + got := IntToString(tc.input) + if got != tc.want { + t.Errorf("IntToString(%d) = %s, want %s\n", tc.input, got, tc.want) + } + }) + } +}