dth2331
2017-03-23 11:45
浏览 35
已采纳

如何在Go中尽可能均匀地随机分割地图?

I have a quick question. I am fairly new to golang. Say I have a map like so:

map[int]string

How could I randomly split it into two maps or arrays and as close to even as possible? So for example, if there are 15 items, it would be split 7 - 8.

图片转代码服务由CSDN问答提供 功能建议

我有一个简短的问题。 我刚接触golang。 假设我有一个这样的地图:

  map [int] string 
   
 
 

我该如何随机分割地图 分成两个映射或数组,并尽可能接近? 例如,如果有15个项目,则将其拆分为7-8。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doujiazong0322 2017-03-23 12:47
    已采纳

    For example:

    func split(m map[int]string) (odds map[int]string, evens map[int]string) {
        n := 1
        odds = make(map[int]string)
        evens = make(map[int]string)
        for key, value := range m {
            if n % 2 == 0 {
                evens[key] = value
            } else {
                odds[key] = value
            }
            n++
        }
        return odds, evens
    }
    

    It is actually an interesting example, because it shows a few aspects of Go that are not obvious for beginners:

    • range m iterates in a random order, unlike in any other language as far as I know,
    • the modulo operator % returns the remainder of the integer division,
    • a function can return several values.
    点赞 评论
  • dseomy1964 2017-03-23 12:54

    You could do something like this:

    myStrings := make(map[int]string)
    // Values are added to myStrings
    myStrings2 := make(map[int]string)
    // Seed system time for random numbers
    rand.Seed(time.Now().UTC().UnixNano())
    for k, v := range myStrings {
        if rand.Float32() < 0.5 {
            myStrings2[k] = v
            delete(myStrings, k)
    
        }
    }
    

    https://play.golang.org/p/6OnH1k4FMu

    点赞 评论

相关推荐 更多相似问题