Skip to content

Instantly share code, notes, and snippets.

@harshavardhana
Forked from fwessels/random-servers.go
Last active December 26, 2018 21:44
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 harshavardhana/44614a69650c9111defe3470941cdd16 to your computer and use it in GitHub Desktop.
Save harshavardhana/44614a69650c9111defe3470941cdd16 to your computer and use it in GitHub Desktop.
Create a list of random servers
package main
import (
"fmt"
"hash/crc32"
)
func randomServers(token string, count int) []int {
hTok := crc32.Checksum([]byte(token), crc32.IEEETable)
val := uint32(hTok)
// initialize array to select from
ints := make([]int, count)
for i := 0; i < count; i++ {
ints[i] = i + 1
}
result := make([]int, 0, count)
for i := count; i >= 2; i-- {
// determine position and add to result
m := val % uint32(i)
result = append(result, ints[m])
// remove item just appended to result
ints = append(ints[0:m], ints[m+1:len(ints)]...)
}
// append last item
return append(result, ints[0])
}
func main() {
fmt.Println(randomServers("minio", 32)[:28])
// Prints: [6 9 26 2 3 16 25 24 10 21 32 14 22 1 20 5 13 19 7 18 17 31 12 11 28 8 30 27]
fmt.Println(randomServers("rocks", 32)[:28])
// Prints: [21 29 26 12 14 10 9 13 18 2 20 22 6 16 1 5 11 25 31 24 3 7 19 4 27 30 8 32]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment