Skip to content

Commit 26d2b14

Browse files
authored
Merge pull request #2 from golang-infrastructure/fix-#1
fix:#1
2 parents 052d74e + 03c18dc commit 26d2b14

File tree

2 files changed

+8
-12
lines changed

2 files changed

+8
-12
lines changed

fisher_yates_knuth_shuffle.go

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,9 @@ func FisherYatesKnuthShuffle[T any](slice []T) {
1818

1919
// FisherYatesShuffleMatrix Fisher–Yates-Knuth shuffle算法对矩阵洗牌
2020
func FisherYatesShuffleMatrix[T any](matrix [][]T) {
21-
for i := len(matrix) - 1; i >= 0; i-- {
22-
for j := len(matrix[i]) - 1; j >= 0; j-- {
23-
chooseI := standaloneRand.Intn(i + 1)
24-
chooseJ := standaloneRand.Intn(j + 1)
25-
matrix[chooseI][chooseJ], matrix[i][j] = matrix[i][j], matrix[chooseI][chooseJ]
26-
}
21+
row, col := len(matrix), len(matrix[0])
22+
for index := row*col - 1; index > 0; index-- {
23+
chooseIndex := standaloneRand.Intn(index + 1)
24+
matrix[index/col][index%col], matrix[chooseIndex/col][chooseIndex%col] = matrix[chooseIndex/col][chooseIndex%col], matrix[index/col][index%col]
2725
}
2826
}

sattolo.go

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,9 @@ func SattoloShuffle[T any](slice []T) {
99
}
1010

1111
func SattoloShuffleMatrix[T any](matrix [][]T) {
12-
for i := len(matrix) - 1; i >= 0; i-- {
13-
for j := len(matrix[i]) - 1; j >= 0; j-- {
14-
chooseI := standaloneRand.Intn(i + 1)
15-
chooseJ := standaloneRand.Intn(j + 1)
16-
matrix[chooseI][chooseJ], matrix[i][j] = matrix[i][j], matrix[chooseI][chooseJ]
17-
}
12+
row, col := len(matrix), len(matrix[0])
13+
for index := row*col - 1; index > 0; index-- {
14+
chooseIndex := standaloneRand.Intn(index)
15+
matrix[index/col][index%col], matrix[chooseIndex/col][chooseIndex%col] = matrix[chooseIndex/col][chooseIndex%col], matrix[index/col][index%col]
1816
}
1917
}

0 commit comments

Comments
 (0)