Created
June 29, 2021 12:28
-
-
Save lirlia/de0e2779b4d04fc6eca78d03156ae61d to your computer and use it in GitHub Desktop.
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 ( | |
"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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://blog.framinal.life/entry/2021/06/29/213901