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

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; }

Replies are listed 'Best First'.
Re^4: Reverse Polish Notation Question
by nat47 (Sexton) on May 02, 2015 at 02:01 UTC
    Why is the extra space needed after the first number in the RPN?

      Because the 2 and the 4 are two separate operands.

        Sorry, I was looking at that because when I've been trying to process long strings I've been getting the error "Modification of non-creatable array value attempted, subscript -2", I fixed it, I needed spaces after everything
Re^4: Reverse Polish Notation Question
by nat47 (Sexton) on May 01, 2015 at 21:56 UTC
    ++'d and giving it a test right now :)