ISBN13 check digit: Difference between revisions
m
syntax highlighting fixup automation
Langurmonkey (talk | contribs) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 26:
{{trans|Python}}
<
n = n.replace(‘-’, ‘’).replace(‘ ’, ‘’)
I n.len != 13
Line 40:
L(t) tests
print(‘ISBN13 ’t‘ validates ’is_isbn13(t))</
{{out}}
Line 52:
=={{header|8080 Assembly}}==
<
jmp demo
;;; ---------------------------------------------------------------
Line 118:
jmp 5
good: db 'good$'
bad: db 'bad$'</
{{out}}
Line 133:
=={{header|8086 Assembly}}==
<
bits 16
org 100h
Line 186:
section .data
good: db 'good$'
bad: db 'bad$'</
{{out}}
Line 201:
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<
BYTE FUNC CheckISBN13(CHAR ARRAY t)
Line 245:
Test("978-1788399081")
Test("978-1788399083")
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/ISBN13_check_digit.png Screenshot from Atari 8-bit computer]
Line 256:
=={{header|Ada}}==
<
procedure ISBN_Check is
Line 292:
Show ("978-1788399081");
Show ("978-1788399083");
end ISBN_Check;</
{{out}}
<pre>978-1734314502 Good
Line 301:
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
<
# returns TRUE if the alledged isbn13 has the correct check sum, #
# FALSE otherwise #
Line 335:
)
OD
END</
{{out}}
<pre>
Line 346:
=={{header|APL}}==
{{works with|Dyalog APL}}
<
13≠⍴n←(⍵∊⎕D)/⍵:0
0=10|(⍎¨n)+.×13⍴1 3
}</
{{out}}
Line 359:
===Composition of pure functions===
<
-- isISBN13 :: String -> Bool
Line 563:
return lst
end tell
end zipWith</
{{Out}}
<pre>{{"978-1734314502", true}, {"978-1734314509", false}, {"978-1788399081", true}, {"978-1788399083", false}}</pre>
Line 571:
This task ''can'' be tackled very simply by working through the numeric text two characters at a time:
<
if (ISBN13's class is not text) then return false
Line 608:
set output to output as text
set AppleScript's text item delimiters to astid
return output</
{{output}}
Line 618:
Or it can be handled purely numerically. Since the "weights" alternate and are palindromic, it makes no difference whether the last digit or the first is treated as the check digit. In fact, if preferred, the repeat below can go round 7 times with the <tt>return</tt> line as simply: <tt>return (sum mod 10 = 0)</tt>.
<
if (ISBN13's class is not text) then return false
Line 642:
return ((sum + ISBN13) mod 10 = 0)
end validateISBN13</
=={{header|Arturo}}==
<
currentCheck: to :integer to :string last isbn
isbn: map split chop replace isbn "-" "" 'd -> to :integer d
Line 666:
loop tests 'test [
print [test "=>" validISBN? test]
]</
{{out}}
Line 676:
=={{header|AutoHotkey}}==
<
for i, v in StrSplit(RegExReplace(n, "[^0-9]"))
sum += !Mod(i, 2) ? v*3 : v
return n "`t" (Mod(sum, 10) ? "(bad)" : "(good)")
}</
Examples:<
nums := ["978-1734314502","978-1734314509","978-1788399081","978-1788399083"]
for i, n in nums
output .= ISBN13_check_digit(n) "`n"
MsgBox % output
return</
{{out}}
<pre>978-1734314502 (good)
Line 694:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f ISBN13_CHECK_DIGIT.AWK
BEGIN {
Line 717:
return(substr(isbn,13,1) == check_digit ? "OK" : sprintf("NG check digit S/B %d",check_digit))
}
</syntaxhighlight>
{{out}}
<pre>
Line 729:
=={{header|BCPL}}==
<
let checkISBN(s) = valof
Line 761:
show("978-1788399081")
show("978-1788399083")
$)</
{{out}}
<pre>978-1734314502: good
Line 769:
=={{header|C}}==
<
int check_isbn13(const char *isbn) {
Line 800:
}
return 0;
}</
{{out}}
Line 812:
=={{header|C++}}==
{{trans|C}}
<
bool check_isbn13(std::string isbn) {
Line 847:
return 0;
}</
{{out}}
<pre>978-1734314502: good
Line 855:
=={{header|C sharp}}==
<
using System.Linq;
Line 877:
}
}
}</
{{out}}
<pre>
Line 886:
=={{header|CLU}}==
<
if string$size(s) ~= 14 then return(false) end
if s[4] ~= '-' then return(false) end
Line 919:
end
end
end start_up</
{{out}}
<pre>978-1734314502: good
Line 928:
=={{header|COBOL}}==
{{works with|GnuCOBOL}}
<
* Author: Jay Moseley
* Date: November 10, 2019
Line 1,067:
END FUNCTION validISBN13.
</syntaxhighlight>
{{out}}
Line 1,078:
=={{header|Cowgol}}==
<
sub check_isbn13(isbn: [uint8]): (r: uint8) is
Line 1,114:
print(result[check_isbn13(isbns[n])]);
n := n + 1;
end loop;</
{{out}}
<pre>978-1734314502: good
Line 1,123:
=={{header|D}}==
{{trans|Kotlin}}
<
bool isValidISBN13(string text) {
Line 1,147:
assert(isValidISBN13("978-1788399081"));
assert(!isValidISBN13("978-1788399083"));
}</
=={{header|Draco}}==
<
byte n, check, d;
char cur;
Line 1,188:
test("978-1788399081");
test("978-1788399083")
corp</
{{out}}
<pre>978-1734314502: good
Line 1,203:
{{Works with|Office 365 betas 2021}}
<
=LAMBDA(s,
LET(
Line 1,228:
)
)
)</
and also assuming the following generic bindings in the Name Manager for the WorkBook:
<
=LAMBDA(s,
MID(s,
Line 1,256:
AND(47 < ic, 58 > ic)
)
)</
{{Out}}
Line 1,290:
=={{header|Factor}}==
<
math.functions math.parser math.vectors qw sequences
sequences.extras sets unicode ;
Line 1,303:
qw{ 978-1734314502 978-1734314509 978-1788399081 978-1788399083 }
[ dup isbn13? "good" "bad" ? "%s: %s\n" printf ] each</
{{out}}
<pre>
Line 1,314:
=={{header|Forth}}==
The following word not only identifies correct 13 digit ISBN (and EAN) codes, but also 8 digit EAN and GTIN codes.
<syntaxhighlight lang="text">: is-digit [char] 0 - 10 u< ;
: isbn? ( a n -- f)
Line 1,321:
if [char] 0 - * rot + swap 3 * 8 mod else drop drop then
-1 chars +loop drop 10 mod 0= \ now calculate checksum
;</
{{out}}
In Forth, a "true" value is indicated by "-1".
Line 1,332:
=={{header|Fortran}}==
<
program isbn13
implicit none
Line 1,369:
end function check_isbn13
end program isbn13
</syntaxhighlight>
{{out}}
Line 1,380:
=={{header|FreeBASIC}}==
<
function is_num( byval c as string ) as boolean
Line 1,416:
print isbns(i)+": bad"
end if
next i</
{{out}}
Line 1,427:
=={{header|F_Sharp|F#}}==
<
open System
Line 1,445:
else
printfn "%s Invalid ISBN13" argv.[0]
0</
{{out}}
Line 1,462:
=={{header|Go}}==
<
import (
Line 1,502:
fmt.Printf("%s: %s\n", isbn, res)
}
}</
{{out}}
Line 1,513:
=={{header|Haskell}}==
<
import Text.Printf (printf)
Line 1,540:
"978-1788399081",
"978-1788399083"
]</
{{out}}
<pre>978-1734314502: Valid: True
Line 1,549:
Or, expressed in terms of ''cycle'':
<
isISBN13 :: String -> Bool
Line 1,568:
"978-1788399081",
"978-1788399083"
]</
{{Out}}
<pre>("978-1734314502",True)
Line 1,576:
=={{header|IS-BASIC}}==
<
110 DO
120 PRINT :INPUT PROMPT "ISBN-13 code: ":IS$
Line 1,601:
330 LET SUM=SUM+VAL(ISBN$(13))
340 IF MOD(SUM,10)=0 THEN LET ISBN=-1
350 END DEF</
=={{header|J}}==
<
isbn13c =: D&([ check@:i. clean)
Line 1,610:
lc =: [ +/@:* weight
weight =: 1 3 $~ #
clean =: ] -. a. -. [</
{{out}}
<
1 0 1 0</
=={{header|Java}}==
<
System.out.println(isISBN13("978-1734314502"));
System.out.println(isISBN13("978-1734314509"));
Line 1,635:
return false;
}
</
<pre>
true
Line 1,646:
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
<syntaxhighlight lang="jq">
def isbn_check:
def digits: tostring | explode | map( select(. >= 48 and . <= 57) | [.] | implode | tonumber);
Line 1,662:
testingcodes[]
| "\(.): \(if isbn_check then "good" else "bad" end)"
</syntaxhighlight>
{{out}}
<pre>
Line 1,672:
=={{header|Julia}}==
<
return sum(iseven(i) ? 3 * parse(Int, ch) : parse(Int, ch)
for (i, ch) in enumerate(replace(str, r"\D" => ""))) % 10 == 0
Line 1,683:
println(code, ": ", isbncheck(code) ? "good" : "bad")
end
</
<pre>
978-1734314502: good
Line 1,692:
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">
fun isValidISBN13(text: String): Boolean {
val isbn = text.replace(Regex("[- ]"), "")
Line 1,699:
.sum() % 10 == 0
}
</syntaxhighlight>
Tested using Spek
<syntaxhighlight lang="kotlin">
describe("ISBN Utilities") {
mapOf(
Line 1,719:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,731:
{{works with|langur|0.8.11}}
In this example, we map to multiple functions (actually 1 no-op).
<
.s = replace(.s, RE/[\- ]/)
matching(re/^[0-9]{13}$/, .s) and
Line 1,748:
write .key, ": ", if(.pass: "good"; "bad")
writeln if(.pass == .tests[.key]: ""; " (ISBN-13 CHECK DIGIT TEST FAILED)")
}</
{{works with|langur|0.9.0}}
In this example, we set a for loop value as it progresses.
<
.s = replace(.s, RE/[\- ]/)
var .alt = true
Line 1,770:
write .key, ": ", if(.pass: "good"; "bad")
writeln if(.pass == .tests[.key]: ""; " (ISBN-13 CHECK DIGIT TEST FAILED)")
}</
{{out}}
Line 1,780:
=={{header|Lua}}==
{{trans|C}}
<
local count = 0
local sum = 0
Line 1,820:
end
main()</
{{out}}
<pre>978-1734314502: good
Line 1,829:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
ValidISBNQ[iban_String] := Module[{i},
i = StringReplace[iban, {" " -> "", "-" -> ""}];
Line 1,843:
ValidISBNQ["978-1734314509"]
ValidISBNQ["978-1788399081"]
ValidISBNQ["978-1788399083"]</
{{out}}
<pre>True
Line 1,852:
=={{header|Modula-2}}==
<
FROM InOut IMPORT WriteString, WriteLn;
FROM Strings IMPORT Length;
Line 1,895:
check('978-1788399081');
check('978-1788399083');
END ISBN.</
{{out}}
<pre>978-1734314502: good
Line 1,904:
=={{header|Nanoquery}}==
{{trans|Go}}
<
// remove any hyphens or spaces
isbn = str(isbn).replace("-","").replace(" ","")
Line 1,939:
print format("%s: %s\n", isbn, res)
end</
{{out}}
<pre>978-1734314502: good
Line 1,947:
=={{header|Nim}}==
<
func is_isbn*(s: string): bool =
Line 1,964:
for isbn in isbns:
var quality: string = if is_isbn(isbn): "good" else: "bad"
echo &"{isbn}: {quality}"</
{{out}}
<pre>
Line 1,975:
=={{header|Pascal}}==
{{works with|Extended Pascal}}
<
const
Line 2,059:
writeLn(isValidISBNString('978-1788399081'));
writeLn(isValidISBNString('978-1788399083'))
end.</
{{out}}
<pre>True
Line 2,067:
=={{header|Perl}}==
<
use warnings;
use feature 'say';
Line 2,081:
my $check_d = check_digit($isbn);
say "$_ : " . ($check == $check_d ? 'Good' : "Bad check-digit $check; should be $check_d")
}</
{{out}}
<pre>978-1734314502 : Good
Line 2,091:
=={{header|Phix}}==
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">check_isbn13</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">isbn</span><span style="color: #0000FF;">)</span>
Line 2,113:
<span style="color: #008000;">"978-2-74839-908-0"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"978-2-74839-908-5"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"978 1 86197 876 9"</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">isbns</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span> <span style="color: #000000;">check_isbn13</span><span style="color: #0000FF;">(</span><span style="color: #000000;">isbns</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</
{{out}}
<pre>
Line 2,126:
=={{header|PicoLisp}}==
<
(let L
(make
Line 2,145:
"978-1-86197-876-9"
"978-2-74839-908-5"
"978 1 86197 876 9" ) )</
{{out}}
<pre>
Line 2,156:
=={{header|PL/M}}==
<
CHECK$ISBN13: PROCEDURE (PTR) BYTE;
Line 2,208:
CALL BDOS(0,0);
EOF</
{{out}}
<pre>978-1734314502: GOOD
Line 2,216:
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
function Get-ISBN13 {
$codes = (
Line 2,255:
}
Get-ISBN13
</syntaxhighlight>
{{out}}
Line 2,266:
=={{header|PureBasic}}==
<
Print(X)
If IsISBN13(X) : PrintN(" good") : Else : PrintN(" bad") : EndIf
Line 2,286:
TestISBN13("978-1788399083")
Input()
EndIf</
{{out}}
<pre>978-1734314502 good
Line 2,295:
=={{header|Python}}==
<
n = n.replace('-','').replace(' ', '')
if len(n) != 13:
Line 2,310:
978-1788399083'''.strip().split()
for t in tests:
print(f"ISBN13 {t} validates {is_isbn13(t)}")</
{{out}}
Line 2,320:
Or, expressed in terms of ''itertools.cycle''
<
Line 2,361:
if __name__ == '__main__':
main()
</syntaxhighlight>
{{Out}}
<pre>('978-1734314502', True)
Line 2,369:
=={{header|Quackery}}==
<
[ 1 & ] is odd? ( n --> b )
Line 2,400:
$ '978-1734314509' isbn-test
$ '978-1788399081' isbn-test
$ '978-1788399083' isbn-test</
{{out}}
<pre>
Line 2,411:
=={{header|Racket}}==
<
(define (isbn13-check-digit-valid? s)
Line 2,425:
(check-false (isbn13-check-digit-valid? "978-1734314509"))
(check-true (isbn13-check-digit-valid? "978-1788399081"))
(check-false (isbn13-check-digit-valid? "978-1788399083")))</
{{out}}
Line 2,435:
Also test a value that has a zero check digit.
<syntaxhighlight lang="raku"
(10 - (sum (|$isbn.comb(/<[0..9]>/)) »*» (1,3)) % 10).substr: *-1
}
Line 2,452:
978-2-74839-908-0
978-2-74839-908-5
>;</
{{out}}
<pre>978-1734314502 : Good
Line 2,464:
=={{header|Red}}==
<
is_digit: charset [#"0" - #"9"]
remove-each i str [not pick is_digit i] ; remove non-digits
Line 2,487:
print check_valid_isbn13 str
]
</syntaxhighlight>
{{out}}
Line 2,499:
=={{header|REXX}}==
A couple of additional checks were made to verify a correct length, and also that the ISBN-13 code is all numerics (with optional minus signs).
<
parse arg $ /*obtain optional arguments from the CL*/
if $='' | if $="," then $= '978-1734314502 978-1734314509 978-1788399081 978-1788399083'
Line 2,517:
if right(sum, 1)==0 then say ' ISBN-13 code ' x " is valid."
else say ' ISBN-13 code ' x " isn't valid."
end /*j*/ /*stick a fork in it, we're all done. */</
{{out|output|text= when using the four default inputs:}}
<pre>
Line 2,527:
=={{header|Ring}}==
<
load "stdlib.ring"
Line 2,552:
ok
next
</syntaxhighlight>
Output:
<pre>
Line 2,565:
=={{header|Ruby}}==
<
cleaned = str.delete("^0-9").chars
return false unless cleaned.size == 13
Line 2,573:
isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"]
isbns.each{|isbn| puts "#{isbn}: #{validISBN13?(isbn)}" }
</
<pre>978-1734314502: true
978-1734314509: false
Line 2,581:
=={{header|Rust}}==
<
let isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"];
isbns.iter().for_each(|isbn| println!("{}: {}", isbn, check_isbn(isbn)));
Line 2,595:
checksum % 10 == 0
}
</syntaxhighlight>
{{out}}
<pre>
Line 2,605:
=={{header|Seed7}}==
<
const func boolean: isISBN13 (in var string: input) is func
Line 2,638:
writeln(str <& ": " <& isISBN13(str));
end for;
end func;</
{{out}}
<pre>
Line 2,648:
=={{header|Standard ML}}==
<
fun check (c, p as (m, n)) =
if Char.isDigit c then
Line 2,662:
val () = (print
o concat
o map (fn s => s ^ (if checkISBN s then ": good\n" else ": bad\n"))) test</
{{out}}
<pre>978-1734314502: good
Line 2,671:
=={{header|Swift}}==
<
guard !isbn.isEmpty else {
return false
Line 2,694:
for isbn in cases {
print("\(isbn) => \(checkISBN(isbn: isbn) ? "good" : "bad")")
}</
Line 2,706:
=={{header|Tcl}}==
<
proc validISBN13 code {
regsub -all {\D} $code "" code ;# remove non-digits
Line 2,726:
978-1788399083
} {puts $test:[validISBN13 $test]}
</syntaxhighlight>
{{out}}
<pre>978-1734314502:true
Line 2,733:
978-1788399083:false</pre>
Simpler variant, using two loop vars and constant factors; same output:
<
proc validISBN13 code {
regsub -all {\D} $code "" code ;# remove non-digits
Line 2,746:
return false
}
</syntaxhighlight>
=={{header|uBasic/4tH}}==
{{works with|version 3.64.0}}
<syntaxhighlight lang="text">a := "978-1734314502"
Print Show(a), Show (Iif (Func(_IsISBN (a)), "good", "bad"))
Line 2,776:
Next
Return ((c@ % 10) = 0) ' modulus 10 must be zero</
{{out}}
<pre>978-1734314502 good
Line 2,787:
=={{header|UNIX Shell}}==
{{works with|Bourne Again Shell}}
<
local i n t
n=${1//[^0-9]/}
Line 2,804:
printf '%s\n' 'NOT OK'
fi
done</
{{Out}}
<pre>978-1734314502: OK
Line 2,813:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Function CheckISBN13(code As String) As Boolean
Line 2,840:
End Sub
End Module</
{{out}}
<pre>True
Line 2,849:
=={{header|Vlang}}==
{{trans|go}}
<
// remove any hyphens or spaces
isbn := isbn13.replace('-','').replace(' ','')
Line 2,881:
println("$isbn: $res")
}
}</
{{out}}
Line 2,892:
=={{header|Wren}}==
<
var cps = s.codePoints
var digits = []
Line 2,912:
for (test in tests) {
System.print("%(test) -> %(isbn13.call(test) ? "good" : "bad")")
}</
{{out}}
Line 2,923:
=={{header|XPL0}}==
<
proc ISBN13(Str); \Show if International Standard Book Number is good
Line 2,949:
ISBN13("978-1-59327-220-3");
ISBN13("978-178839918");
]</
{{out}}
Line 2,962:
=={{header|zkl}}==
<
var [const] one3=("13"*6 + 1).split("").apply("toInt"); // examine 13 digits
// one3=("13"*6) if you want to calculate what the check digit should be
one3.zipWith('*,isbn - " -").sum(0) % 10 == 0
}</
<
#<<<"
978-1734314502
Line 2,977:
#<<<
foreach isbn in (isbns)
{ println(isbn.strip()," ",ISBN13_check(isbn) and " Good" or " Bad") }</
{{out}}
<pre>
|