user who wrote:
> 
> 4 numbers (all from 1-9) are given, make a formula(include +-*/()) for
> result 24.  ex:
> 
> 4, 2, 7, 5
> (4-2)*(7+5) = 24
> 
> shortest/quickest solution?

most straightforward (ducks...)

#!/usr/bin/perl

use strict;

my @n = qw( 4 2 7 5 );
my @op = qw( + - * / );
my @f = qw/ ((NxN)xN)xN (NxN)x(NxN) (Nx(NxN))xN Nx((NxN)xN) Nx(Nx(NxN)) /;

for my $n (grep { !/[^1-4]/ and !/(.).*\1/ } 1234..4321)
  {
  for my $op (grep !/[^1-4]/, 111..444)
    {
    for my $f (my @ff = @f) # alias problem...
      {
      $f =~ s/N/$n[$_-1]/e for $n =~ /\d/g;
      $f =~ s/x/$op[$_-1]/e for $op =~ /\d/g;
      print "ans: $f\n" if 24 == eval $f;
      }
    }
  }


It prints 20 results.

-- 
Rick Klement

Reply via email to