github.com/noisysockets/noisysockets@v0.21.2-0.20240515114641-7f467e651c90/internal/util/shuffle.go (about) 1 // SPDX-License-Identifier: MPL-2.0 2 /* 3 * Copyright (C) 2024 The Noisy Sockets Authors. 4 * 5 * This Source Code Form is subject to the terms of the Mozilla Public 6 * License, v. 2.0. If a copy of the MPL was not distributed with this 7 * file, You can obtain one at http://mozilla.org/MPL/2.0/. 8 */ 9 10 package util 11 12 import ( 13 "crypto/rand" 14 "math/big" 15 ) 16 17 // Shuffle shuffles the elements of a slice. 18 func Shuffle[T any](s []T) []T { 19 n := len(s) 20 for i := n - 1; i > 0; i-- { 21 jBig, err := rand.Int(rand.Reader, big.NewInt(int64(i+1))) 22 if err != nil { 23 panic(err) 24 } 25 26 j := int(jBig.Int64()) 27 s[i], s[j] = s[j], s[i] 28 } 29 return s 30 }