title: How do I solve a set of constraints in Perl?
body: <p>I have the following set of constraints in Perl (just a sample set of constraints, not the ones I really need):</p>
  
  <pre><code>$a &lt; $b
  $b &gt; $c
  $a is odd =&gt; $a in [10..18]
  $a &gt; 0
  $c &lt; 30
  </code></pre>
  
  <p>And I need to find a list <code>($a, $b, $c)</code> that meet the constraints.  My naive solution is</p>
  
  <pre><code>sub check_constraint {
      my ($a, $b, $c) = @_;
      if !($a &lt; $b) {return 0;}
      if !($b &gt; $c) {return 0;}
      if (($a % 2) &amp;&amp; !(10 &lt;= $a &amp;&amp; $a &lt;= 18)) {return 0;}
      if !($a &gt; 0) {return 0;}
      if !($c &lt; 30) {return 0;}
      return 1;
  }
  
  sub gen_abc {
      my $c = int rand 30;
      my $b = int rand $c;
      my $a = int rand $b;
      return ($a, $b, $c);
  }
  
  ($a, $b, $c) = &amp;gen_abc();
  while (!&amp;check_constraint($a, $b, $c)) {
      ($a, $b, $c) = &amp;gen_abc();
  }
  </code></pre>
  
  <p>Now, this solution isn't guaranteed to end, and is pretty inefficient in general.  Is there a better way to do this in Perl?</p>
  
  <p><strong>Edit:</strong>  I need this for a random test generator, so the solution needs to use random functions such as <code>rand()</code>.  A solution that's completely deterministic isn't enough, although if that solution can give me a list of possible combinations I can select an index at random:</p>
  
  <pre><code>@solutions = &amp;find_allowed_combinations(); # solutions is an array of array references
  $index = int rand($#solutions);
  ($a, $b, $c) = @$solution[$index];
  </code></pre>
  
  <p><strong>Edit 2:</strong>  The constraints here are simple to solve with brute force.  However, if there are many variables with a large range of possible values, brute force isn't an option.</p>