UPC: Difference between revisions
Content added Content deleted
SqrtNegInf (talk | contribs) (Added Perl example) |
|||
Line 249: | Line 249: | ||
It may be desirable to format the result differently, but that's currently not a part of the task definition. |
It may be desirable to format the result differently, but that's currently not a part of the task definition. |
||
=={{header|Perl}}== |
|||
{{trans|Perl 6}} |
|||
<lang perl>use strict; |
|||
use warnings; |
|||
use feature 'say'; |
|||
sub decode_UPC { |
|||
my($line) = @_; |
|||
my(%pattern_to_digit_1,%pattern_to_digit_2,@digits,$sum); |
|||
my @patterns1 = (' ## #', ' ## #', ' # ##', ' #### #', ' # ##', |
|||
' ## #', ' # ####', ' ### ##', ' ## ###', ' # ##'); |
|||
my @patterns2 = @patterns1; |
|||
$patterns2[$_] =~ tr/# / #/ for 0..$#patterns2; |
|||
$pattern_to_digit_1{$patterns1[$_]} = $_ for 0..$#patterns1; |
|||
$pattern_to_digit_2{$patterns2[$_]} = $_ for 0..$#patterns2; |
|||
my $re = '\s*# #\s*((?:' . join('|',@patterns1) . '){6})\s*# #\s*((?:' . join('|',@patterns2) . '){6})\s*# #\s*'; |
|||
$line =~ /^$re$/g || return; |
|||
my($match1,$match2) = ($1,$2); |
|||
push @digits, $pattern_to_digit_1{$_} for $match1 =~ /(.......)/g; |
|||
push @digits, $pattern_to_digit_2{$_} for $match2 =~ /(.......)/g; |
|||
$sum += (3,1)[$_%2] * $digits[$_] for 0..11; |
|||
$sum % 10 ? '' : join '', @digits; |
|||
} |
|||
my @lines = ( |
|||
' # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ', |
|||
' # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ', |
|||
' # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ', |
|||
' # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ', |
|||
' # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ', |
|||
' # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ', |
|||
' # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ', |
|||
' # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ', |
|||
' # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ', |
|||
' # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ', |
|||
); |
|||
for my $line (@lines) { |
|||
say decode_UPC($line) |
|||
// decode_UPC(join '', reverse split '', $line) |
|||
// 'Invalid'; |
|||
} |
|||
</lang> |
|||
{{out}} |
|||
<pre>924773271019 |
|||
403944441050 |
|||
834999676706 |
|||
939825158811 |
|||
Invalid |
|||
316313718717 |
|||
214575875608 |
|||
818778841813 |
|||
706466743030 |
|||
653483540435</pre> |
|||
=={{header|Perl 6}}== |
=={{header|Perl 6}}== |