UPC: Difference between revisions

2,585 bytes added ,  4 years ago
julia example
(Added Perl example)
(julia example)
Line 249:
 
It may be desirable to format the result differently, but that's currently not a part of the task definition.
 
=={{header|Julia}}==
{{trans|Perl 6}}
<lang julia>function decodeUPC(line)
pat1 = (" ## #", " ## #", " # ##", " #### #", " # ##",
" ## #", " # ####", " ### ##", " ## ###", " # ##")
pat2 = [replace(x, r"[# ]" => (x) -> x == " " ? "#" : " ") for x in pat1]
 
ptod1 = Dict((b => a - 1) for (a, b) in enumerate(pat1))
ptod2 = Dict((b => a - 1) for (a, b) in enumerate(pat2))
 
reg = Regex("^\\s*# #\\s*((?:" * join(pat1, "|") *
"){6})\\s*# #\\s*((?:" * join(pat2, "|") * "){6})\\s*# #\\s*")
 
if (m = match(reg, line)) != nothing
mats, dig, dsum = filter(!isempty, m.captures), Int[], 0
for mat in mats
append!(dig, [ptod1[x.match] for x in eachmatch(r"(.......)", mat)
if haskey(ptod1, x.match)])
append!(dig, [ptod2[x.match] for x in eachmatch(r"(.......)", mat)
if haskey(ptod2, x.match)])
end
dsum += sum([(isodd(i) ? 3 : 1) * n for (i, n) in enumerate(dig)])
if dsum % 10 == 0
return prod(string.(dig))
end
end
return ""
end
 
const lines = [
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ",
]
 
for line in lines
println((s = decodeUPC(line)) != "" ? s :
(s = decodeUPC(reverse(line))) != "" ? s : "Invalid")
end
</lang>{{out}}
<pre>
924773271019
403944441050
834999676706
939825158811
Invalid
316313718717
214575875608
818778841813
706466743030
653483540435
</pre>
 
 
=={{header|Perl}}==
4,102

edits