I have a resource scheduling issue in Java where things need to be sequenced, but there are restrictions on what resources can be next to each other. A good analogy is a string of ‘digits’, where only certain digits can be next to each other. My solution was recursive, and works fine for small strings, but run time is O(X^N), where X is the number of possible digits (the base), and N is the length of the string. It quickly becomes unmanageable.
Using the compatibility matrix below, here are a few examples of allowed strings
Length of 1: 0, 1, 2, 3, 4
Length of 2: 02, 03, 14, 20, 30, 41
Length of 3: 020, 030, 141, 202, 203, 302, 303, 414
0 1 2 3 4 --------------------- 0| 0 0 1 1 0 1| 0 0 0 0 1 2| 1 0 0 0 0 3| 1 0 0 0 0 4| 0 1 0 0 0
My solution for counting all strings of length N was start with an empty string, permute the first digit, and make a recursive call for all strings of length N-1. The recursive calls check the last digit that was added and try all permutations that can be next to that digit. There are some optimizations made so that I don’t try and permute 00, 01, 04 every time, for example – only 02, 03, but performance is still poor as it scales from base 5 (the example) to base 4000.
Any thoughts on a better way to count the permutations other than trying to enumerate all of them?
If you just want the number of strings of a certain length, you could just multiply the compatibility matrix with itself a few times, and sum it’s values.
A few examples:
The original matrix (row i, column j) could be thought of as the number of strings that start with symbol i, and whose next symbol is symbol j. Alternatively, you could see it as number of strings of length 2, which start with symbol i and ends with symbol j.
Matrix multiplication preserves this invariant, so after exponentiation, An-1 would contain the number of strings that start with symbol i, has length n, and ends in symbol j.
See Wikipedia: Exponentiation by squaring for an algorithm for faster calculation of matrix powers.
(Thanks stefan.ciobaca)
This specific case reduces to the formula: