Is the iteration of the map random enough for a random selection of keys?

Can I rely on random map iteration to implement random pairing of clients in a web application? I tried looking around, but I can't seem to find a breakdown of how random this accident is.

The algorithm will look something like this:

var clients map[Client]struct{}

func PairClient(c Client) (Client, error) {
    for m := range clients {
        if m != c {
            return m, nil
        }
    }
    return nil, fmt.Errorf("lobby: insufficient number of clients")
}

Will it be enough if there are> 1000 connected clients, or should I support a separate piece of clients and arbitrarily choose from this?

+4
source share
2 answers

, () (spec, blog, hashmap source, , fooobar.com/questions/1663119/...), .

? , / . . , "" for range, , ( ).

? "". 10 . ():

m := map[int]int{}
for i := 0; i < 10; i++ {
    m[i] = i
}

dist := make([]int, 10)
for i := 0; i < 100000; i++ {
    for idx := range m {
        dist[idx]++
        break
    }
}

fmt.Println("Distribution:", dist)

( Go Playground):

Distribution: [25194 24904 6196 6134 6313 6274 6297 6189 6189 6310]

2 (0 1) 4 , , ​​ .

, ( ) , . , (, , ).

+6

spec:

  1. . (...)

, , , undefined. Go , .

+3

Source: https://habr.com/ru/post/1663117/


All Articles