#!/usr/bin/perl
# riddle: find a ten-digit number containing each digit once, so that the 
# number formed by the first n digits is divisible by n for each value of n 
# between 1 and 10.
#
# Matt Sparks, 20050815
sub get_rand {
    return int(rand(9))+1;
}

sub get_num {
    my %used;
    my $c;
    my $num;
    while($c<9) {
        my $cand=get_rand;
        if (!defined $used{$cand}) {
            $num.=$cand;
            $used{$cand}=1;
            $c++;
        }
    }
    return $num."0";
}

sub check_num {
    my($num,$size)=@_;
    $size=10 if !$size;
    for(1..$size) {
        my $part=substr($num,0,$_);
        if ($part % $_ != 0) { return 0; }
    }
    return 1;
}

my $num;
while (1) {
    $num=get_num;
    last if check_num($num,10);
}
print "Answer: $num\n";
