in reply to Re: Number from given digits puzzle
in thread Number from given digits puzzle

Thanks. Making that change and another trivial one appears to fix the code. I still don't know what problem your change fixes, but I'll try to find it out (it might be something related to aliasing.

The trivial change is that the second addittion operator in line 28 has to be replaced by a concatenation operator:

&$f($v1 + 10 * $v2, $s1 . $s2);

Here's the fixed code for convenience:

#!perl # alapm.pl -- megold egy számrejtvényt # Rubyból fordítottam perlbe kábé szó szerint, tehát rosszabbnak kell # lennie, mintha eleve perlben írnám. Látszik rajta, callbackeket # használok úgy, ahogy perl-ben nem tenném. # Állítsuk el&#337; a 24-et alapm&#369;veletekkel az 1, 3, 4, 6 számje +gyek pontosan # egyszeri felhasználásával. A sorrend tetsz. use warnings; use strict; use Carp "cluck"; sub mask { my($s, $m) = @_; [map { $$s[$_] } grep { 0 != ($m & (1<<$_)) } 0 .. @$s - 1]; } sub poss2 { my($v1, $v2, $s1, $s2, $f) = @_; &$f($v1 + $v2, "(" . $s1 . " + " . $s2 . ")"); &$f($v1 - $v2, "(" . $s1 . " - " . $s2 . ")"); &$f($v1 * $v2, "(" . $s1 . " * " . $s2 . ")"); 1e-8 < abs($v2) and &$f($v1 / $v2, "(" . $s1 . " / " . $s2 . ")"); $s1 =~ /^\d+$/ && $s2 =~ /^\d$/ and &$f($v1 + 10 * $v2, $s1 . $s2); } sub poss { my($v, $s, $f) = @_; if (1 == @$v) { &$f($$v[0], $$s[0]); } else { for my $m (1 .. (1<<@$v) - 2) { my(@vv2, @ss2); poss(mask($v, ~$m), mask($s, ~$m), sub { my($v2, $s2) = @_; push @vv2, $v2; push @ss2, $s2; }); poss(mask($v, $m), mask($s, $m), sub { my($v1, $s1) = @_; for my $k (0 .. @vv2 - 1) { poss2($v1, $vv2[$k], $s1, $ss2[$k], $f # # ); } }); } } } my(@NUMS, $TARGET); sub main { poss([@NUMS], [@NUMS], sub { my($r, $s) = @_; abs($r - $TARGET) < 1e-6 and print $r, " = ", $s, "\n"; }); } @NUMS = (1, 3, 4, 6); $TARGET = 24; main(); __END__

Replies are listed 'Best First'.
Re^3: Number from given digits puzzle
by Krambambuli (Curate) on Mar 31, 2007 at 12:36 UTC
    With one more change, the code works fine:
    27,28c27,28 < $s1 =~ /^\d+$/ and $s2 =~ /^\d$/ and < &$f(10*$v1 + $v2, $s1 . $s2); --- > $s1 =~ /^\d+$/ && $s2 =~ /^\d$/ and > &$f($v1 + 10 * $v2, $s1 . $s2);
    and the output I see is
    24 = (3 * (14 - 6)) 24 = (6 / (1 - (3 / 4))) 24 = ((14 - 6) * 3)
    which seems quite OK.

    Now I haven't looked yet if that's an oneliner in some Perl Golf competition, but I'd bet there is something :)

    Would be nice to let us now if in the end you had some personal conclusions about your attempted Ruby/Perl comparison.

    Thanks,
    Krambambuli

      Oh yes. Even the ruby code has that bug.

      (Take care because you're giving a reverse patch.)