in reply to RPN Question

Go through your string left-to-right. If it's an operand, stack it, otherwise if it's an operator, perform it on the top two items on the stack and place the result back on the stack.

Replies are listed 'Best First'.
Re^2: Reverse Polish Notation Question
by nat47 (Sexton) on May 01, 2015 at 21:01 UTC
    And when an x is encountered?

      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?
        ++'d and giving it a test right now :)

      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

      Gimme a few minutes, I'll show you.

        That would be amazing, thank you!