Skip to content

Instantly share code, notes, and snippets.

@lirlia
Created June 29, 2021 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lirlia/de0e2779b4d04fc6eca78d03156ae61d to your computer and use it in GitHub Desktop.
Save lirlia/de0e2779b4d04fc6eca78d03156ae61d to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math/rand"
"sort"
)
// slice内に指定の値があるかをチェックして
// 要素番号を返す関数
func index(slice []string, item string) int {
for i := range slice {
if slice[i] == item {
return i
}
}
return -1
}
// 配列をシャッフルする
func shuffle(data []day) {
n := len(data)
for i := n - 1; i >= 0; i-- {
j := rand.Intn(i + 1)
data[i], data[j] = data[j], data[i]
}
}
type day struct {
name string
}
func main() {
dayNameList := []day{
day{"Sunday"},
day{"Monday"},
day{"Tuesday"},
day{"Wednesday"},
day{"Thursday"},
day{"Friday"},
day{"Saturday"},
}
// 曜日の並び順
orderList := []string{
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
}
// まずは普通に表示
shuffle(dayNameList)
fmt.Println("Shuffle: \n", dayNameList)
// 並び替え
sort.Slice(dayNameList, func(i, j int) bool {
return index(orderList, dayNameList[i].name) < index(orderList, dayNameList[j].name)
})
// 再度表示
fmt.Println("After Sort: \n", dayNameList)
}
@lirlia
Copy link
Author

lirlia commented Jun 29, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment