返回特定键的任何值的二值字典
我需要创建一个字典,每个键有 2 个值,并且它必须以相同的概率返回这 2 个值之一。
例子:
myDicry
{
key = "A", value1=15, value2=56;
}
int firstCall = myDicry["A"]; // = 15
int secondCall = myDicry["A"]; // = 56
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
可以编写一个以这种方式运行的 IDictionary 实现,但这不是一个好主意:大多数人会为集合类找到一个非确定性索引器非常不直观。
相反,我建议您将此作为键的值的责任,而不是字典本身。一种选择是编写一个自定义类型,能够以相同的概率从一组可能性中进行选择。例如:
然后您可以像这样使用字典:
It would be possible to write an
IDictionary<TKey, TValue>
implementation that behaved in this manner, but that would not be a good idea: most people would find a non-deterministic indexer for a collection-class very unintuitive.Instead, I suggest you make this the responsibility of the value for a key, rather than the Dictionary itself. One option would be to write a custom-type that is capable of picking from a set of possibilities with equal probability. For example:
You could then use the dictionary like this:
框架中没有内置任何内容来执行此操作,但您可能希望通过创建一个具有
Dictionary>
的“包装”类型来实现它。然后,您可以编写一个索引器来在两个值之间进行适当的选择。There's nothing built into the framework to do this, but you'd probably want to implement it by creating a "wrapper" type which had a
Dictionary<TKey, Tuple<TValue, TValue>>
. You'd then write an indexer to choose appropriately between the two values.实际上,我只是在一个内部使用
Dictionary
的类中实现它。这样,您甚至可以实现该类型以使每个键具有可变数量的值。喜欢:
I would actually just implement this in a class that uses a
Dictionary<TKey, TValue[]>
internally. That way you could even implement the type to have a variable number of values per key.Like:
使用 Tuple 作为字典值类型。
Use Tuple as dictionary value type.
您还可以为字典编写一个扩展方法,这样您就可以创建如下内容:
然后您可以将其与任何字典一起使用。
^^这是我写的,所以如果有轻微错误,请原谅。
You could also write an extension method for the dictionary, so you could create something like this:
Then you can use this with any dictionary.
^^ that was written off the top of my head, so please excuse me if this is slightly wrong.
下面的代码将解决问题的字典部分,并使随机化可定制,以便您可以应用适合您需求的伪随机级别。 (或者简单地对其进行硬编码而不是使用函子)
This below code will solve the dictionary part of the problem and make the randomization customizable so that you can apply a level so pseudo-randomness that suits your needs. (or simply hard code it instead of the use of a functor)