summaryrefslogtreecommitdiff
path: root/factors/factors_test.go
blob: a2e81cd84a039bb340afbc0c8a84bd320c50589f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package factors

import (
	"fmt"
	"testing"
)

var primeFactorCases = map[uint]PrimeFactorization{
	0: PrimeFactorization{map[uint]uint{0: 1}},
	1: PrimeFactorization{map[uint]uint{}},
	2: PrimeFactorization{map[uint]uint{2: 1}},
	3: PrimeFactorization{map[uint]uint{3: 1}},
	4: PrimeFactorization{map[uint]uint{2: 2}},
	6: PrimeFactorization{map[uint]uint{2: 1, 3: 1}},
	10: PrimeFactorization{map[uint]uint{2: 1, 5: 1}},
	12: PrimeFactorization{map[uint]uint{2: 2, 3: 1}},
	33: PrimeFactorization{map[uint]uint{3: 1, 11: 1}},
	60: PrimeFactorization{map[uint]uint{2: 2, 3: 1, 5: 1}},
	86400: PrimeFactorization{map[uint]uint{2: 7, 3: 3, 5: 2}},
}

func TestPrimeFactorize(t *testing.T) {
	for i, expected := range primeFactorCases {
		testname := fmt.Sprintf("%d", i)
		t.Run(testname, func(t *testing.T) {
			actual := PrimeFactorize(i)
			if !mapEquals(expected.exponents, actual.exponents) {
				t.Errorf("PrimeFactorize(%d) = %s, want %s", i, actual, expected)
			}
		})
	}
}

var factorCases = map[uint][]uint{
	1: []uint{1},
	2: []uint{1, 2},
	4: []uint{1, 2, 4},
	6: []uint{1, 2, 3, 6},
	10: []uint{1, 2, 5, 10},
	12: []uint{1, 2, 3, 4, 6, 12},
	13: []uint{1, 13},
	15: []uint{1, 3, 5, 15},
	18: []uint{1, 2, 3, 6, 9, 18},
	60: []uint{1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, 60},
}

func TestFactors(t *testing.T) {
	for i, expected := range factorCases {
		testname := fmt.Sprintf("%d", i)
		t.Run(testname, func(t *testing.T) {
			actual := Factors(i)
			if !setEquals(expected, actual) {
				t.Errorf("Factors(%d) = %v, want %v", i, actual, expected)
			}
		})
	}
}

func setEquals(a, b []uint) bool {
	// use maps to simulate sets
	// aSet[a] == true means set contains a, false means not
	aSet := make(map[uint]bool)
	bSet := make(map[uint]bool)
	for _, i := range a {
		aSet[i] = true
	}
	for _, j := range b {
		bSet[j] = true
	}
	return mapEquals(aSet, bSet)
}

func mapEquals[K comparable, V comparable](a, b map[K]V) bool {
	for k := range a {
		if a[k] != b[k] {
			return false
		}
	}
	for k := range b {
		if a[k] != b[k] {
			return false
		}
	}
	return true
}