I have a dictionary that has keys and multiple values per key. Same value can be assigned to multiple keys.
For the sake of simplicity, the keys are int
s and the values are string
s,
so that it would look like in C#:
Dictionary<int,string[]>
As an example the dictionary is filled as follows:
{ 1, ["A","B"] },
{ 2, ["A"] }
I now have to remove duplicate values, under the condition that each key keeps at least one value (if at all possible).
So we cannot say 1 gets A, because 2 will then have no associated value anymore.
The result for the example should be:
{ 1, ["B"] },
{ 2, ["A"] }
Another example with result:
{ 1, ["A", "B"] },
{ 2, ["C", "D"] }
-->
{ 1, ["A", "B"] },
{ 2, ["C", "D"] }
One key cannot contains multiples times the same value, so the following scenario is not considered, it cannot happen:
{ 1, ["B"] },
{ 2, ["A", "A"] }
What I tried so far, but where I am not sure if I captured all edge cases or if there are more efficient or more logic ways:
If a key has only one value assigned, this is fixed. The value is removed from all other keys and the key value pair is removed from the iterating list and stored elsewhere
1.1 If after that removal one key does not have any values associated, the algorithm failed, it is not possible.
1.2 Repeat 1. until no key with only a single value is left.
Search for values that are only assigned to one key. The key value pair is removed from the iterating list and stored elsewhere
Repeat 1. to 2. until 2. does not find a result
No we have a list with only n to n relations. All keys have at least 2 values and each value is at least assigned to 2 keys.
Now we randomly remove one value from a single key.
Repeat 1. to 5. until nothing changes anymore.
Is there a standard algorithm for this requirement? I am still not sure if I considered all edge cases.