Is there a data structure that allows an object property to be accessed with two keys in either order?

Let’s say, for sake of an arbitrary example, that I want to store information about twinned towns. I want to be able to access the data about the twinning by having the names of both towns as keys, but assuming that neither is the ‘initial’ key. So I’d access the data property like this: twinning_data['derby', 'montreal'] = { 'year': 1986 } or in reverse: twinning_data[ 'montreal', 'derby'] = { 'year': 1986 }.

The best I can come up with is just to concatenate the strings and then try one and then the other way round. Perhaps there is an order independent hash one could use?


You could add them together character by character or perform any other commutative operation, then hash the result.

You could use a normal Map with a Bag<City> or a Set<City> as keys. Maps, Sets, and to a lesser extent Bags are usually available in any decent collections / data structures library.

Here’s an example in Ruby:

require 'set'

twinning_data = { Set['derby', 'montreal'] => { year: 1986 } }
twinning_data[Set['montreal', 'derby']]
#=> { :year => 1986 }

Of course, Bags and Sets can technically have an arbitrary number of elements, whereas you want to have exactly 2; ergo, the type is not particularly precise. A more precise type would be some sort of BinaryUndirectedRelation type, which however, probably doesn’t readily exist outside of a graph library or the internals of an RDBMS kernel.


Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *