RosettaCodeData/Task/UPC/Crystal/upc.cr
2026-04-30 12:34:36 -04:00

30 lines
1.7 KiB
Crystal

UPC_RE = %r{^\s*# #((?:[ #]{7}){6}) # # ((?:[ #]{7}){6})# #\s*$}
UPC_DIGITS = [" ## #", " ## #", " # ##", " #### #", " # ##",
" ## #", " # ####", " ### ##", " ## ###", " # ##"]
def decode_upc (line)
return nil unless line =~ UPC_RE
digits = ($1 + $2.tr("# ", " #")).chars.in_slices_of(7).map(&.join)
.map {|d| UPC_DIGITS.index! d }
if [3,1,3,1,3,1,3,1,3,1,3,1].zip(digits).map {|m, d| m * d}.sum % 10 != 0
return nil
end
digits
rescue
return nil
end
[" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # "]
.each do |line|
code = decode_upc(line) || decode_upc(line.reverse)
puts code || "(bad barcode)"
end