【问题标题】:Algorithm for matching HashMap key with another random HashMap key, never duplicating values or matching itself将 HashMap 键与另一个随机 HashMap 键匹配的算法,从不重复值或匹配自身
【发布时间】:2016-02-14 10:15:28
【问题描述】:

这可能不是最合乎逻辑/最简单/有效的方法。我希望能提供一些关于更好逻辑的意见,所以我宁愿尝试解释这个问题。

列表:

Jon - null
Dad - null
Mom - null
Thor - null
July - null

我想创建一个随机匹配这些与另一个“键”的方法,没有重复的值或具有相同的键和值。

另一个问题是如果有 3 个键。

1 - null
2 - null
3 - null

迭代 1:

1 - 2
2 - null
3 - null

迭代 2:

1 - 2
2 - 1
3 - null

迭代 3:

???

HashMap 可能不是最合乎逻辑的存储方式。

【问题讨论】:

标签: java algorithm sorting hashmap


【解决方案1】:

答案不在 java 中,但由于这更像是一个算法问题,我相信你可以弄清楚如何将 python 翻译成 java:

import random

# The original collection, using a set instead of map/hash since we don't care
# about the values
set1 = set(range(100))

# Make a copy of set1, we're using a list here so that random.choice will work
set2 = list(set1)

pairs = []

for i in set1:

  # Deal with the final item being the same in both collections,
  # swap with the first one
  if len(set2) == 1 and i == set2[0]:
    tmp = pairs[0][1]
    pairs[0][1] = set2[0]
    pairs.append([i,tmp])
    break

  # Pick random items from set2 until you get one that isn't the same as i
  while True:
    j = random.choice(set2)
    if i != j:
      break

  # Remove the value from set2 so we won't pick it again
  # In this example, set2 is actually a list so that random.choice would work on it
  # This could be kind of expensive, might be better using an actual set
  set2.remove(j)

  # Add our pair to the paired up list
  pairs.append([i,j])

【讨论】:

  • 谢谢,这看起来很棒!明天早上测试一下。
【解决方案2】:

你所说的叫做精神错乱。据我所知,很难以一种可能性相同的方式产生紊乱,但是有一种相当有效的产生它们的方法。

只需遍历键并从尚未使用的键集中随机分配一个值,始终避免使用当前键。

实际上,您只能在最后一步卡住。例如。像这样的

1 - 2 
2 - 4 
3 - 1
4 - 3
5 - ???

如果发生这种情况,只需选择已选择的值之一,然后交换。

1 - 2
2 - 5 <-- swap
3 - 1
4 - 3
5 - 4 <-- swap

here 给出了Set 的实现,它具有获取随机元素的有效方法。

【讨论】:

  • “随机赋值”---如何从集合中随机取值?
  • 是的,这就是我想要做的,但我想知道是否有这样的算法,或者是否有人有解决方案。
【解决方案3】:

将您的列表复制到队列中,对其进行随机播放,然后从列表和队列中分配对。如果队列中的元素相同,则放回尾部,取下一个。

List<String> list = <list with your items>;
ArrayDeque<String> queue = new ArrayDeque<>(list1);
Collections.shuffle(queue);
List<StringPair> result = new ArrayList<>();
for (String s : list) {
   for (String s2; (s2 = queue.poll()).equals(s);)
     queue.offer(s2);
   result.add(s, s2);
}

以上是一个基本的大纲,可能需要更多的工作,但它似乎是一个不错的方法。

【讨论】:

  • 是否保证位置 1 的值不会相同?
  • 嗯,不。这是要解决的问题。
  • 实际上将新列表按随机数移动会更好。
猜你喜欢
  • 1970-01-01
  • 2020-04-06
  • 2021-05-31
  • 2016-02-13
  • 1970-01-01
  • 2013-11-14
  • 1970-01-01
  • 2018-12-17
  • 1970-01-01
相关资源
最近更新 更多