Last active
December 12, 2015 03:08
-
-
Save silvioq/4704316 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use strict; | |
use warnings; | |
sub process($); | |
sub usage(){ | |
print "./m10gen pattern\n"; | |
print " Where pattern is a number or 'X'.\n"; | |
print " The script replaces each 'X' in the pattern for a digit and prints valid M10 numbers"; | |
print "Example:\ņ"; | |
print "./m10gen 525000XXX\n"; | |
} | |
sub validate($){ | |
my @rev = reverse split //,$_[0]; | |
my ($sum1,$sum2,$i) = (0,0,0); | |
for(my $i=0;$i<@rev;$i+=2) { | |
$sum1 += $rev[$i]; | |
last if $i == $#rev; | |
$sum2 += 2*$rev[$i+1]%10 + int(2*$rev[$i+1]/10); | |
} | |
return ($sum1+$sum2) % 10 == 0; | |
} | |
# Analyze the pattern and, recursively replace | |
# X for 0-9 and check m10 | |
sub process($){ | |
my $pattern = shift; | |
my $pos; | |
if( ( $pos = index( $pattern, 'X' ) ) >= 0 ){ | |
for my $digit( 0..9 ){ | |
my $to_replace = $pattern; | |
substr( $to_replace, $pos, 1, $digit ); | |
print "$pattern $pos $digit $to_replace\n" if $ENV{DEBUG}; | |
process( $to_replace ); | |
} | |
} else { | |
print $pattern . "\n" if validate( $pattern ); | |
} | |
} | |
if( !$ARGV[0] ){ | |
usage(); | |
exit; | |
} | |
# Check for correct pattern | |
my $pattern = $ARGV[0]; | |
if( !( $pattern =~ /^[0-9X]+$/ ) ){ | |
usage(); | |
exit; | |
} | |
process( $pattern ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment