RosettaCodeData/Task/UPC/Phix/upc.phix
2026-04-30 12:34:36 -04:00

66 lines
2.7 KiB
Text

with javascript_semantics
constant numbers = {" ## #", -- 0
" ## #", -- 1
" # ##", -- 2
" #### #", -- 3
" # ##", -- 4
" ## #", -- 5
" # ####", -- 6
" ### ##", -- 7
" ## ###", -- 8
" # ##"} -- 9
function flip(string s)
for i,ch in s do
s[i] = iff(ch='#'?' ':'#')
end for
return s
end function
constant numberf = apply(numbers,flip)
procedure decode(string bar_code)
bar_code = trim(bar_code)
if length(bar_code)=95
and bar_code[1..3]="# #"
and bar_code[46..50]=" # # "
and bar_code[93..95]="# #" then
for reversed=false to true do
sequence r = {}, nums = numbers
integer st = 4, checksum = 0, k
for i=1 to 12 do
k = find(bar_code[st..st+6],nums)-1
if k=-1 then exit end if
r &= k
checksum += iff(odd(i)?k*3:k)
st += 7
if i=6 then
st += 5
nums = numberf
end if
end for
if k!=-1 then
if remainder(checksum,10) then
printf(1,"invalid checksum\n")
else
printf(1,"%v%s\n",{r,iff(reversed?" (upside down)","")})
end if
return
end if
bar_code = reverse(bar_code)
end for
end if
printf(1,"invalid\n")
end procedure
constant bar_codes = split("""
# # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # #
# # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # #
# # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # #
# # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # #
# # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # #
# # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # #
# # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # #
# # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # #
# # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # #
# # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # #
""","\n",true)
for t in bar_codes do decode(t) end for