in reply to Number from given digits puzzle
Not thoroughly tested, but it finds the solutionmy $target = 24; my @nums = ( 1, 3, 4, 6); for ( solve( $target, @nums) ) { my $val = eval; print "$_ = $val\n"; } sub solve { my ( $target, @nums) = @_; my @sols; for my $i ( 0 .. $#nums ) { my @rem = @nums; my $first = splice @rem, $i, 1; if ( @rem ) { for ( complements( $target, $first) ) { my ( $op, $try) = @$_; push @sols, map "$first $op $_", map m{[-+*/]} ? "($_)" : $_, solve( $try, @rem); } } else { push @sols, $first if $first eq $target; # sic! } } return @sols; } sub complements { my ( $t, $x) = @_; ( [ '+', $t - $x], [ '-', $x - $t], $x ? [ '*', $t/$x] : (), $t ? [ '/', $x/$t] : (), ); }
Anno6 / (1 - (3 / 4)) = 24
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Number from given digits puzzle
by Anonymous Monk on Mar 05, 2009 at 03:54 UTC | |
by Anno (Deacon) on Mar 09, 2009 at 16:20 UTC |