Calculate ISBN-13 check digit
Golfscript - 25 chars
{...+(;2%+{+}*3-~10%`+}:f
Whole program version is only 19 chars
...+(;2%+{+}*3-~10%
Check back here for analysis later. Meanwhile check out my old uninspired answer
Golfscript - 32 chars
Similar to the luhn number calculation
{.{2+}%.(;2%{.+}%+{+}*~)10%`+}:f
Analysis for 978030640615
{...}:f this is how you define the function in golfscript
. store an extra copy of the input string
'978030640615' '978030640615'
{2+}% add 2 to each ascii digit, so '0'=>50, I can get away with this instead
of {15&}% because we are doing mod 10 math on it later
'978030640615' [59 57 58 50 53 50 56 54 50 56 51 55]
. duplicate that list
'978030640615' [59 57 58 50 53 50 56 54 50 56 51 55] [59 57 58 50 53 50 56 54 50 56 51 55]
(; trim the first element off
'978030640615' [59 57 58 50 53 50 56 54 50 56 51 55] [57 58 50 53 50 56 54 50 56 51 55]
2% select every second element
'978030640615' [59 57 58 50 53 50 56 54 50 56 51 55] [57 50 50 54 56 55]
{.+}% double each element by adding to itself
'978030640615' [59 57 58 50 53 50 56 54 50 56 51 55] [114 100 100 108 112 110]
+ join the two lists together
'978030640615' [59 57 58 50 53 50 56 54 50 56 51 55 114 100 100 108 112 110]
{+}* add up the items in the list
'978030640615' 1293
~ bitwise not
'978030640615' -1294
) add one
'978030640615' -1293
10% mod 10
'978030640615' 7
` convert to str
'978030640615' '7'
+ join the strings
'9780306406157'
Python - 44 chars
f=lambda s:s+`-sum(map(int,s+s[1::2]*2))%10`
Python - 53 chars
def f(s):d=map(int,s);return s+`-sum(d+d[1::2]*2)%10`
Haskell - 54 characters
i s=s++show(sum[-read[c]*m|c<-s|m<-cycle[1,3]]`mod`10)
This requires support for parallel list comprehensions, which is supported by GHC (with the -XParallelListComp
flag) and Hugs (with the -98
flag).