in reply to Re: Reverse Polish Notation Question
in thread RPN Question

And when an x is encountered?

Replies are listed 'Best First'.
Re^3: Reverse Polish Notation Question
by Anonymous Monk on May 01, 2015 at 21:51 UTC

    Passes one test case :)

    #!/usr/bin/perl # http://perlmonks.org/?node_id=1125392 use strict; my @stack; $_ = @ARGV ? "@ARGV" : '2 4x*8-*3x*+11x*1+9--'; # x cancels out $_ = @ARGV ? "@ARGV" : '2 4x*8-*3x*+10x*1+9--'; # adjusted print " raw $_\n"; use Data::Dump qw(pp); while( /(\d+)|(x)|([*+-])/g ) { pp \@stack; if( length $1 ) { push @stack, [ $1 ]; } elsif( $2 ) { push @stack, [ 0, 1 ]; } else { my $op = $3; my ($x, $y) = splice @stack, -2; if( $op eq '+' ) { my $i = 0; $x->[$i++] += $_ for @$y; push @stack, $x; } elsif( $op eq '-' ) { my $i = 0; $x->[$i++] -= $_ for @$y; push @stack, $x; } elsif( $op eq '*' ) { push @stack, multiply( $x, $y ); } } } pp \@stack; my ($x0, $x1) = @{ pop @stack }; if( $x1 ) { print "x = ", -$x0 / $x1, "\n"; } else { die "x has cancelled out"; } sub multiply # two polynomials { my ($x, $y) = @_; my ($n, @result) = (0); for my $xval (@$x) { my $pos = $n; $result[$pos++] += $xval * $_ for @$y; $n++; } return \@result; }
      Why is the extra space needed after the first number in the RPN?

        Because the 2 and the 4 are two separate operands.

      ++'d and giving it a test right now :)
Re^3: Reverse Polish Notation Question
by Anonymous Monk on May 01, 2015 at 21:16 UTC

    Btw, didn't you like my recursive descent solution ?

      It was incredibly good, I'm just trying to learn Perl and also tried this problem with RPN. Although, now I'm worried I did the RPN calculation wrong

        Your equation 2(4x-8)+3x=11x+1-9 is bad, x cancels out.

Re^3: Reverse Polish Notation Question
by Anonymous Monk on May 01, 2015 at 21:04 UTC

    Gimme a few minutes, I'll show you.

      That would be amazing, thank you!