I want to produce the shortest (or one of the shortest) possible combination(s) of the enum fields that would result in a particular enum value. What would be the best algorithm to accomplish this?
For example, say I have the enum:
enum MyEnum
{
One = 1,
Two = 2,
Three = One | Two,
Four = 4,
Six = Two | Four,
Eight = 8,
All = One | Two | Four | Eight
}
Now for example for the value 7
I would like my function to output either "One | Six"
or "Three | Six"
.
Edit: Of course Three | Four
Three | Four
would be a valid output as well.
What you are basically asking for is minimum set cover, a problem known to be NP Complete. Fortunately, that doesn't mean that you can't solve it for small cases such as this. You can also get a O(logn)
approximation via the greedy algorithm.
If there is no particular structure to your enum values, then you won't be able to do much better than brute force for a general exact solution. If you know that your enums have a particular structure, then you can often due much better via things like graph partitioning or CSP + backtracking.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.