in reply to How would you solve a user-inputted simple one-variable Linear Equation
Some code to get you started.
use strict; use warnings; my $eq = '2+3x+7x(x+27)-6'; my @mult=(1); my @pow=(0); my @c; # die "Not supported.\n" if /[^-+0-9x]/; die "Not supported: '$1' \n" if $eq =~ /([^-+0-9x()]+)/; # as per Anom +alousMonk's suggestion print "Equation: $eq\n"; while($eq=~/([-+]?)(\d*)(x?)([)(]?)/g){ next unless "$1$2$3$4"; my $d = $2 || 1; $d *= -1 if $1 eq '-'; if( $4 eq '(' ) { push @mult, $mult[-1]*$d; push @pow, $pow[-1]+1; } else { if( $3 ) { $c[1+$pow[-1]] += $mult[-1]*$d; } else { $c[$pow[-1]] += $mult[-1]*$d; } } if( $4 eq ')' ) { pop @mult; pop @pow; } } print "Summary: @c\n";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How would you solve a user-inputted simple one-variable Linear Equation
by AnomalousMonk (Archbishop) on Apr 25, 2015 at 22:20 UTC | |
by hdb (Monsignor) on Apr 26, 2015 at 07:03 UTC |