<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="/stylesheets/rss.css"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
  <channel>
    <title>Aaron Feng: Brain Teaser: Constraint programming</title>
    <link>http://aaronfeng.com/articles/2007/06/27/brain-teaser-constraint-programming</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description>Adventures in software development</description>
    <item>
      <title>Brain Teaser: Constraint programming</title>
      <description>&lt;p&gt;I had never heard of &lt;a href="http://en.wikipedia.org/wiki/Constraint_programming"&gt;constraint programming&lt;/a&gt; until a co-worker wrote the following problem on the board a few days ago:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;A/BC + D/EF + G/HI = 1&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;All variables are &lt;strong&gt;unique&lt;/strong&gt; 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.&lt;/p&gt;

&lt;p&gt;I decided to whip up a program to find out the answer.&lt;/p&gt;

&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;class Program {
  static List&amp;lt;int&amp;gt; ints = new List&amp;lt;int&amp;gt;();
  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(&amp;quot;{0}/{1}{2} + {3}/{4}{5} + {6}/{7}{8} = 1&amp;quot;, 
      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;
    }
  }
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;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.&lt;/p&gt;</description>
      <pubDate>Wed, 27 Jun 2007 22:15:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:e9736f40-be98-448e-8c2b-02f0ae700220</guid>
      <author>Aaron Feng</author>
      <link>http://aaronfeng.com/articles/2007/06/27/brain-teaser-constraint-programming</link>
      <category>programming</category>
    </item>
  </channel>
</rss>
