Re: math formula substitution and evaluation
- From: rvtol+news@xxxxxxxxxxxx (Dr.Ruud)
- Date: Sun, 16 Jul 2006 16:06:07 +0200
Daniel D Jones schreef:
Given something like the following:
my @variables = [3, 7, 13, 4, 12];
my @tests = ("2*a+b==c", "c-d+a==e");
I need to be able to evaluate the mathematical truth of the tests
#!/usr/bin/perl
# beware: this approach is wrong
use warnings;
use strict;
my $rv = qr~[-+]?(?:[0-9]+|[a-z]+)~ ; # value
my $ro = qr~(?:[-+*/^]|\*\*)~ ; # operator
my $re = qr~\A $rv(?:$ro$rv)* == $rv \z~x ;
my @v = <DATA> =~ /(\d+)/g ;
print join(', ', @v), "\n" ;
while ( <DATA> )
{
chomp ;
tr/A-Z/a-z/ ;
print "$_\t" ;
unless (/$re/) { print "ERROR\n" ; next }
s/([a-z])/($v[ord($1) - ord('a')])/g ;
print "$_\t", eval() ? 'T' : 'F', "\n" ;
}
__DATA__
3, 7, 13, 4, 12
2*a+b==c
c-d+a==e
c-d+a==a
c-d+a==ee
c-d++a==e
-D+c+a==E
2**a==8
2^a==8
--
Affijn, Ruud
"Gewoon is een tijger."
.
- References:
- math formula substitution and evaluation
- From: Daniel D Jones
- math formula substitution and evaluation
- Prev by Date: regex with dollar sign
- Next by Date: Re: regex with dollar sign
- Previous by thread: Re: math formula substitution and evaluation
- Next by thread: Perl Beginner
- Index(es):
Relevant Pages
|
|