ISBN13 check digit: Difference between revisions

→‎{{header|Ruby}}: replaced by more idiomatic Ruby
(Add Fortran implementation.)
(→‎{{header|Ruby}}: replaced by more idiomatic Ruby)
Line 1,602:
 
=={{header|Ruby}}==
<lang ruby>def checkISBN13validISBN13?(codestr)
{{trans|C#}}
cleaned = str.delete("^0-9").chars
<lang ruby>def checkISBN13(code)
return false unless cleaned.size == 13
length = 0
cleaned.each_slice(2).sum{|d1, d2| d1.to_i + 3*d2.to_i }.remainder(10) == 0
sum = 0
 
code.split('').each { |c|
if '0' <= c and c <= '9' then
if length % 2 == 0 then
sum = sum + 1 * (c.ord - '0'.ord)
else
sum = sum + 3 * (c.ord - '0'.ord)
end
 
length = length + 1
end
}
 
if length != 13 then
return false
end
 
return sum % 10 == 0
end
 
def main
puts checkISBN13("978-1734314502")
puts checkISBN13("978-1734314509")
puts checkISBN13("978-1788399081")
puts checkISBN13("978-1788399083")
end
 
isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"]
main()</lang>
isbns.each{|isbn| puts "#{isbn}: #{validISBN13?(isbn)}" }
</lang>{{out}}
<pre>true
<pre>978-1734314502: true
false
978-1734314509: false
true
978-1788399081: true
false</pre>
978-1788399083: false
</pre>true
 
=={{header|Rust}}==
1,149

edits