I have a set of values which need to be shuffled when needed. I don't know which variable type is best for me. Data is actually based on key-value structure.Like;
100 "white"
200 "black"
300 "red"
and like that. What I want to do is to change the key-value pairs according to I don't know yet, some algorithm.But they need to be shuffled like this, but shuffling need to be not random, so I can revert data when I need.
100 "red"
200 "white"
300 "black"
I don't really know how my approach should be to the solution. Should I use HashTable or something, and how can I shuffle them dynamically? Any help is appreciated
It looks like you need a list of tupples. A Map is exactly that. However, a standard like HashMap has no functionality for changing the relationship between key and value.
I think I would have implemented my own Map for this. Create a class that implements java.util.Map, implement the required methods and create some other methods for "mixing".
It all dependes on what functionality you really need on the list of tupples. Do you need to look up colors very fast? Can there be more than one tupple with the same numbers?
I am not sure how exactly you are going to shuffle the pairs, but if you need to shuffle them based on the key, you can use a
Map
:Alternatively, if you need to shuffle the pair randomly, you can create a class
Pair
(which will basically store anint
and aString
), as suggested by larsmans, and store them in an array. Then, a slightly-modified version ofFisher-Yates shuffle
can be used. Something along these lines:Another way for shuffling the key-value mappings randomly:
Edit:
If you don't want to change the original map (since you need it afterwards), you can create a new one instead:
You do not really want a seemingly-randomly mixing which can be reverted (which quickly gets complicated), but simply retain your original map. If this does not fit, you need to describe your problem better.
Okay, you want to encrypt the mapping by using a secret key, giving another mapping, and then decrypt it again. Obviously random shuffling does not help here, and even pseudorandom is no good, since it gives no reliable way to reshuffle. In the basic case, your key would be a invertible map between the keys of our mapping.
Decryption works the same, in fact, only using the reverse map of the key.
So, when you have your example keys of
{100, 200, 300}
, any permutation of these keys is a valid key for our "encryption scheme". (There are only 6 possible ones, which is not very secure.)The map
decrypted
now should be the same as the original map.For bigger keysets you would want to find a scheme to get a suitable permutation of keys from some input-able key.