|
| 1 | +package twosum |
| 2 | + |
| 3 | +import ( |
| 4 | + "reflect" |
| 5 | + "testing" |
| 6 | +) |
| 7 | + |
| 8 | +func TestTwoSum(t *testing.T) { |
| 9 | + cases := []struct { |
| 10 | + name string |
| 11 | + fn func([]int, int) []int |
| 12 | + nums []int |
| 13 | + target int |
| 14 | + expected []int |
| 15 | + }{ |
| 16 | + // TwoSumBruteForce |
| 17 | + {"Brute Force - Valid Pair", TwoSumBruteForce, []int{2, 7, 11, 15}, 9, []int{0, 1}}, |
| 18 | + {"Brute Force - No Pair", TwoSumBruteForce, []int{1, 2, 3}, 7, nil}, |
| 19 | + {"Brute - Empty", TwoSumBruteForce, []int{}, 0, nil}, |
| 20 | + {"Brute - Single Element", TwoSumBruteForce, []int{5}, 5, nil}, |
| 21 | + {"Brute - Negative Numbers", TwoSumBruteForce, []int{-3, 4, 3, 90}, 0, []int{0, 2}}, |
| 22 | + {"Brute - Duplicates", TwoSumBruteForce, []int{3, 3}, 6, []int{0, 1}}, |
| 23 | + |
| 24 | + // Sorting (Two Pointer) |
| 25 | + {"Sorted - Valid Pair", TwoSumSorted, []int{2, 7, 11, 15}, 9, []int{0, 1}}, |
| 26 | + {"Sorted - No Pair", TwoSumSorted, []int{1, 2, 3}, 7, nil}, |
| 27 | + {"Sorted - Empty", TwoSumSorted, []int{}, 0, nil}, |
| 28 | + {"Sorted - Single Element", TwoSumSorted, []int{5}, 5, nil}, |
| 29 | + {"Sorted - Negative Numbers", TwoSumSorted, []int{-3, 4, 3, 90}, 0, []int{0, 2}}, |
| 30 | + {"Sorted - Duplicates", TwoSumSorted, []int{3, 3}, 6, []int{0, 1}}, |
| 31 | + |
| 32 | + // Map Two-Pass |
| 33 | + {"MapTwoPass - Valid Pair", TwoSumMapTwoPass, []int{2, 7, 11, 15}, 9, []int{0, 1}}, |
| 34 | + {"MapTwoPass - No Pair", TwoSumMapTwoPass, []int{1, 2, 3}, 7, nil}, |
| 35 | + {"MapTwoPass - Empty", TwoSumMapTwoPass, []int{}, 0, nil}, |
| 36 | + {"MapTwoPass - Single", TwoSumMapTwoPass, []int{5}, 5, nil}, |
| 37 | + {"MapTwoPass - Negative", TwoSumMapTwoPass, []int{-3, 4, 3, 90}, 0, []int{0, 2}}, |
| 38 | + {"MapTwoPass - Duplicates", TwoSumMapTwoPass, []int{3, 3}, 6, []int{0, 1}}, |
| 39 | + |
| 40 | + // Map One-Pass |
| 41 | + {"MapOnePass - Valid Pair", TwoSumMapOnePass, []int{2, 7, 11, 15}, 9, []int{0, 1}}, |
| 42 | + {"MapOnePass - No Pair", TwoSumMapOnePass, []int{1, 2, 3}, 7, nil}, |
| 43 | + {"MapOnePass - Empty", TwoSumMapOnePass, []int{}, 0, nil}, |
| 44 | + {"MapOnePass - Single", TwoSumMapOnePass, []int{5}, 5, nil}, |
| 45 | + {"MapOnePass - Negative", TwoSumMapOnePass, []int{-3, 4, 3, 90}, 0, []int{0, 2}}, |
| 46 | + {"MapOnePass - Duplicates", TwoSumMapOnePass, []int{3, 3}, 6, []int{0, 1}}, |
| 47 | + } |
| 48 | + |
| 49 | + for _, c := range cases { |
| 50 | + t.Run(c.name, func(t *testing.T) { |
| 51 | + got := c.fn(c.nums, c.target) |
| 52 | + if !reflect.DeepEqual(got, c.expected) { |
| 53 | + t.Errorf("%s failed: expected %v, got %v", c.name, c.expected, got) |
| 54 | + } |
| 55 | + }) |
| 56 | + } |
| 57 | +} |
0 commit comments