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

huangapple go评论85阅读模式
英文:

How to randomly split a map in Go as evenly as possible?

问题

我有一个快速的问题。我对golang还比较新手。假设我有一个如下的map:

map[int]string

如何将它随机分成两个尽可能均匀的map或数组?例如,如果有15个项,它将被分成7-8。

英文:

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.

答案1

得分: 2

例如:

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
}

这实际上是一个有趣的例子,因为它展示了一些对初学者来说不太明显的Go语言特性:

  • range m 以随机顺序迭代,与我所知的其他任何语言都不同,
  • 取模运算符 % 返回整数除法的余数,
  • 一个函数可以返回多个值。
英文:

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.

答案2

得分: 2

你可以这样做:

myStrings := make(map[int]string)
// 将值添加到myStrings中
myStrings2 := make(map[int]string)
// 为随机数种子系统时间
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

英文:

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() &lt; 0.5 {
		myStrings2[k] = v
		delete(myStrings, k)

	}
}

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

huangapple
  • 本文由 发表于 2017年3月23日 19:45:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/42975100.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定