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

In reply to Re^3: Reverse Polish Notation Question by Anonymous Monk
in thread RPN Question by nat47

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.