Advertisement
faubiguy

algebra.pl

Jul 23rd, 2015
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.08 KB | None | 0 0
  1. @a=map{[split'\+|(?=-)']}    # Split each factor into components
  2.     <>=~s/\n//r=~s/(\(.+?\))\^(\d)/$1x$2/ger=~/[^()]+/g;    # Get factors by flattening exponents then splitting list on parenthesized expressions
  3. for(@{$a[0]}){
  4.     $l{/\d/?'':$_}=/\d/?$_:1    # Initialize %l (hash from variable to coefficient) with first factor
  5. }
  6. for(1..$#a){    # Loop through other factors to multiply
  7.     %b=();    # Temporary hash to store current result in
  8.     for(@{$a[$_]}){    # Loop $_ through components of current factor
  9.         while(($k,$v)=each%l){ # Loop $k,$v through variables and coefficients of current polynomial
  10.             $b{/\d/?$k:join'',sort($_,split'',$k)}+=/\d/?$v*$_:$v # If component is a number multiply coefficients by it, otherwise append it to variables (and sort to keep unique indexes)
  11.         }
  12.     }
  13.     %l=%b # Set current polynomial to temporary result
  14. }
  15. print(
  16.     (join' ',map{"$l{$_}$_"}sort{length$b<=>length$a}keys%l) # Format hash as list ordered by degree
  17.     =~s/\b1(?=[a-z])//gr=~s/-/- /gr=~s/\b \b/ + /gr=~s/(([a-z])\2+)/"$2^".length$1/gre) # String substitutions to do the rest of the formatting
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement