# go高效洗牌算法

· · 2989 次点击 · · 开始浏览

package main

import (
"fmt"
"math/rand"
)

type Articlestruct {
Titlestring
Authorstring
}

var articles =[]Article{{Title:"Study golang",Author:"yuanfang"},{Title:"Effective golang",Author:"yuanfang"},{Title:"Effective python",Author:"yuanfang"}}

func main() {
newArticles :=[3]Article{}
l := rand.Perm(3)
for i:=0;i<3;i++ {
newArticles[i]=articles[l[i]]
}
fmt.Println(l)
fmt.Println(newArticles) }

func Perm(nint) []int {return globalRand.Perm(n) }

func (r *Rand)Perm(nint) []int {

m :=make([]int, n)

for i :=0; i < n; i++ {

m[i] = m[j]

m[j] = i

}

return m
}

2 回复  |  直到 2019-11-07 11:56:56

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

package main

import (
"fmt"
"math/rand"
)

type Articlestruct {
Titlestring
Authorstring
}

var articles =[]Article{{Title:"Study golang",Author:"yuanfang"},{Title:"Effective golang",Author:"yuanfang"},{Title:"Effective python",Author:"yuanfang"}}

func main() {
newArticles :=[3]Article{}
l := rand.Perm(3)
for i:=0;i<3;i++ {
newArticles[i]=articles[l[i]]
}
fmt.Println(l)
fmt.Println(newArticles) }

func Perm(nint) []int {return globalRand.Perm(n) }

func (r *Rand)Perm(nint) []int {

m :=make([]int, n)

for i :=0; i < n; i++ {

m[i] = m[j]

m[j] = i

}

return m
}