Get an arbitrary key/item from a map

前端 未结 6 1618
攒了一身酷
攒了一身酷 2021-02-01 12:59

I am new to Go and now I want to get an arbitrary item from a map; what\'s the idiomatic way to do that? I can only think of something like this:

func get_some_k         


        
6条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-01 13:15

    It is usually not a good idea to force an API on a data-structure that doesn't intrinsically support it. At best it will be slow, hacky, hard-to-test, hard-to-debug and unstable. Go's map natively supports upsert, get, delete, and length but not GetRandom.

    Of the two concrete solutions mentioned here

    • iterating over a range and choosing the first one does not guarantee a random item will be chosen or enable any control over the degree of randomness (ie uniform, gaussian, and seeding)
    • reflection is hacky, slow and requires additional memory proportional to the size of the map

    The other solutions talk about using additional data structures to help the map support this operation. This is what I think makes the most sense

    type RandomizedSet interface {
        Delete(key int) // O(1)
        Get(key int) int // O(1)
        GetRandomKey() int // O(1)
        Len() int // O(1)
        Upsert(key int, val int) // O(1)
    }
    
    type randomizedset struct {
        h map[int]int // map key to its index in the slice
        indexes []int // each index in the slice contains the value
        source rand.Source // rng for testability, seeding, and distribution
    }
    
    func New(source rand.Source) RandomizedSet {
        return &randomizedset{
            h: make(map[int]int, 0),
            indexes: make([]int, 0),
            source: source,
        }
    }
    
    // helper to accomodate Delete operation
    func (r *randomizedset) swap(i, j int) {
        r.indexes[i], r.indexes[j] = r.indexes[j], r.indexes[i]
        r.h[r.indexes[i]] = i
        r.h[r.indexes[j]] = j
    }
    
    // remainder of implementations here
    
    

提交回复
热议问题