note
kcott
<p>G'day [jess195],</p>
<p>Welcome to the monastery.</p>
<blockquote><em>
"I need to check what user enters against my answer. Say I have x + 1 as a correct answer, but user entered 1 + x. How can I build something that would check for all associativity and commutativity in a given equation?"
</em></blockquote>
<p>
My thoughts on this was to substitute the variables with real values and then compare the results.
However, looking at some of your subsequent replies in this thread, I'm wondering if you really do want to compare two answers or generate a list of all possible answers:
assuming the former, here's some code I've been playing around with that you can possibly adapt to your needs.
</p>
<code>
#!/usr/bin/env perl
use strict;
use warnings;
use constant DEBUG => 0;
use constant FUZZINESS => 1e-15;
use Scalar::Util 'looks_like_number';
my %vals = map { $_ => rand } 'a' .. 'z';
my @equations = (
'x + y',
'x - y',
'x * y',
'x / y',
'x % y',
'x ^ y',
'x * (y + z)',
'x / (y + z)',
'(x + y) * (x + y)',
'(x + y) * (x - y)',
);
EQUATION:
for my $equation (@equations) {
TRY:
while (1) {
print '-' x 40, "\n";
print "Base equation: $equation\n";
print 'Try/Skip/Quit (t/s/q) [t]: ';
my $choice = <>;
next EQUATION if $choice =~ /^s/i;
last EQUATION if $choice =~ /^q/i;
print 'Equivalent equation: ';
my $try = <>;
chomp $try;
if (equivalent($equation, $try)) {
print "'$equation' and '$try' are equivalent.\n";
print 'Try again (y/n) [n]: ';
my $choice = <>;
next TRY if $choice =~ /^y/i;
last TRY;
}
else {
print "'$equation' and '$try' are not equivalent.\n";
next TRY;
}
}
}
sub equivalent {
my ($equation, $try) = @_;
my $eqn_val = get_value($equation);
return 0 unless defined $eqn_val;
my $try_val = get_value($try);
return 0 unless defined $try_val;
return abs($eqn_val - $try_val) < FUZZINESS ? 1 : 0;
}
sub get_value {
my $in_equation = shift;
print "get_value($in_equation)\n" if DEBUG;
(my $equation = $in_equation) =~ s/([a-z])/$vals{$1}/g;
$equation =~ s/\^/**/g;
print "SUBS: $equation\n" if DEBUG;
my $value = eval {
eval $equation;
};
if ($@) {
warn $@;
return undef;
}
if (not defined $value && length $value && looks_like_number $value) {
warn "!!! BAD EQUATION: '$in_equation'\n";
return undef;
}
print "VALUE: $value\n" if DEBUG;
return $value;
}
</code>
<p>Here's some example output:</p>
<code>
'x + y' and 'y + x' are equivalent.
...
'x - y' and 'y - x' are not equivalent.
...
'x - y' and 'x-y' are equivalent.
...
'x * (y + z)' and 'x*y + x*z' are equivalent.
...
'x * (y + z)' and 'z * x + y * x' are equivalent.
...
'x / (y + z)' and 'x/y + x/z' are not equivalent.
...
'(x + y) * (x + y)' and 'x^2 + 2*x*y + y^2' are equivalent.
...
'(x + y) * (x - y)' and 'x^2 + y^2' are not equivalent.
...
'(x + y) * (x - y)' and 'x^2 - y^2' are equivalent.
</code>
<!-- Node text goes above. Div tags should contain sig only -->
<div class="pmsig"><div class="pmsig-861371">
<p>-- Ken</p>
</div></div>
1055515
1055515