Mike Perrenoud
Mike Perrenoud

Reputation: 67898

Weighted Permutations Algorithm

Team:

I am building a business rules engine that is contextually aware -- but it's weighted -- or in other words each business rule has a level of granularity defined by the segments of a key. The segments are not combinatorial in that they cannot be weighted in any order, but rather permutable like a combination lock (interestingly enough improperly named but widely accepted).

However, to reduce the amount of code that's necessary to provide the business rules we are only building exclusion files meaning that each segment could end up with a specific key value or ALL.

So, now that we have an abstract background, let's take a concrete example. The defined segments are as follows:

  1. Line of Business (LOB)
  2. Company
  3. State

Now, let's assume for this example that the LOB is ABC, Company is G and State is WY. If you break that down I should get the following permutations:

However, I need an algorithm to solve that problem. The segments must also be returned in the aforementioned order because you must always find the most finite rule first.

I look forward to your responses and thank you all in advance!

Upvotes: 0

Views: 464

Answers (2)

Servy
Servy

Reputation: 203802

public static void Main(string[] args)
{
    List<string> inputValues = new List<string>() { "ABC", "G", "WY" };
    List<string> results = new List<string>();

    int permutations = (int)Math.Pow(2.0, (double)inputValues.Count);

    for (int i = 0; i < permutations; i++)
    {
        int mask = 1;
        Stack<string> lineValues = new Stack<string>();
        for (int j = inputValues.Count-1; j >= 0; j--, mask <<= 1)
        {
            if ((i & mask) == 0)
            {
                lineValues.Push(inputValues[j]);
            }
            else
            {
                lineValues.Push("ALL");
            }
        }
        results.Add(string.Join("_", lineValues.ToArray())); //ToArray can go away in 4.0(?) I've been told.  I'm still on 3.5
    }

    foreach (string s in results)
    {
        Console.WriteLine(s);
    }

    Console.WriteLine("Press any key to exit...");
    Console.ReadKey(true);
}

Upvotes: 1

maniek
maniek

Reputation: 7307

If I get the question right, You should:

-Generate all binary strings of length N (there will be 2^N of them)
-sort them by number of bits set
-generate rules. Rule has 'ALL' in position i, if bit number i in the corresponding binary string is set

Upvotes: 0

Related Questions