Brain Teaser: Constraint programming
I had never heard of constraint programming until a co-worker wrote the following problem on the board a few days ago:
A/BC + D/EF + G/HI = 1
All variables are unique digits from 1 - 9. Two variables next to each other is equivalent to 10 * var1 + var2. For example, if B = 2, C = 5 then the result is 10 * 2 + 5 which equals 25.
I decided to whip up a program to find out the answer.
class Program {
static List<int> ints = new List<int>();
static Random r = new Random();
static void Main(string[] args) {
double A = 0, B = 0, C = 0, D = 0, E = 0, F = 0, G = 0, H = 0, I = 0;
while (!(((A / (10 * B + C)) + (D / (10 * E + F)) + (G / (10 * H + I))) == 1)) {
GenerateUniqueInts();
A = ints[0]; B = ints[1]; C = ints[2];
D = ints[3]; E = ints[4]; F = ints[5];
G = ints[6]; H = ints[7]; I = ints[8];
}
Console.WriteLine(String.Format("{0}/{1}{2} + {3}/{4}{5} + {6}/{7}{8} = 1",
A, B, C, D, E, F, G, H, I));
}
public static void GenerateUniqueInts() {
ints.Clear();
int value = (r.Next() % 9) + 1;
while (!(ints.Count == 9)) {
if (!ints.Contains(value)) ints.Add(value);
value = (r.Next() % 9) + 1;
}
}
}It only takes a couple of seconds for the program to figure out the answer. It turns out there is only one solution to this problem. However, on my first implementation I instantiated the Random object in the GenerateUniqueInts() method. For some reason, that can take up 10 minutes to run. If you are interested in the answer, try the program out.
