S
Simon Andrews
In a discussion about interview questions the following problem came up:
"Take the numbers 123456789. Insert between each number either a + * or
nothing and find the two equations whose answer is 2002"
Of course I had a go and managed to find a solution, but I'm not really
happy with the way I did it. In particular I'm not wild about:
1) Having to build the full set of symbols before performing the actual
calculations. Is there a simple way to do this which only holds one
equation in memory at a time?
2) The use of eval. In this particular case it's probably the nicest
way to do it, but is it really necessary?
Any thoughts?
Simon.
#!perl
use warnings;
use strict;
my @numbers = (1,2,3,4,5,6,7,8,9);
my @symbols = ('','+','*');
my $options = build_symbol_options([[]]);
foreach my $option (@$options) {
my $equation = '';
for my $index(0..$#numbers-1) {
$equation .= $numbers[$index];
$equation .= $option->[$index];
}
$equation .= $numbers[$#numbers];
my $answer = eval($equation);
if ($answer == 2002) {
print $equation," = 2002\n";
}
}
sub build_symbol_options {
my ($options) = @_;
if (@{$options->[0]} == 8) {
return $options;
}
my $new_options;
foreach my $option (@$options) {
foreach my $symbol (@symbols) {
my @new_symbols = @$option;
push @new_symbols,$symbol;
push @$new_options, \@new_symbols;
}
}
build_symbol_options($new_options);
}
"Take the numbers 123456789. Insert between each number either a + * or
nothing and find the two equations whose answer is 2002"
Of course I had a go and managed to find a solution, but I'm not really
happy with the way I did it. In particular I'm not wild about:
1) Having to build the full set of symbols before performing the actual
calculations. Is there a simple way to do this which only holds one
equation in memory at a time?
2) The use of eval. In this particular case it's probably the nicest
way to do it, but is it really necessary?
Any thoughts?
Simon.
#!perl
use warnings;
use strict;
my @numbers = (1,2,3,4,5,6,7,8,9);
my @symbols = ('','+','*');
my $options = build_symbol_options([[]]);
foreach my $option (@$options) {
my $equation = '';
for my $index(0..$#numbers-1) {
$equation .= $numbers[$index];
$equation .= $option->[$index];
}
$equation .= $numbers[$#numbers];
my $answer = eval($equation);
if ($answer == 2002) {
print $equation," = 2002\n";
}
}
sub build_symbol_options {
my ($options) = @_;
if (@{$options->[0]} == 8) {
return $options;
}
my $new_options;
foreach my $option (@$options) {
foreach my $symbol (@symbols) {
my @new_symbols = @$option;
push @new_symbols,$symbol;
push @$new_options, \@new_symbols;
}
}
build_symbol_options($new_options);
}