當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


GO Shuffle用法及代碼示例

GO語言"math/rand"包中"Shuffle"函數的用法及代碼示例。

用法:

func Shuffle(n int, swap func(i, j int))

使用默認 Source Shuffle[洗牌] pseudo-randomizes 元素的順序。 n 是元素的數量。如果 n < 0,則 Shuffle Panics。swap 交換索引為 i 和 j 的元素。

例子:

package main

import (
	"fmt"
	"math/rand"
	"strings"
)

func main() {
	words := strings.Fields("ink runs from the corners of my mouth")
	rand.Shuffle(len(words), func(i, j int) {
		words[i], words[j] = words[j], words[i]
	})
	fmt.Println(words)

}

輸出:

[mouth my the of runs corners from ink]

示例(SlicesInUnison):

package main

import (
	"fmt"
	"math/rand"
)

func main() {
	numbers := []byte("12345")
	letters := []byte("ABCDE")
	// Shuffle numbers, swapping corresponding entries in letters at the same time.
	rand.Shuffle(len(numbers), func(i, j int) {
		numbers[i], numbers[j] = numbers[j], numbers[i]
		letters[i], letters[j] = letters[j], letters[i]
	})
	for i := range numbers {
		fmt.Printf("%c: %c\n", letters[i], numbers[i])
	}

}

輸出:

C: 3
D: 4
A: 1
E: 5
B: 2

相關用法


注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 Shuffle。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。