-
Notifications
You must be signed in to change notification settings - Fork 376
/
inplace_shuffle_test.go
65 lines (52 loc) · 1.29 KB
/
inplace_shuffle_test.go
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
/*
Problem:
- Given a list of integers, shuffle its location in-place.
Example:
- Input: []int{1, 2, 3, 4, 5}
Output: []int{2, 1, 4, 3, 5}
Approach:
- Iterate through the list, swap current value with a value in a randomized
index that is between the current and last index.
Solution:
- Cache the last index value of the list.
- Iterate through the list, get a randomized index value between the
current index and the last index, then use it to swap the corresponding
values at these two indices.
Cost:
- O(n) time, O(1) space.
*/
package interviewcake
import (
"testing"
"github.com/hoanhan101/algo/common"
)
func TestInplaceShuffle(t *testing.T) {
tests := []struct {
in []int
expected []int
}{
{[]int{}, []int{}},
{[]int{1}, []int{1}},
{[]int{1, 2, 3, 4, 5}, []int{2, 1, 4, 3, 5}},
}
for _, tt := range tests {
result := inplaceShuffle(tt.in)
common.Equal(t, tt.expected, result)
}
}
func inplaceShuffle(list []int) []int {
// check edge case.
if len(list) <= 1 {
return list
}
lastIndex := len(list) - 1
for i := 0; i < len(list); i++ {
// get a andomized index that is between the current and last index.
randomIndex := common.Random(i, lastIndex)
// swap current value.
if i != randomIndex {
common.Swap(list, i, randomIndex)
}
}
return list
}