Created
September 27, 2013 04:24
-
-
Save skoowoo/6724116 to your computer and use it in GitHub Desktop.
go runtime中的洗牌算法测试
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"math/rand" | |
"time" | |
"fmt" | |
) | |
var report map[int][]int | |
func shuffle(r *rand.Rand) { | |
var data [10]int | |
for i := 0; i < 10; i++ { | |
data[i] = i | |
} | |
for i := 0; i < 10; i++ { | |
o := data[i] | |
j := r.Int() % (i + 1) | |
data[i] = data[j] | |
data[j] = o | |
} | |
for i := 0; i < 10; i++ { | |
pos_list := report[data[i]] | |
pos_list[i]++ | |
} | |
} | |
func main() { | |
// init | |
report = make(map[int][]int, 10) | |
for i := 0; i < 10; i++ { | |
report[i] = make([]int, 10) | |
} | |
// shuffling | |
src := rand.NewSource(time.Now().UnixNano()) | |
r := rand.New(src) | |
for n := 0; n < 10000; n++ { | |
shuffle(r) | |
} | |
// report result | |
for k, v := range report { | |
fmt.Printf("%d -> ", k) | |
for _, p := range v { | |
fmt.Printf("%5d ", p) | |
} | |
fmt.Printf("\n") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
测试结果,每个数字出现在数组各个位置的次数
2 -> 969 1004 999 998 916 1058 983 1028 1042 1003
1 -> 1007 989 1006 991 972 1022 996 1013 995 1009
7 -> 1022 1024 992 1022 1058 956 1028 978 959 961
3 -> 1018 1014 1009 999 1013 945 989 982 1025 1006
4 -> 990 995 1007 1027 981 963 974 993 1003 1067
8 -> 1008 989 1029 963 1037 1036 1036 974 941 987
9 -> 993 1000 979 1018 1040 1021 1020 917 1003 1009
0 -> 1016 993 940 1009 1020 1032 1006 996 988 1000
5 -> 1003 976 1020 977 972 1001 947 1062 1054 988
6 -> 974 1016 1019 996 991 966 1021 1057 990 970