算法匹配HashMap的键与另一个随机HashMap的关键,绝不重复的值或匹配自己 [英] Algorithm for matching HashMap key with another random HashMap key, never duplicating values or matching itself

查看:173
本文介绍了算法匹配HashMap的键与另一个随机HashMap的关键,绝不重复的值或匹配自己的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是可能的,这不是最合乎逻辑/这样做的easyiest /有效途径。我喜欢一些投入上更好的逻辑,所以我应该努力解释这个问题。

It's possible this is not most logical/easyiest/effective way of doing this. I would love some input on a better logic, so I'll rather try to explain the problem.

清单:

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

我想创建一个与另一个关键在符合这些方法随机的,没有重复的值或具有键和值是相同的。

I want to create a method that matches these with another 'key' at random, not having duplicate values or having a key and value which are the same.

的另一个问题是,如果有例如3个按键。

Another problem is if there are for example 3 keys.

1 - null
2 - null
3 - null

迭代1:

1 - 2
2 - null
3 - null

迭代2:

1 - 2
2 - 1
3 - null

迭代3:

???

这有可能是一个HashMap不会是这个存储的最合理的方式。

It's possible a HashMap not is the most logical way of storing this.

推荐答案

你所讲的被称为紊乱。据我所知这是相当困难的产生紊乱以这样的方式,他们都同样有可能,但他们产生一个合理有效的方式。

What you are talking about is called a derangement. As far as I know it's quite difficult to generate derangements in such a way that they are all equally likely, but there is a reasonably effective way of generating them.

简单地遍历键和随机从所有尚未被使用,总是避免了当前键键组分配一个值。

Simply iterate over the keys and assign a value at random from the set of keys that haven't already been used, always avoiding the current key.

您可以实际上只有感到迷惑的最后一步。例如。像这样

You can actually only get stuck at the very last step. E.g. something like this

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

如果出现这种情况,只需选择其中一个值已被选中,和交换。

If this happens, just choose one of the values already selected, and swap.

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

设置与获取随机元素的有效方法的实现,给出这里

An implementation of Set with an efficient method for getting random elements is given here.

这篇关于算法匹配HashMap的键与另一个随机HashMap的关键,绝不重复的值或匹配自己的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆