|
| 1 | +package lll |
| 2 | + |
| 3 | +import ( |
| 4 | + "testing" |
| 5 | + |
| 6 | + "github.com/stretchr/testify/assert" |
| 7 | +) |
| 8 | + |
| 9 | +func TestCopyRandomList(t *testing.T) { |
| 10 | + // Helper function to build linked list from input |
| 11 | + buildList := func(input [][]interface{}) *Node { |
| 12 | + if len(input) == 0 { |
| 13 | + return nil |
| 14 | + } |
| 15 | + nodes := make([]*Node, len(input)) |
| 16 | + for i, val := range input { |
| 17 | + nodes[i] = &Node{Val: val[0].(int)} |
| 18 | + } |
| 19 | + for i, val := range input { |
| 20 | + if i < len(input)-1 { |
| 21 | + nodes[i].Next = nodes[i+1] |
| 22 | + } |
| 23 | + if val[1] != nil { |
| 24 | + nodes[i].Random = nodes[val[1].(int)] |
| 25 | + } |
| 26 | + } |
| 27 | + return nodes[0] |
| 28 | + } |
| 29 | + |
| 30 | + // Helper function to convert list to [][]interface{} for comparison |
| 31 | + convertList := func(head *Node) [][]interface{} { |
| 32 | + var result [][]interface{} |
| 33 | + indexMap := make(map[*Node]int) |
| 34 | + cur := head |
| 35 | + index := 0 |
| 36 | + for cur != nil { |
| 37 | + indexMap[cur] = index |
| 38 | + cur = cur.Next |
| 39 | + index++ |
| 40 | + } |
| 41 | + cur = head |
| 42 | + for cur != nil { |
| 43 | + if cur.Random != nil { |
| 44 | + result = append(result, []interface{}{cur.Val, indexMap[cur.Random]}) |
| 45 | + } else { |
| 46 | + result = append(result, []interface{}{cur.Val, nil}) |
| 47 | + } |
| 48 | + |
| 49 | + cur = cur.Next |
| 50 | + } |
| 51 | + return result |
| 52 | + } |
| 53 | + |
| 54 | + tests := []struct { |
| 55 | + name string |
| 56 | + input [][]interface{} |
| 57 | + expected [][]interface{} |
| 58 | + }{ |
| 59 | + { |
| 60 | + name: "Example 1", |
| 61 | + input: [][]interface{}{{7, nil}, {13, 0}, {11, 4}, {10, 2}, {1, 0}}, |
| 62 | + expected: [][]interface{}{{7, nil}, {13, 0}, {11, 4}, {10, 2}, {1, 0}}, |
| 63 | + }, |
| 64 | + { |
| 65 | + name: "Example 2", |
| 66 | + input: [][]interface{}{{1, 1}, {2, 1}}, |
| 67 | + expected: [][]interface{}{{1, 1}, {2, 1}}, |
| 68 | + }, |
| 69 | + { |
| 70 | + name: "Example 3", |
| 71 | + input: [][]interface{}{{3, nil}, {3, 0}, {3, nil}}, |
| 72 | + expected: [][]interface{}{{3, nil}, {3, 0}, {3, nil}}, |
| 73 | + }, |
| 74 | + } |
| 75 | + |
| 76 | + for _, tt := range tests { |
| 77 | + t.Run(tt.name, func(t *testing.T) { |
| 78 | + head := buildList(tt.input) |
| 79 | + copiedList := copyRandomList(head) |
| 80 | + assert.Equal(t, tt.expected, convertList(copiedList)) |
| 81 | + }) |
| 82 | + } |
| 83 | +} |
0 commit comments