what is the excel formula to convert a ten digit isbn to the thirteen digit ean code?
ISBN13 check digit
Y'all are encouraged to solve this task according to the task description, using any language you may know.
- Task
Validate the check digit of an ISBN-13 code:
-
-
- Multiply every other digit by3.
- Add these numbers and the other digits.
- Take the remainder of this number after division byx.
- If information technology is0, the ISBN-13 cheque digit is right.
-
Use the following codes for testing:
-
-
-
-
- 978-1734314502 (good)
- 978-1734314509 (bad)
- 978-1788399081 (good)
- 978-1788399083 (bad)
-
-
-
Show output hither, on this page
- See also
-
- for details: 13-digit ISBN method of validation. (installs cookies.)
Contents
- 1 11l
- 2 8080 Assembly
- 3 8086 Assembly
- 4 Action!
- 5 Ada
- vi ALGOL 68
- 7 APL
- eight AppleScript
- 8.i Composition of pure functions
- eight.ii Straightforward
- nine Arturo
- 10 AutoHotkey
- eleven AWK
- 12 BCPL
- 13 C
- fourteen C++
- 15 C#
- 16 CLU
- 17 COBOL
- 18 Cowgol
- nineteen D
- 20 Draco
- 21 Excel
- 21.i LAMBDA
- 22 Cistron
- 23 Forth
- 24 Fortran
- 25 FreeBASIC
- 26 F#
- 27 Fōrmulæ
- 28 Go
- 29 Haskell
- 30 IS-Basic
- 31 J
- 32 Java
- 33 jq
- 34 Julia
- 35 Kotlin
- 36 langur
- 37 Lua
- 38 Mathematica / Wolfram Language
- 39 Modula-2
- forty Nanoquery
- 41 Nim
- 42 Pascal
- 43 Perl
- 44 Phix
- 45 PicoLisp
- 46 PL/M
- 47 PowerShell
- 48 PureBasic
- 49 Python
- 50 Quackery
- 51 Racket
- 52 Raku
- 53 Red
- 54 REXX
- 55 Ring
- 56 Cerise
- 57 Rust
- 58 Seed7
- 59 Standard ML
- 60 Swift
- 61 Tcl
- 62 uBasic/4tH
- 63 UNIX Shell
- 64 Visual Basic .Cyberspace
- 65 Wren
- 66 XPL0
- 67 zkl
11l [edit]
F is_isbn13(=due north)
north = northward.replace('-', '').supplant(' ', '')
I due north.len != xiii
R 0B
V product = sum(due north[(0..).stride(2)].map(ch -> Int(ch)))
+ sum(n[(1..).stride(2)].map(ch -> Int(ch) * three))
R product % ten == 0V tests = |'978-1734314502
978-1734314509
978-1788399081
978-1788399083'.split("\n")L(t) tests
print('ISBN13 't' validates 'is_isbn13(t))
ISBN13 978-1734314502 validates 1B ISBN13 978-1734314509 validates 0B ISBN13 978-1788399081 validates 1B ISBN13 978-1788399083 validates 0B
8080 Associates [edit]
org 100h
jmp demo
;;; ---------------------------------------------------------------
;;; Check if the string at BC is a valid ISBN-13 code.
;;; Carry set up if true, clear if not.
isbn13: lxi h,0 ; HL = accumulator
mov d,h ; D = 0 (such that if E=A, DE=A).
call isbngc ; Become first character
rnc ; Carry clear = invalid
dad d ; Add together to running total one time
telephone call isbngc ; Go second grapheme
rnc ; Carry clear = invalid
dad d ; Add to running total thrice
dad d
dad d
telephone call isbngc ; Go third character
rnc ; Carry clear = invalid
dad d ; Add to running total once
ldax b ; 4th character should exist a dash '-'
inx b
cpi '-'
stc ; Clear carry w/o touching other flags
cmc
rnz ; If not equal, invalid.
push h ; Keep loop counter on stack
mvi fifty,five ; 5 times ii characters
isbnlp: xthl ; Accumulator in HL
call isbngc ; Get even grapheme
jnc isbnex ; If invalid, stop
dad d ; Add to running total thrice
dad d
dad d
telephone call isbngc ; Become odd character
jnc isbnex ; If invalid, finish
dad d ; Add to running total once
xthl ; Loop counter in (H)L
dcr l ; Done nonetheless?
jnz isbnlp ; If not, do next ii characters
popular h ; Get accumulator
lxi d,-ten ; Trial sectionalisation past x
isbndv: dad d ; Decrease 10
jc isbndv ; Until nix passed
mov a,l ; Move low byte to A
adi 10 ; Add ten back (the mod loop went ane step too far)
rz ; If null, return (carry will take been ready)
ana a ; Otherwise, make certain conduct is clear
ret ; And then return
isbnex: pop h ; Exam failed - throw abroad accumulator and return
ret
isbngc: ldax b ; Become character from [BC]
inx b ; Increment BC
sui '0' ; Subtract ASCII '0' to get digit value
cpi x ; If x or higher (unsigned), invalid digit.
mov e,a ; Set (D)Due east = value
ret
;;; ---------------------------------------------------------------
;;; Demo: see if the CP/Grand command line contains a valid ISBN13
;;; lawmaking.
demo: lxi b,82h ; Beginning of control line argument, skipping first space
call isbn13 ; Is information technology valid?
mvi c,9 ; CP/M impress string
lxi d,proficient ; If acquit is fix, then yes
jc 5
lxi d,bad ; Otherwise, no.
jmp v
good: db 'good$'
bad: db 'bad$'
A>isbn13 978-1734314502 adept A>isbn13 978-1734314509 bad A>isbn13 978-1788399081 skilful A>isbn13 978-1788399083 bad
8086 Assembly [edit]
cpu 8086
$.25 sixteen
org 100h
section .text
jmp demo
isbn13: ;;; ---------------------------------------------------------------
;;; Check if the string at DS:SI is a valid ISBN-13 code.
;;; Deport set if true, clear if imitation.
xor dx , dx ; DX = running total
xor ah , ah ; Set AH=0 so that AX=AL
call .digit ; Get first digit and add to DX
call .digit ; Get second digit and add to DX
add dx , ax ; Add to DX twice more
add dx , ax
telephone call .digit ; Become 3rd digit and add together to DX
lodsb ; Fourth character should be a '-'
cmp al , '-'
jne .neglect ; If not equal, fail
mov cx , 5 ; And then loop v times for the adjacent x digits
. loop : call .digit ; Get even digit and add together to DX
add dx , ax ; Add to running total twice more
add dx , ax
call .digit ; Get odd digit and add to DX
loop . loop ; Exercise this v times
mov ax , dx ; Divide running total by ten
mov dl , 10
div dl
test ah , ah ; Is the rest nothing?
jnz . out ; If not, terminate (TEST clears carry)
stc ; Otherwise, set carry and render
ret
.digit: lodsb ; Become showtime character
sub al , '0' ; Decrease ASCII 0 to get digit value
cmp al , 9
ja .dfail
add together dx , ax ; Add to ASCII
ret
.dfail: popular dx ; Remove return pointer for .digit from stack
.fail: clc ; Failure - clear carry
. out : ret
;;; ---------------------------------------------------------------
;;; Demo: see if the MS-DOS command line contains a valid ISBN13
;;; code.
demo: mov si , 82h ; Start of command line argument skipping space
phone call isbn13 ; Is information technology valid?
mov ah , ix ; MS-DOS print string
mov dx ,good ; If conduct is set, information technology is good
jc .print
mov dx ,bad ; Otherwise, it is bad
.print: int 21h
ret
department .data
practiced: db 'skillful$'
bad: db 'bad$'
C:\>isbn13 978-1734314502 expert C:\>isbn13 978-1734314509 bad C:\>isbn13 978-1788399081 proficient C:\>isbn13 978-1788399083 bad
Action! [edit]
INCLUDE "D2:CHARTEST.ACT" ;from the Action! Tool KitBYTE FUNC CheckISBN13(CHAR ARRAY t)
BYTE i,index,sum,vsum=0 index=0
FOR i=1 TO t(0)
DO
five=t(i)
IF IsDigit(v) THEN
5==-'0
IF index MOD 2=i And then
v==*three
FI
sum==+5
index==+i
ELSEIF 5#' AND 5#'- THEN
RETURN (0)
FI
OD
IF index#13 OR sum MOD ten#0 So
RETURN (0)
FI
RETURN (1)PROC Test(CHAR Assortment t)
BYTE correctcorrect=CheckISBN13(t)
Print(t) Print(" is ")
IF correct THEN
PrintE("correct")
ELSE
PrintE("incorrect")
FI
ReturnPROC Main()
Put(125) PutE() ;articulate screenTest("978-1734314502")
Test("978-1734314509")
Test("978-1788399081")
Exam("978-1788399083")
RETURN
Screenshot from Atari 8-bit computer
978-1734314502 is correct 978-1734314509 is incorrect 978-1788399081 is correct 978-1788399083 is incorrect
Ada [edit]
with Ada.Text_IO;process ISBN_Check is
function Is_Valid (ISBN : Cord) render Boolean is
Odd : Boolean := Truthful;
Sum : Integer := 0;
Value : Integer;
brainstorm
for I in ISBN'Range loop
if ISBN (I) in '0' .. '9' then
Value := Graphic symbol'Pos (ISBN (I) ) - Character'Pos ('0');
if Odd then
Sum := Sum + Value;
else
Sum := Sum + 3 * Value;
end if;
Odd := not Odd;
end if;
end loop;
render Sum modern x = 0;
end Is_Valid;procedure Show (ISBN : String) is
use Ada.Text_IO;
Valid : abiding Boolean := Is_Valid (ISBN);
brainstorm
Put (ISBN); Put ( " " );
Put ( ( if Valid and then "Good" else "Bad" ) );
New_Line;
cease Testify;
begin
Show ( "978-1734314502" );
Show ( "978-1734314509" );
Evidence ( "978-1788399081" );
Show ( "978-1788399083" );
end ISBN_Check;
978-1734314502 Good 978-1734314509 Bad 978-1788399081 Practiced 978-1788399083 Bad
ALGOL 68 [edit]
Begin # Check some IsBN13 bank check digits #
# returns True if the alledged isbn13 has the correct check sum, #
# FALSE otherwise #
# not-digit characters are ignored and there must be 13 digits #
PROC check isbn13 = ( String isbn13 ) BOOL :
Brainstorm
INT sum := 0;
INT digits := 0;
BOOL other digit := Fake ;
FOR pos FROM LWB isbn13 TO UPB isbn13 DO
IF CHAR c = isbn13[ pos ] ;
c >= "0" AND c <= "9"
And so
# have another digit #
digits +:= ane;
sum +:= ( ABS c - ABS "0" ) * IF other digit THEN 3 ELSE 1 FI ;
other digit := Not other digit
FI
OD ;
digits = 13 AND sum Modernistic 10 = 0
END ; # check isbn13 #
# task test cases #
[ ] STRING tests = ( "978-1734314502" , "978-1734314509" , "978-1788399081" , "978-1788399083" ) ;
[ ] BOOL expected = ( TRUE , Faux , True , FALSE ) ;
FOR pos FROM LWB tests TO UPB tests Exercise
BOOL result = check isbn13( tests[ pos ] ) ;
print ( ( tests[ pos ]
, ": "
, IF result THEN "skillful" ELSE "bad" FI
, IF issue = expected[ pos ] THEN "" ELSE " Not AS EXPECTED" FI
, newline
)
)
OD
END
978-1734314502: skilful 978-1734314509: bad 978-1788399081: good 978-1788399083: bad
APL [edit]
check_isbn13←{
13≠⍴n←(⍵∊⎕D)/⍵:0
0=10|(⍎¨n)+.×13⍴1 3
}
check_isbn13¨ '978-1734314502' '978-1734314509' '978-1788399081' '978-1788399083' 1 0 ane 0
AppleScript [edit]
Limerick of pure functions [edit]
-------------------- ISBN13 Bank check DIGIT ---------------------- isISBN13 :: Cord -> Bool
on isISBN13(s)
script digitValue
on |λ|(c)
if isDigit(c) and then
{c as integer }
else
{ }
end if
cease |λ|
terminate scriptset digits to concatMap(digitValue, characters of southward)
13 = length of digits ¬
and 0 = sum(zipWith( my mul, digits, cycle( { 1, 3 } ) ) ) mod 10
end isISBN13--------------------------- Test ---------------------------
on run
script examination
on |λ|(s)
{due south, isISBN13(s) }
end |λ|
finish scriptmap(test, { "978-1734314502", "978-1734314509", ¬
"978-1788399081", "978-1788399083" } )
end run-------------------- GENERIC FUNCTIONS ---------------------
-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
set lng to length of xs
set acc to { }
tell mReturn(f)
repeat with i from 1 to lng
set acc to acc & (|λ|( item i of xs, i, xs) )
stop repeat
end tell
render acc
end concatMap-- cycle :: [a] -> Generator [a]
on bike(xs)
script
property lng : 1 + (length of xs)
property i : missing value
on |λ|( )
if missing value is i then
set i to 1
else
set nxt to ( 1 + i) mod lng
if 0 = ( ( 1 + i) mod lng) then
set i to i
else
prepare i to nxt
end if
end if
return item i of xs
end |λ|
end script
finish cycle-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
prepare v to startValue
set lng to length of xs
echo with i from one to lng
set v to |λ|(v, item i of xs, i, xs)
end echo
return v
end tell
end foldl-- isDigit :: Char -> Bool
on isDigit(c)
ready due north to ( id of c)
48 ≤ n and 57 ≥ due north
end isDigit-- length :: [a] -> Int
on |length|(xs)
set c to class of xs
if list is c or string is c then
length of xs
else
( 2 ^ 29 - i ) -- (maxInt - unproblematic proxy for non-finite)
end if
end |length|-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
-- The list obtained by applying f
-- to each element of xs.
tell mReturn(f)
set lng to length of xs
set lst to { }
repeat with i from one to lng
set terminate of lst to |λ|( particular i of xs, i, xs)
end repeat
render lst
end tell
end map-- min :: Ord a => a -> a -> a
on min(x, y)
if y < ten then
y
else
10
terminate if
finish min-- mReturn :: Beginning-course m => (a -> b) -> k (a -> b)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper.
if script is grade of f so
f
else
script
property |λ| : f
end script
end if
end mReturn-- mul (*) :: Num a => a -> a -> a
on mul(a, b)
a * b
stop mul-- sum :: [Num] -> Num
on sum(xs)
script add
on |λ|(a, b)
a + b
terminate |λ|
finish scriptfoldl(add, 0, xs)
end sum-- take :: Int -> [a] -> [a]
-- take :: Int -> String -> String
on have(due north, xs)
set c to form of xs
if listing is c then
if 0 < northward then
items 1 thru min(n, length of xs) of xs
else
{ }
stop if
else if cord is c then
if 0 < n so
text 1 thru min(n, length of xs) of xs
else
""
end if
else if script is c so
set ys to { }
repeat with i from ane to northward
ready v to |λ|( ) of xs
if missing value is v then
render ys
else
set end of ys to v
end if
end repeat
return ys
else
missing value
finish if
cease have-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(|length|(xs), |length|(ys) )
if i > lng then return { }
set xs_ to take(lng, xs) -- Let for non-finite
prepare ys_ to take(lng, ys) -- generators like cycle etc
gear up lst to { }
tell mReturn(f)
echo with i from 1 to lng
prepare terminate of lst to |λ|( particular i of xs_, item i of ys_)
end echo
return lst
terminate tell
cease zipWith
{{"978-1734314502", true}, {"978-1734314509", simulated}, {"978-1788399081", true}, {"978-1788399083", false}}
Straightforward [edit]
This job can be tackled very simply by working through the numeric text two characters at a time:
on validateISBN13(ISBN13)
if (ISBN13'due south class is not text ) then return falsegear up astid to AppleScript'southward text item delimiters
gear up AppleScript'southward text item delimiters to { "-", space }
set ISBN13 to ISBN13's text items
set AppleScript's text item delimiters to ""
set ISBN13 to ISBN13 as text
set AppleScript's text item delimiters to astidif ( ( ( count ISBN13) is not 13 ) or (ISBN13 contains "." ) or (ISBN13 contains "," ) ) and so return faux
effort
ISBN13 as number
on mistake
return false
end tryset sum to 0
repeat with i from 1 to 12 by ii
gear up sum to sum + (character i of ISBN13) + (character (i + one ) of ISBN13) * 3 -- Automatic text-to-number coercions.
end repeatreturn ( (sum + (character thirteen of ISBN13) ) modernistic 10 = 0 )
end validateISBN13-- Test:
set up output to { }
set verdicts to { "bad", "good" }
repeat with thisISBN13 in { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" }
fix isValid to validateISBN13(thisISBN13)
gear up end of output to thisISBN13 & ": " & detail ( (isValid as integer ) + 1 ) of verdicts
finish repeatset astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to linefeed
set output to output as text
set up AppleScript's text particular delimiters to astid
render output
"978-1734314502: proficient 978-1734314509: bad 978-1788399081: good 978-1788399083: bad"
Or it can be handled purely numerically. Since the "weights" alternate and are palindromic, it makes no difference whether the last digit or the starting time is treated as the check digit. In fact, if preferred, the repeat below can get round seven times with the return line as simply: return (sum mod 10 = 0).
on validateISBN13(ISBN13)
if (ISBN13's class is non text ) then return falseset astid to AppleScript'southward text item delimiters
fix AppleScript's text item delimiters to { "-", space }
set ISBN13 to ISBN13's text items
ready AppleScript'southward text item delimiters to ""
set ISBN13 to ISBN13 as text
set AppleScript's text item delimiters to astidif ( ( ( count ISBN13) is not xiii ) or (ISBN13 contains "." ) or (ISBN13 contains "," ) ) then render false
endeavour
set ISBN13 to ISBN13 as number
on error
return false
stop tryset sum to 0
repeat 6 times
set up sum to sum + ISBN13 mod 10 + ISBN13 mod 100 div x * 3
prepare ISBN13 to ISBN13 div 100
cease repeatrender ( (sum + ISBN13) mod 10 = 0 )
cease validateISBN13
Arturo [edit]
validISBN?: function [isbn] [
currentCheck: to :integer to :cord terminal isbn
isbn: map split chop replace isbn "-" "" => [ to :integer]south: 0
loop.with:'i isbn 'northward [
if? even? i -> southward: s + n
else -> s: s + 3 *n
]
checkDigit: 10 - due south % 10
return currentCheck = checkDigit
]tests: [
"978-1734314502" "978-1734314509"
"978-1788399081" "978-1788399083"
]loop tests 'test [
print [test "=>" validISBN? exam]
]
978-1734314502 => true 978-1734314509 => false 978-1788399081 => true 978-1788399083 => false
AutoHotkey [edit]
ISBN13_check_digit(n) {
for i, five in StrSplit( RegExReplace (due north, "[^0-9]" ) )
sum += !Mod (i, 2 ) ? five* 3 : five
render n "`t" ( Mod (sum, 10 ) ? "(bad)" : "(good)" )
}
Examples:
output := ""
nums := [ "978-1734314502" , "978-1734314509" , "978-1788399081" , "978-1788399083" ]
for i, northward in nums
output .= ISBN13_check_digit(n) "`n"
MsgBox % output
render
978-1734314502 (practiced) 978-1734314509 (bad) 978-1788399081 (good) 978-1788399083 (bad)
AWK [edit]
# syntax: GAWK -f ISBN13_CHECK_DIGIT.AWK
BEGIN {
arr[ ++n] = "978-1734314502"
arr[ ++n] = "978-1734314509"
arr[ ++due north] = "978-1788399081"
arr[ ++north] = "978-1788399083"
arr[ ++n] = "9780820424521"
arr[ ++north] = "0820424528"
for (i=ane; i<=north; i++ ) {
printf ( "%south %s\northward",arr[i],isbn13(arr[i] ) )
}
leave( 0 )
}
function isbn13(isbn, check_digit,i,sum) {
gsub ( / [ - ] /,"",isbn)
if ( length (isbn) != xiii ) { return ( "NG length" ) }
for (i=1; i<= 12; i++ ) {
sum += substr (isbn,i,1 ) * (i % two == 1 ? one : 3 )
}
check_digit = x - (sum % 10 )
return ( substr (isbn,thirteen,i ) == check_digit ? "OK" : sprintf ( "NG check digit Due south/B %d",check_digit) )
}
978-1734314502 OK 978-1734314509 NG check digit S/B two 978-1788399081 OK 978-1788399083 NG check digit S/B ane 9780820424521 OK 0820424528 NG length
BCPL [edit]
go "libhdr"allow checkISBN(s) = valof
$( allow tally = 0
unless s%0 = 14 resultis false
unless southward%four = '-' resultis falsefor i=1 to 3
$( permit digit = s%i-'0'
test i rem two = 0
practice tally := tally + 3 * digit
or tally := tally + digit
$)for i=5 to xiv
$( let digit = s%i-'0'
exam i rem ii = 0
do tally := tally + digit
or tally := tally + three * digit
$)resultis tally rem 10 = 0
$)let show(s) exist
writef("%S: %South*N", due south, checkISBN(south) -> "good", "bad")let outset() be
$( show("978-1734314502")
show("978-1734314509")
show("978-1788399081")
show("978-1788399083")
$)
978-1734314502: good 978-1734314509: bad 978-1788399081: skilful 978-1788399083: bad
C [edit]
#include <stdio.h>int check_isbn13( const char *isbn) {
int ch = *isbn, count = 0 , sum = 0 ;
/* check isbn contains xiii digits and summate weighted sum */
for ( ; ch != 0 ; ch = *++isbn, ++count) {
/* skip hyphens or spaces */
if (ch == ' ' || ch == '-' ) {
--count;
go along ;
}
if (ch < '0' || ch > '9' ) {
return 0 ;
}
if (count & 1 ) {
sum += 3 * (ch - '0' ) ;
} else {
sum += ch - '0' ;
}
}
if (count != 13 ) return 0 ;
render ! (sum% 10 ) ;
}int master( ) {
int i;
const char * isbns[ ] = { "978-1734314502" , "978-1734314509" , "978-1788399081" , "978-1788399083" } ;
for (i = 0 ; i < 4 ; ++i) {
printf ( "%s: %s\northward" , isbns[i] , check_isbn13(isbns[i] ) ? "good" : "bad" ) ;
}
return 0 ;
}
978-1734314502: good 978-1734314509: bad 978-1788399081: expert 978-1788399083: bad
C++ [edit]
#include <iostream>bool check_isbn13(std:: string isbn) {
int count = 0 ;
int sum = 0 ;for ( auto ch : isbn) {
/* skip hyphens or spaces */
if (ch == ' ' || ch == '-' ) {
keep ;
}
if (ch < '0' || ch > '9' ) {
return false ;
}
if (count & one ) {
sum + = 3 * (ch - '0' ) ;
} else {
sum + = ch - '0' ;
}
count++ ;
}if (count ! = 13 ) {
render false ;
}
return sum % 10 == 0 ;
}int main( ) {
auto isbns = { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" } ;
for ( car isbn : isbns) {
std:: cout << isbn << ": " << (check_isbn13(isbn) ? "expert" : "bad" ) << '\due north' ;
}render 0 ;
}
978-1734314502: good 978-1734314509: bad 978-1788399081: good 978-1788399083: bad
C# [edit]
using System ;
using Arrangement.Linq ;public class Program
{
public static void Main( ) {
Console. WriteLine (CheckISBN13( "978-1734314502" ) ) ;
Console. WriteLine (CheckISBN13( "978-1734314509" ) ) ;
Console. WriteLine (CheckISBN13( "978-1788399081" ) ) ;
Panel. WriteLine (CheckISBN13( "978-1788399083" ) ) ;static bool CheckISBN13( string lawmaking) {
code = code. Replace ( "-", "" ) . Replace ( " ", "" ) ;
if (code. Length != thirteen ) return false ;
int sum = 0 ;
foreach ( var (alphabetize, digit) in code. Select ( (digit, index) => (index, digit) ) ) {
if ( char . IsDigit (digit) ) sum += (digit - '0' ) * (index % 2 == 0 ? 1 : 3 ) ;
else return false ;
}
render sum % x == 0 ;
}
}
}
True Simulated True Fake
CLU [edit]
isbn13_check = proc (s: string) returns (bool)
if string$size(s) ~= 14 then return(false) end
if s[4] ~= '-' and then return(false) end
begin
check: int := 0
for i: int in int$from_to(1, 14) practice
if i=iv and so continue end
d: int := int$parse(string$c2s(due south[i]))
if i=2 cor (i>iv cand i//2=1) then d := d*3 terminate
check := check + d
terminate
return(check//ten = 0)
finish except when bad_format:
return(false)
end
end isbn13_checkstart_up = proc ()
po: stream := stream$primary_output()
tests: array[cord] := array[string]$
["978-1734314502",
"978-1734314509",
"978-1788399081",
"978-1788399083"]for test: string in array[string]$elements(tests) exercise
stream$puts(po, test)
stream$puts(po, ": ")
if isbn13_check(test)
then stream$putl(po, "adept")
else stream$putl(po, "bad")
end
cease
stop start_up
978-1734314502: good 978-1734314509: bad 978-1788399081: good 978-1788399083: bad
COBOL [edit]
******************************************************************
* Author: Jay Moseley
* Date: November 10 , 2019
* Purpose: Testing diverse subprograms/ functions.
* Tectonics: cobc -xj testSubs.cbl
******************************************************************
IDENTIFICATION DIVISION .Plan-ID . testSubs.
Environs DIVISION .CONFIGURATION Section .
REPOSITORY.
Office ALL INTRINSIC
FUNCTION validISBN13.INPUT-OUTPUT SECTION .
FILE-Control .Data DIVISION .
FILE Department .
WORKING-STORAGE Section .
01 IX PIC S9( 4 ) COMP .
01 Examination-ISBNS.
02 FILLER PIC 10( xiv ) VALUE '978-1734314502' .
02 FILLER PIC 10( 14 ) VALUE '978-1734314509' .
02 FILLER PIC X( 14 ) VALUE '978-1788399081' .
02 FILLER Flick Ten( 14 ) VALUE '978-1788399083' .
01 TEST-ISBN REDEFINES TEST-ISBNS
OCCURS iv TIMES
PIC X( fourteen ) .Process DIVISION .
Chief-Process .
PERFORM
VARYING Ix
FROM ane
Past one
UNTIL Ix > 4DISPLAY Exam-ISBN (Nine) ' ' WITH NO ADVANCING
END-Display
IF validISBN13(TEST-ISBN (IX) ) = -1
DISPLAY '(bad)'
ELSE
Brandish '(good)'
END-IFEND-PERFORM .
GOBACK.
END PROGRAM testSubs.
******************************************************************
* Author: Jay Moseley
* Appointment: May 19 , 2016
* Purpose: validate ISBN-13 (International Standard
* Book Number ) .
******************************************************************
IDENTIFICATION DIVISION .Office-ID. validISBN13.
Surround DIVISION .CONFIGURATION Department .
REPOSITORY.
Role ALL INTRINSIC.INPUT-OUTPUT Section .
FILE-Control .Data Sectionalization .
FILE Department .
WORKING-STORAGE SECTION .
01 PASSED-SIZE Moving-picture show S9( 6 ) COMP-5 .
01 IX Film S9( 4 ) COMP .01 Work-FIELDS.
02 WF-DIGIT Moving-picture show Ten.
02 WF-COUNT Motion-picture show 9 ( ii ) .
88 WEIGHT-i VALUE ane , 3 , 5 , vii , ix , eleven , 13 .
88 WEIGHT-3 VALUE ii , 4 , 6 , 8 , 10 , 12 .
02 WF-SUM Picture S9( eight ) COMP .LINKAGE SECTION .
01 PASSED-ISBN PIC X ANY LENGTH .
01 RETURN-VALUE PIC S9.PROCEDURE DIVISION USING PASSED-ISBN
RETURNING RETURN-VALUE .CALL 'C$PARAMSIZE'
USING 1
GIVING PASSED-SIZE
END-Call .COMPUTE-CKDIGIT.
INITIALIZE WORK-FIELDS.
PERFORM
VARYING IX
FROM ane
Past 1
UNTIL Ix GREATER THAN PASSED-SIZEMove PASSED-ISBN (Ix:1 ) TO WF-DIGIT
IF WF-DIGIT IS NUMERIC
ADD 1 TO WF-COUNT
IF WEIGHT-1
ADD NUMVAL (WF-DIGIT) TO WF-SUM
ELSE
COMPUTE WF-SUM = WF-SUM +
( NUMVAL (WF-DIGIT) * iii )
END-COMPUTE
END-IF
Stop-IFEND-PERFORM .
IF MOD (WF-SUM , x ) = 0
MOVE +0 TO RETURN-VALUE
ELSE
Movement -1 TO Render-VALUE
END-IF .GOBACK.
* - - - - - - - - - - - - - - - - - - - - - - PROGRAM Leave POINTEND FUNCTION validISBN13.
978-1734314502 (proficient) 978-1734314509 (bad) 978-1788399081 (good) 978-1788399083 (bad)
Cowgol [edit]
include "cowgol.coh";sub check_isbn13(isbn: [uint8]): (r: uint8) is
var north: uint8 := 0;
r := 0;
loop
var c := [isbn];
isbn := @adjacent isbn;
if c == 0 then break; end if;
c := c - '0';
if c <= 9 so
r := r + c;
due north := northward + 1;
if (n & one) == 0 so
r := r + c * 2;
terminate if;
finish if;
stop loop;
if n == 13 and r%10 == 0 so
r := 1;
else
r := 0;
end if;
end sub;var isbns: [uint8][] := {
"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"
};var result: [uint8][] := {": bad\n", ": good\north"};
var n: uint8 := 0;
while n < @sizeof isbns loop
impress(isbns[n]);
print(result[check_isbn13(isbns[n])]);
n := n + one;
stop loop;
978-1734314502: good 978-1734314509: bad 978-1788399081: practiced 978-1788399083: bad
D [edit]
import std.stdio ;bool isValidISBN13( cord text) {
int sum, i;
foreach (c; text) {
if ( '0' <= c && c <= '9' ) {
int value = c - '0' ;
if (i % two == 0 ) {
sum += value;
} else {
sum += iii * value;
}i++;
}
}
render i == 13 && 0 == sum % 10 ;
}unittest {
assert (isValidISBN13( "978-1734314502" ) ) ;
assert ( !isValidISBN13( "978-1734314509" ) ) ;
assert (isValidISBN13( "978-1788399081" ) ) ;
assert ( !isValidISBN13( "978-1788399083" ) ) ;
}
Draco [edit]
proc nonrec isbn13_check(*char isbn) bool:
byte northward, check, d;
char cur;
bool ok;
due north := 0;
check := 0;
ok := truthful;
while
cur := isbn*;
isbn := isbn + i;
ok and cur ~= '\e'
practise
if north=3 then
if cur ~= '-' then ok := fake fi
elif cur<'0' or cur>'9' and then
ok := false
else
d := cur - '0';
if n=1 or (n>3 and north&one = 0) and so
d := d * 3;
fi;
check := check + d
fi;
northward := north + ane
od;
ok and n = 14 and bank check%10 = 0
corpproc nonrec test(*char isbn) void:
writeln(isbn, ": ",
if isbn13_check(isbn) then "proficient" else "bad" fi)
corpproc nonrec main() void:
test("978-1734314502");
exam("978-1734314509");
test("978-1788399081");
exam("978-1788399083")
corp
978-1734314502: expert 978-1734314509: bad 978-1788399081: adept 978-1788399083: bad
Excel [edit]
LAMBDA [edit]
Binding the proper noun ISBN13Check to the post-obit lambda expression in the Name Director of the Excel WorkBook:
(See LAMBDA: The ultimate Excel worksheet function)
ISBN13Check
= LAMBDA (south,
Permit (
ns, FILTERP(
LAMBDA (5,
Not (ISERROR(five) )
)
) (
VALUE (CHARSROW(s) )
) ,
ixs, SEQUENCE(
one , COLUMNS(ns) ,
1 , 1
) ,0 = MOD(
SUM(
IF ( 0 <> Modern(ixs, ii ) ,
Alphabetize(ns, ixs) ,
three * Alphabetize(ns, ixs)
)
) ,
10
)
)
)
and also bold the post-obit generic bindings in the Name Manager for the WorkBook:
CHARSROW
= LAMBDA (s,
MID(s,
SEQUENCE( one , LEN(s) , one , i ) ,
1
)
)FILTERP
= LAMBDA (p,
LAMBDA (xs,
FILTER(xs, p(xs) )
)
)ISDIGIT
= LAMBDA (c,
LET (
ic, CODE(c) ,AND ( 47 < ic, 58 > ic)
)
)
fx | =ISBN13Check(A2) | ||
---|---|---|---|
A | B | ||
1 | Candidate string | ISBN13 checked | |
2 | 978-1734314502 | True | |
iii | 978-1734314509 | Faux | |
4 | 978-1788399081 | TRUE | |
5 | 978-1788399083 | FALSE |
Factor [edit]
USING: combinators.short-circuit formatting kernel math
math.functions math.parser math.vectors qw sequences
sequences.extras sets unicode ;: (isbn13?) ( str -- ? )
string>digits
[ <evens> sum ] [ <odds> 3 v*north sum + ] bi 10 divisor? ;: isbn13? ( str -- ? )
"- " without
{ [ length thirteen = ] [ [ digit? ] all? ] [ (isbn13?) ] } one&& ;qw{ 978-1734314502 978-1734314509 978-1788399081 978-1788399083 }
[ dup isbn13? "good" "bad" ? "%south: %s\n" printf ] each
978-1734314502: good 978-1734314509: bad 978-1788399081: skillful 978-1788399083: bad
Forth [edit]
The post-obit word non only identifies correct xiii digit ISBN (and EAN) codes, but also viii digit EAN and GTIN codes.
: is-digit [char] 0 - 10 u< ;: isbn? ( a n -- f)
1- chars over + 2>r 0 1 2r> ?do
dup i [electronic mail protected] dup is-digit \ get length and factor, setup loop
if [char] 0 - * rot + swap 3 * viii mod else drop drop then
-1 chars +loop driblet 10 modern 0= \ now calculate checksum
;
In Along, a "truthful" value is indicated past "-1".
s" 978-1734314502" isbn? . -1 ok s" 978-1734314509" isbn? . 0 ok southward" 978-1788399081" isbn? . -1 ok south" 978-1788399083" isbn? . 0 ok
Fortran [edit]
program isbn13
implicit nonecharacter ( len = xiv ), dimension ( 4 ), parameter :: isbns = [ "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" ]
integer :: ipractise i = i, ubound (isbns, i )
if (check_isbn13(isbns(i) ) ) so
impress*, isbns(i), " : ", "good"
else
print*, isbns(i), " : ", "bad"
end if
end do
contains
pure function check_isbn13(isbn)
character ( len =* ), intent ( in ) :: isbn
logical :: check_isbn13
integer :: summ, counter, i, digitcheck_isbn13 = .imitation.
counter = 0
summ = 0exercise i = one, len (isbn)
if (isbn(i:i) == ' ' .or. isbn(i:i) == '-' ) cycle
counter = counter + ane
read(isbn(i:i), '(I1)' ) digit
if ( modulo (counter, 2 ) == 0 ) then
summ = summ + 3 *digit
else
summ = summ + digit
end if
terminate do
if (counter == xiii .and. modulo (summ, 10 ) == 0 ) check_isbn13 = .true.
end function check_isbn13
finish program isbn13
978-1734314502 : skilful 978-1734314509 : bad 978-1788399081 : good 978-1788399083 : bad
FreeBASIC [edit]
#define ZEROC asc("0")function is_num( byval c as string ) as boolean
if asc (c) >= ZEROC andalso asc (c)<ZEROC+10 and then return true
return false
terminate functionfunction is_good_isbn( isbn as cord ) as boolean
dim equally uinteger charno = 0, digitno = 0, sum = 0
dim equally string*ane currchar
while charno <= len (isbn)
currchar = mid (isbn,charno,1 )
if is_num(currchar) then
if digitno modernistic 2 = i then
sum += two*( asc (currchar)-ZEROC)
terminate if
sum += asc (currchar)-ZEROC
digitno += 1
stop if
charno += 1
wend
if sum mod 10 = 0 then
render true
else
return fake
terminate if
end functiondim as cord isbns( 0 to 3 ) = { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" }
dim as uinteger i
for i = 0 to 3
if is_good_isbn( isbns(i) ) so
impress isbns(i)+": adept"
else
impress isbns(i)+": bad"
end if
adjacent i
978-1734314502: practiced 978-1734314509: bad 978-1788399081: good 978-1788399083: bad
F# [edit]
// ISBN13 Check Digit
open Systemallow parseInput (input: string ) =
Seq.map ( fun c -> c |> string ) input |> Seq.toList |> Listing.map ( fun 10 -> Int32.Parse x)[ <EntryPoint> ]
let main argv =
permit isbnnum = parseInput ( Cord.filter ( fun 10 -> x <> '-' ) argv.[ 0 ] )
// Multiply every other digit past 3
permit everyOther = List.mapi ( fun i x -> if i % 2 = 0 and so 10 * 3 else 10) isbnnum
// Sum the *3 list with the original list
allow sum = List.sum everyOther + List.sum isbnnum
// If the remainder of sum / ten is 0 then it's a valid ISBN13
if sum % 10 = 0 and then
printfn "%s Valid ISBN13" argv.[ 0 ]
else
printfn "%s Invalid ISBN13" argv.[ 0 ]
0
978-1734314502 Valid ISBN13 978-1734314509 Inalid ISBN13 978-1788399081 Valid ISBN13 978-1788399083 Inalid ISBN13
Fōrmulæ [edit]
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures only non text. Moreover, in that location can be multiple visual representations of the same plan. Even though information technology is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than than visualization and edition.
Programs in Fōrmulæ are created/edited online in its website, Nevertheless they run on execution servers. By default remote servers are used, merely they are limited in memory and processing power, since they are intended for demonstration and coincidental use. A local server can be downloaded and installed, it has no limitations (it runs in your own reckoner). Because of that, example programs tin exist fully visualized and edited, simply some of them will non run if they require a moderate or heavy computation/memory resource, and no local server is being used.
In this page you lot can come across the program(s) related to this task and their results.
Go [edit]
packet mainimport (
"fmt"
"strings"
"unicode/utf8"
)func checkIsbn13(isbn string ) bool {
// remove whatever hyphens or spaces
isbn = strings. ReplaceAll (strings. ReplaceAll (isbn, "-" , "" ), " " , "" )
// check length == 13
le := utf8.RuneCountInString(isbn)
if le != 13 {
return simulated
}
// bank check only contains digits and calculate weighted sum
sum := int32 ( 0 )
for i , c := range isbn {
if c < '0' || c > 'ix' {
return false
}
if i % 2 == 0 {
sum += c - '0'
} else {
sum += three * (c - '0' )
}
}
return sum% 10 == 0
}func main() {
isbns := [] string { "978-1734314502" , "978-1734314509" , "978-1788399081" , "978-1788399083" }
for _, isbn := range isbns {
res := "bad"
if checkIsbn13(isbn) {
res = "good"
}
fmt. Printf ( "%s: %south\due north" , isbn, res)
}
}
978-1734314502: good 978-1734314509: bad 978-1788399081: good 978-1788399083: bad
Haskell [edit]
import Data. Char (digitToInt, isDigit)
import Text.Printf (printf)pair :: Num a => [a] -> [ (a, a) ]
pair [ ] = [ ]
pair xs = p ( have 2 xs) : pair ( driblet two xs)
where
p ps = case ps of
(x : y : zs) -> (x, y)
(x : zs) -> (x, 0 )validIsbn13 :: String -> Bool
validIsbn13 isbn
| length (digits isbn) /= xiii = Fake
| otherwise = calc isbn `rem` x == 0
where
digits = map digitToInt . filter isDigit
calc = sum . map (\(ten, y) -> x + y * 3 ) . pair . digitschief :: IO ( )
main =
mapM_
(printf "%south: Valid: %s\n" <*> ( show . validIsbn13) )
[ "978-1734314502" ,
"978-1734314509" ,
"978-1788399081" ,
"978-1788399083"
]
978-1734314502: Valid: True 978-1734314509: Valid: Fake 978-1788399081: Valid: True 978-1788399083: Valid: Simulated
Or, expressed in terms of cycle:
import Data. Char (digitToInt, isDigit)isISBN13 :: String -> Bool
isISBN13 =
( 0 == )
. flip rem x
. sum
. flip
( zipWith ( ( * ) . digitToInt) . filter isDigit)
( wheel [ i , 3 ] )main :: IO ( )
main =
mapM_
( print . ( ( , ) <*> isISBN13) )
[ "978-1734314502" ,
"978-1734314509" ,
"978-1788399081" ,
"978-1788399083"
]
("978-1734314502",True) ("978-1734314509",Faux) ("978-1788399081",Truthful) ("978-1788399083",False)
IS-BASIC [edit]
100 PROGRAM "ISBN13.bas"
110 DO
120 Print :INPUT PROMPT "ISBN-13 code: ":IS$
130 IF IS$="" THEN Go out DO
140 IF ISBN(IS$) THEN
150 Impress "Ok."
160 ELSE
170 Print "CRC error."
180 Finish IF
190 LOOP
200 DEF TRIM$(Due south$)
210 Permit T$=""
220 FOR I=i TO LEN(S$)
230 IF S$(I)>CHR$(47) AND S$(I)<CHR$(58) So LET T$=T$&S$(I)
240 Adjacent
250 Allow TRIM$=T$
260 END DEF
270 DEF ISBN(S$)
280 LET SUM,ISBN=0:Let ISBN$=TRIM$(IS$)
290 IF LEN(ISBN$)<>13 Then PRINT "Invalid length.":Get out DEF
300 FOR I=1 TO 11 STEP ii
310 Permit SUM=SUM+VAL(ISBN$(I))+VAL(ISBN$(I+1))*iii
320 NEXT
330 LET SUM=SUM+VAL(ISBN$(13))
340 IF Mod(SUM,ten)=0 Then LET ISBN=-one
350 END DEF
J [edit]
D =: '0123456789'isbn13c =: D&([ [email protected]:i. clean)
check =: 0 = 10 | lc
lc =: [ +/@:* weight
weight =: i iii $~ #
make clean =: ] -. a. -. [
isbn13c;._1 ' 978-1734314502 978-1734314509 978-1788399081 978-1788399083'
1 0 i 0
Java [edit]
public static void primary( ) {
System.out.println (isISBN13( "978-1734314502" ) ) ;
Arrangement.out.println (isISBN13( "978-1734314509" ) ) ;
Organisation.out.println (isISBN13( "978-1788399081" ) ) ;
System.out.println (isISBN13( "978-1788399083" ) ) ;
}
public static boolean isISBN13( Cord in) {
int pre = Integer.parseInt (in.substring ( 0,3 ) ) ;
if (pre!= 978 ) return faux ;
Cord postStr = in.substring ( 4 ) ;
if (postStr.length ( ) != 10 ) render false ;
int mail = Integer.parseInt (postStr) ;
int sum = 38 ;
for ( int x = 0 ; x< 10 ;x+= 2 )
sum += (postStr.charAt (x) - 48 ) * 3 + ( (postStr.charAt (10+ 1 ) - 48 ) ) ;
if (sum%10== 0 ) return truthful ;
return false ;
}
true false true false
jq [edit]
Works with gojq, the Go implementation of jq
def isbn_check:
def digits: tostring | explode | map( select(. >= 48 and . <= 57) | [.] | implode | tonumber);
def sum(south): reduce s every bit $x (zip; . + $x);
digits
| . as $digits
| sum(range(0;length;2) | $digits[.]) as $one
| (iii * sum(range(1;length;2) | $digits[.])) equally $2
| (($one+$two) % ten) == 0;def testingcodes:
["978-1734314502", "978-1734314509",
"978-1788399081", "978-1788399083"];testingcodes[]
| "\(.): \(if isbn_check and so "good" else "bad" end)"
978-1734314502: good 978-1734314509: bad 978-1788399081: proficient 978-1788399083: bad
Julia [edit]
part isbncheck(str)
render sum(iseven(i) ? 3 * parse(Int, ch) : parse(Int, ch)
for (i, ch) in enumerate(replace(str, r"\D" => ""))) % ten == 0
stopconst testingcodes = ["978-1734314502", "978-1734314509",
"978-1788399081", "978-1788399083"]for lawmaking in testingcodes
println(code, ": ", isbncheck(code) ? "good" : "bad")
finish
978-1734314502: expert 978-1734314509: bad 978-1788399081: good 978-1788399083: bad
Kotlin [edit]
fun isValidISBN13(text: Cord): Boolean {
val isbn = text.supersede(Regex("[- ]"), "")
return isbn.length == thirteen && isbn.map { information technology - '0' }
.mapIndexed { index, value -> when (index % 2) { 0 -> value else -> 3 * value } }
.sum() % x == 0
}
Tested using Spek
describe("ISBN Utilities") {
mapOf(
"978-1734314502" to true,
"978-1734314509" to simulated,
"978-1788399081" to true,
"978-1788399083" to simulated
).forEach { (input, expected) ->
it("returns $expected for $input") {
println("$input: ${when(isValidISBN13(input)) {
true -> "expert"
else -> "bad"
}}")
assert(isValidISBN13(input) == expected)
}
}
}
978-1734314502: proficient 978-1734314509: bad 978-1788399081: good 978-1788399083: bad
langur [edit]
In this example, nosotros map to multiple functions (actually 1 no-op).
val .isbn13checkdigit = f(var .s) {
.southward = supplant(.s, RE/[\- ]/)
matching(re/^[0-9]{13}$/, .s) and
fold(f{+}, map [_, f{x iii}], s2n .due south) div 10
}val .tests = h{
"978-1734314502": true,
"978-1734314509": false,
"978-1788399081": truthful,
"978-1788399083": false,
}for .key of .tests {
val .pass = .isbn13checkdigit(.key)
write .central, ": ", if(.laissez passer: "adept"; "bad")
writeln if(.pass == .tests[.key]: ""; " (ISBN-13 CHECK DIGIT Examination FAILED)")
}
In this case, we set a for loop value every bit it progresses.
val .isbn13checkdigit = f(var .due south) {
.s = supercede(.s, RE/[\- ]/)
var .alt = true
matching(re/^[0-9]{13}$/, .s) and
for[=0] .d in s2n(.s) { _for += if(non= .alt: .d 10 3; .d) } div x
}val .tests = h{
"978-1734314502": true,
"978-1734314509": false,
"978-1788399081": true,
"978-1788399083": false,
}for .key of .tests {
val .pass = .isbn13checkdigit(.central)
write .key, ": ", if(.laissez passer: "good"; "bad")
writeln if(.pass == .tests[.key]: ""; " (ISBN-13 CHECK DIGIT Examination FAILED)")
}
978-1734314502: good 978-1734314509: bad 978-1788399081: skillful 978-1788399083: bad
Lua [edit]
function checkIsbn13(isbn)
local count = 0
local sum = 0
for c in isbn:gmatch"." do
if c == ' ' or c == '-' so
-- skip
elseif c < '0' or '9' < c and then
return false
else
local digit = c - '0'
if (count % two ) > 0 and then
sum = sum + 3 * digit
else
sum = sum + digit
end
count = count + ane
end
endif count ~= 13 then
return false
end
render (sum % 10 ) == 0
endfunction exam(isbn)
if checkIsbn13(isbn) so
print (isbn .. ": good" )
else
print (isbn .. ": bad" )
end
finishpart primary( )
test( "978-1734314502" )
test( "978-1734314509" )
exam( "978-1788399081" )
test( "978-1788399083" )
endmain( )
978-1734314502: expert 978-1734314509: bad 978-1788399081: skilful 978-1788399083: bad
Mathematica / Wolfram Language [edit]
ClearAll[ValidISBNQ]
ValidISBNQ[iban_String] := Module[{i},
i = StringReplace[iban, {" " -> "", "-" -> ""}];
If[StringMatchQ[i, Repeated[DigitCharacter]],
i = ToExpression /@ Characters[i];
i[[2 ;; ;; 2]] *= 3;
Modern[Full[i], x] == 0
,
Fake
]
]
ValidISBNQ["978-1734314502"]
ValidISBNQ["978-1734314509"]
ValidISBNQ["978-1788399081"]
ValidISBNQ["978-1788399083"]
True False True Faux
Modula-two [edit]
MODULE ISBN;
FROM InOut IMPORT WriteString, WriteLn;
FROM Strings IMPORT Length;Process validISBN(southward: Assortment OF CHAR ) : BOOLEAN;
VAR total, i, length: CARDINAL;
BEGIN
total := 0;
length := Length(s);
IF (length # fourteen ) OR (s[ three ] # '-' ) THEN
RETURN False;
Finish;
FOR i := 0 TO length- 1 DO
IF i # 3 And then
IF (south[i] < '0' ) OR (s[i] > '9' ) THEN
RETURN FALSE;
ELSIF (i < 3 ) AND (i Mod 2 = 1 ) OR (i > 3 ) AND (i Modern 2 = 0 ) THEN
total := total + three * ( ORD (due south[i] ) - ORD ( '0' ) );
ELSE
full := total + ORD (s[i] ) - ORD ( '0' );
Stop;
END;
END;
RETURN total MOD x = 0;
END validISBN;PROCEDURE check(s: ARRAY OF CHAR );
BEGIN
WriteString(due south);
WriteString( ': ' );
IF validISBN(southward) And then
WriteString( 'expert' );
ELSE
WriteString( 'bad' );
END;
WriteLn;
End check;BEGIN
check( '978-1734314502' );
check( '978-1734314509' );
check( '978-1788399081' );
check( '978-1788399083' );
Terminate ISBN.
978-1734314502: expert 978-1734314509: bad 978-1788399081: practiced 978-1788399083: bad
Nanoquery [edit]
def checkIsbn13(isbn)
// remove any hyphens or spaces
isbn = str(isbn).replace("-","").supervene upon(" ","")// check length = 13
if len(isbn) != 13
return fake
stop// bank check only contains digits and summate weighted sum
sum = 0
for i in range(0, len(isbn) - 1)
c = isbn[i]
if (ord(c) < ord("0")) or (ord(c) > ord("9"))
render false
stopif (i % ii) = 0
sum += ord(c) - ord("0")
else
sum += iii * (ord(c) - ord("0"))
terminate
endreturn (sum % 10) = 0
ceaseisbns = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"}
for isbn in isbns
res = "bad"
if checkIsbn13(isbn)
res = "good"
endprint format("%s: %s\n", isbn, res)
end
978-1734314502: good 978-1734314509: bad 978-1788399081: good 978-1788399083: bad
Nim [edit]
import strutils, strformatfunc is_isbn*(southward: string): bool =
var sum, len: int
for c in due south:
if is_digit(c):
sum += (ord(c) - ord('0')) * (if len mod ii == 0: i else: 3)
len += 1
elif c != ' ' and c != '-':
return simulated
return (len == xiii) and (sum modern 10 == 0)when is_main_module:
let isbns = [ "978-1734314502", "978-1734314509",
"978-1788399081", "978-1788399083" ]
for isbn in isbns:
var quality: string = if is_isbn(isbn): "expert" else: "bad"
echo &"{isbn}: {quality}"
978-1734314502: good 978-1734314509: bad 978-1788399081: good 978-1788399083: bad
Pascal [edit]
plan ISBNChecksum(output) ;const
codeIndexMaximum = 17 ;
ISBNIndexMinimum = 1 ;
ISBNIndexMaximum = thirteen ;
ISBNIndexRange = ISBNIndexMaximum - ISBNIndexMinimum + 1 ;type
code = string (codeIndexMaximum) ;
codeIndex = 1 .. codeIndexMaximum value 1 ;
decimalDigit = '0' .. '9' ;
decimalValue = 0 .. 9 ;
ISBNIndex = ISBNIndexMinimum.. ISBNIndexMaximum ;
ISBN = array [ISBNIndex] of decimalDigit;{ returns the integer value represented by a character }
function numericValue( protected c: decimalDigit) : decimalValue;
begin
{ in Pascal result variable bears the same name as the role }
numericValue : = ord (c) - ord ( '0' )
end ;{ determines whether an ISBN is technically valid (checksum correct) }
function isValidISBN( protected n: ISBN) : Boolean ;
var
sum: 0 .. 225 value 0 ;
i: ISBNIndex;
begin
{ NB: in Pascal for-loop-limits are _inclusive_ }
for i : = ISBNIndexMinimum to ISBNIndexMaximum exercise
begin
{ alternate scale factor 3^0, 3^ane based on Boolean }
sum : = sum + numericValue(n[i] ) * 3 pow ord ( not odd (i) )
terminate ;isValidISBN : = sum mod ten = 0
end ;{ transform '978-0-387-97649-5' into '9780387976495' }
function digits(northward: code) : lawmaking;
var
sourceIndex, destinationIndex: codeIndex;
begin
for sourceIndex : = 1 to length(north) do
begin
if due north[sourceIndex] in [ '0' .. '9' ] and then
begin
northward[destinationIndex] : = n[sourceIndex] ;
destinationIndex : = destinationIndex + one
end
stop ;{ to change a cord'south length you need overwrite it completely }
digits : = subStr(n, one , destinationIndex - 1 )
terminate ;{ information blazon compulsion }
function asISBN( protected n: code) : ISBN;
var
result: ISBN;
brainstorm
unpack(n[ 1 .. length (n) ] , consequence, 1 ) ;
asISBN : = consequence
end ;{ tells whether a cord value contains a proper ISBN representation }
role isValidISBNString( protected hyphenatedForm: code) : Boolean ;
var
digitOnlyForm: code;
brainstorm
digitOnlyForm : = digits(hyphenatedForm) ;
{ The Extended Pascal `and_then` Boolean operator allows us }
{ to kickoff check the length before invoking `isValidISBN`. }
isValidISBNString : = (length(digitOnlyForm) = ISBNIndexRange)
and_then isValidISBN(asISBN(digitOnlyForm) )
stop ;{ === MAIN ============================================================= }
begin
writeLn (isValidISBNString( '978-1734314502' ) ) ;
writeLn (isValidISBNString( '978-1734314509' ) ) ;
writeLn (isValidISBNString( '978-1788399081' ) ) ;
writeLn (isValidISBNString( '978-1788399083' ) )
finish .
True Imitation True False
Perl [edit]
use strict;
utilise warnings;
use feature 'say' ;sub check_digit {
my ( $isbn ) = @_ ; my ( $sum ) ;
$sum += ( 1 , 3 ) [ $_ %2] * ( split '' , join '' , split /\D/ , $isbn ) [ $_ ] for 0 .. 11 ;
( 10 - $sum % 10 ) % 10 ;
}for ( < 978 - 1734314502 978 - 1734314509 978 - 1788399081 978 - 1788399083 978 - ii - 74839 - 908 - 0 978 - 2 - 74839 - 908 - 5 > ) {
my ( $isbn , $check ) = /(.*)(.)/ ;
my $check_d = check_digit( $isbn ) ;
say "$_ : " . ( $cheque == $check_d ? 'Expert' : "Bad check-digit $check; should be $check_d" )
}
978-1734314502 : Practiced 978-1734314509 : Bad cheque-digit ix; should be 2 978-1788399081 : Good 978-1788399083 : Bad bank check-digit three; should be 1 978-ii-74839-908-0 : Good 978-2-74839-908-5 : Bad check-digit five; should be 0
Phix [edit]
with javascript_semantics procedure check_isbn13 ( cord isbn ) integer digits = 0 , checksum = 0 , due west = 1 for i = 1 to length ( isbn ) practise integer ch = isbn [ i ] if ch != ' ' and ch != '-' then ch -= '0' if ch < 0 or ch > 9 so checksum = 9 exit end if checksum += ch * w digits += 1 westward = 4 - w end if end for checksum = balance ( checksum , 10 ) string gb = iff ( digits = thirteen and checksum = 0 ? "skilful" : "bad" ) printf ( ane , "%s: %s\n" ,{ isbn , gb }) end procedure constant isbns = { "978-1734314502" , "978-1734314509" , "978-1788399081" , "978-1788399083" , "978-ii-74839-908-0" , "978-2-74839-908-v" , "978 one 86197 876 9" } for i = 1 to length ( isbns ) exercise check_isbn13 ( isbns [ i ]) cease for
978-1734314502: adept 978-1734314509: bad 978-1788399081: good 978-1788399083: bad 978-2-74839-908-0: skilful 978-2-74839-908-v: bad 978 one 86197 876 9: practiced
PicoLisp [edit]
(de isbn13? (Due south)
(let L
(make
(for N (chop S)
(and (format Due north) (link @)) ) )
(and
(= 13 (length Fifty))
(=0 (% (sum * L (circ 1 3)) 10)) ) ) )
(mapc
'((A)
(tab
(-19 1)
A
(if (isbn13? A) 'ok 'fail) ) )
(quote
"978-1734314502"
"978-1734314509"
"978-1-86197-876-9"
"978-2-74839-908-five"
"978 1 86197 876 9" ) )
978-1734314502 ok 978-1734314509 fail 978-1-86197-876-9 ok 978-2-74839-908-5 fail 978 1 86197 876 9 ok
PL/1000 [edit]
100H:Bank check$ISBN13: PROCEDURE (PTR) BYTE;
DECLARE PTR ADDRESS, ISBN BASED PTR BYTE;
DECLARE (I, F, T) BYTE;
F = 1;
T = 0;
Do I = 0 TO thirteen;
IF I = 3 So DO;
/* THIRD CHAR SHOULD Exist '-' */
IF ISBN(I) <> '-' THEN Render 0;
END;
ELSE Exercise;
/* DIGITS MUST Exist VALID */
IF ISBN(I) < '0' OR ISBN(I) > '9' Then Render 0;
T = T + (ISBN(I) - '0') * F;
F = four - F; /* MULTIPLY Past i AND 3 ALTERNATELY */
END;
END;
Return (T MOD 10) = 0;
END CHECK$ISBN13;/* CP/M BDOS CALL */
BDOS: PROCEDURE (FUNC, ARG);
DECLARE FUNC BYTE, ARG ADDRESS;
Become TO 5;
END BDOS;PRINT: Procedure (STR);
DECLARE STR Address;
Phone call BDOS(ix, STR);
END Print;/* TESTS */
DECLARE Exam (4) ADDRESS;
TEST(0) = .'978-1734314502$';
TEST(1) = .'978-1734314509$';
TEST(ii) = .'978-1788399081$';
Examination(three) = .'978-1788399083$';DECLARE I BYTE;
Practise I = 0 TO LAST(TEST);
Call Impress(TEST(I));
Telephone call Print(.': $');
IF CHECK$ISBN13(Test(I)) THEN
Call PRINT(.'Practiced$');
ELSE
Phone call PRINT(.'BAD$');
Telephone call Impress(.(13,10,'$'));
END;Phone call BDOS(0,0);
EOF
978-1734314502: GOOD 978-1734314509: BAD 978-1788399081: Expert 978-1788399083: BAD
PowerShell [edit]
part Get-ISBN13 {
$codes = (
"978-1734314502" ,
"978-1734314509" ,
"978-1788399081" ,
"978-1788399083"
)foreach ( $line in $codes ) {
$sum = $null
$codeNoDash = $line.Replace( "-" , "" )for ( $i = 0; $i -lt $codeNoDash.length; $i ++ ) {
if ( ( $i % 2 ) -eq one ) {
$sum += [ decimal ] $codeNoDash [ $i ] * three
} else {
$sum += [ decimal ] $codeNoDash [ $i ]
}
}if ( ( $sum % 10 ) -eq 0 ) {
Write-Host "$line Good"
} else {
Write-Host "$line Bad"
}
}
}
Get-ISBN13
978-1734314502 Good 978-1734314509 Bad 978-1788399081 Practiced 978-1788399083 Bad
PureBasic [edit]
Macro TestISBN13(Ten)
Print (Ten)
If IsISBN13(X) : PrintN ( " good" ) : Else : PrintN ( " bad" ) : EndIf
EndMacroProcedure.b IsISBN13(ISBN13.s)
ISBN13= Left (ISBN13,3 ) + Mid (ISBN13,v )
If IsNAN( Val (ISBN13) ) Or Len (ISBN13) <> 13 : ProcedureReturn #False : EndIf
Dim ISBN.due south{ i } ( 12 ) : PokeS (@ISBN( ),ISBN13)
For i= 0 To eleven Step 2 : sum+ Val (ISBN(i) ) + Val (ISBN(i+ 1 ) ) * 3 : Next
sum+ Val (ISBN( 12 ) )
ProcedureReturn Bool(sum%10= 0 )
EndProcedureIf OpenConsole ( )
TestISBN13( "978-1734314502" )
TestISBN13( "978-1734314509" )
TestISBN13( "978-1788399081" )
TestISBN13( "978-1788399083" )
Input ( )
EndIf
978-1734314502 skillful 978-1734314509 bad 978-1788399081 skillful 978-1788399083 bad
Python [edit]
def is_isbn13(north):
n = due north.replace ( '-' , '' ).supercede ( ' ' , '' )
if len (n) != 13:
return Imitation
production = ( sum ( int (ch) for ch in n[::2 ] )
+ sum ( int (ch) * three for ch in n[ 1::2 ] ) )
return product % ten == 0if __name__ == '__main__':
tests = '''
978-1734314502
978-1734314509
978-1788399081
978-1788399083'''.strip ( ).dissever ( )
for t in tests:
print (f"ISBN13 {t} validates {is_isbn13(t)}" )
ISBN13 978-1734314502 validates True ISBN13 978-1734314509 validates False ISBN13 978-1788399081 validates True ISBN13 978-1788399083 validates Imitation
Or, expressed in terms of itertools.cycle
'''ISBN13 check digit'''from itertools import cycle
# isISBN13 :: String -> Bool
def isISBN13(s):
'''True if s is a valid ISBN13 cord
'''
digits = [ int (c) for c in s if c.isdigit ( ) ]
return 13 == len (digits) and (
0 == sum ( map (
lambda f, x: f(x) ,
cycle( [
lambda 10: 10,
lambda x: iii * x
] ) ,
digits
) ) % 10
)# ------------------------- Exam -------------------------
# main :: IO ()
def main( ):
'''Exam strings for ISBN-13 validity.'''print ( '\n'.bring together (
repr ( (south, isISBN13(s) ) ) for southward
in [ "978-1734314502" ,
"978-1734314509" ,
"978-1788399081" ,
"978-1788399083"
]
) )# MAIN ---
if __name__ == '__main__':
primary( )
('978-1734314502', True) ('978-1734314509', False) ('978-1788399081', True) ('978-1788399083', Imitation)
Quackery [edit]
[ char 0 char 9 1+ within ] is digit? ( c --> b )[ 1 & ] is odd? ( n --> b )
[ [] bandy ]'[ swap
witheach [
dup nested
unrot over do
iff [ dip join ]
else nip
] driblet ] is filter ( [ --> [ )[ 0 swap
witheach [
char->n i^ odd?
iff [ 3 * + ]
else +
] ] is checksum ( $ --> due north )[ filter digit?
dup size thirteen = not
iff [ drib simulated ] done
checksum x mod 0 = ] is isbn ( $ --> b )[ dup repeat$ say ": " isbn
iff [ say "Good" ]
else [ say "Bad" ] cr ] is isbn-test ( $ --> )$ '978-1734314502' isbn-exam
$ '978-1734314509' isbn-examination
$ '978-1788399081' isbn-test
$ '978-1788399083' isbn-exam
978-1734314502: Good 978-1734314509: Bad 978-1788399081: Practiced 978-1788399083: Bad
Racket [edit]
#lang racket/base of operations(ascertain (isbn13-bank check-digit-valid? s)
(nil? (modulo (for/sum ((i (in-naturals))
(d (regexp-supervene upon* #px"[^[:digit:]]" s "")))
(* (- (char->integer d) (char->integer #\0))
(if (fifty-fifty? i) one iii)))
x)))(module+ test
(require rackunit)
(check-truthful (isbn13-cheque-digit-valid? "978-1734314502"))
(check-false (isbn13-check-digit-valid? "978-1734314509"))
(bank check-true (isbn13-bank check-digit-valid? "978-1788399081"))
(check-fake (isbn13-bank check-digit-valid? "978-1788399083")))
no output indicates tests pass
Raku [edit]
(formerly Perl 6)
Also exam a value that has a nil check digit.
sub check-digit ( $isbn ) {
( 10 - (sum ( | $isbn . comb ( /<[0..9]>/ ) ) »*» ( 1 , 3 ) ) % 10 ) . substr : *- 1
}{
my $check = . substr ( *- 1 ) ;
my $check -digit = check-digit . chop ;
say "$_ : " , $check == $bank check -digit ??
'Proficient' !!
"Bad cheque-digit $bank check; should exist $check-digit"
} for words <
978 - 1734314502
978 - 1734314509
978 - 1788399081
978 - 1788399083
978 - 2 - 74839 - 908 - 0
978 - ii - 74839 - 908 - 5
>;
978-1734314502 : Good 978-1734314509 : Bad check-digit nine; should exist two 978-1788399081 : Good 978-1788399083 : Bad bank check-digit 3; should be ane 978-2-74839-908-0 : Skillful 978-2-74839-908-5 : Bad cheque-digit five; should be 0
Cherry-red [edit]
check_valid_isbn13: function [str] [
is_digit: charset [#"0" - #"9"]
remove-each i str [not choice is_digit i] ; remove non-digitseither 13 = length? str [ ; reject strings of incorrect length
sum: 0
echo i 13 [
mul: either even? i [3] [ane] ; multiplier for odd/even digits
sum: sum + (mul * to integer! to string! pick str i)
]zero? (sum % ten) ; bank check if remainder mod 10 is zero
] [
faux
]
]; bank check given examples
foreach [str] ["978-1734314502" "978-1734314509" "978-1788399081" "978-1788399083"] [
prin str
prin " - "
impress check_valid_isbn13 str
]
978-1734314502 - true 978-1734314509 - simulated 978-1788399081 - true 978-1788399083 - imitation
REXX [edit]
A couple of additional checks were fabricated to verify a correct length, and also that the ISBN-xiii code is all numerics (with optional minus signs).
/*REXX pgm validates the cheque digit of an ISBN─13 lawmaking (it may have embedded minuses).*/
parse arg $ /*obtain optional arguments from the CL*/
if $='' | if $="," then $= '978-1734314502 978-1734314509 978-1788399081 978-1788399083'
@ISBN= "ISBN─13 code isn't" /*a literal used when displaying msgs. */
/* [↓] remove all minuses from X code.*/
do j=ane for words ($); y= word ($,j) /*obtain an ISBN─13 code from $ listing.*/
x= space ( translate (y, , '-' ), 0 ) /*remove all minus signs from the code.*/
L= length (ten) /*obtain the length of the ISBN-thirteen code*/
if L \== 13 then exercise; say @ISBN '13 characters: ' 10; exit 13; end
if verify (10, 9876543210 ) \==0 then do; say @ISBN 'numeric: ' x; exit ten; stop
sum= 0
do k=i for L; #= substr (x, k, i ) /*go a decimal digit from the X code. */
if \ (m// 2 ) then #= # * 3 /*multiply every other digit by three. */
sum= sum + # /*add the digit (or product) to the SUM*/
stop /*grand*/if right (sum, 1 )==0 so say ' ISBN-thirteen code ' ten " is valid."
else say ' ISBN-thirteen code ' x " isn't valid."
finish /*j*/ /*stick a fork in information technology, nosotros're all washed. */
- output when using the four default inputs:
ISBN-13 lawmaking 9781734314502 is valid. ISBN-xiii lawmaking 9781734314509 isn't valid. ISBN-13 lawmaking 9781788399081 is valid. ISBN-13 code 9781788399083 isn't valid.
Ring [edit]
load "stdlib.band"isbn = ["978-1734314502","978-1734314509", "978-1788399081", "978-1788399083","978-2-74839-908-0","978-2-74839-908-five","978 1 86197 876 9"]
for northward = ane to len(isbn)
sum = 0
isbnStr = isbn[n]
isbnStr = substr(isbnStr,"-","")
isbnStr = substr(isbnStr," ","")
for m = 1 to len(isbnStr)
if m%two = 0
num = 3*number(substr(isbnStr,m,1))
sum = sum + num
else
num = number(substr(isbnStr,m,one))
sum = sum + num
ok
next
if sum%x = 0
see "" + isbn[northward] + ": truthful" + nl
else
run into "" + isbn[n] + ": bad" + nl
ok
next
Output:
978-1734314502: truthful 978-1734314509: bad 978-1788399081: truthful 978-1788399083: bad 978-two-74839-908-0: true 978-2-74839-908-5: bad 978 1 86197 876 ix: truthful
Ruby [edit]
def validISBN13?(str)
cleaned = str.delete ( "^0-ix" ).chars
return imitation unless cleaned.size == 13
cleaned.each_slice ( ii ).sum { |d1, d2| d1.to_i + 3 *d2.to_i }.remainder ( x ) == 0
ceaseisbns = [ "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" ]
isbns.each { |isbn| puts "#{isbn}: #{validISBN13?(isbn)}" }
978-1734314502: true 978-1734314509: fake 978-1788399081: true 978-1788399083: false
Rust [edit]
fn main() {
permit isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"];
isbns.iter().for_each(|isbn| println!("{}: {}", isbn, check_isbn(isbn)));
}fn check_isbn(isbn: &str) -> bool {
if isbn.chars().filter(|c| c.is_digit(10)).count() != thirteen {
return simulated;
}
let checksum = isbn.chars().filter_map(|c| c.to_digit(10))
.zip([i, three].iter().cycle())
.fold(0, |acc, (val, fac)| acc + val * fac);
checksum % 10 == 0
}
978-1734314502: true 978-1734314509: false 978-1788399081: true 978-1788399083: fake
Seed7 [edit]
$ include "seed7_05.s7i";const func boolean: isISBN13 (in var string: input) is func
upshot
var boolean: isbn is Fake;
local
var char: c is ' ';
var integer: digit is 0;
var integer: i is i;
var integer: sum is 0;
begin
input := supervene upon(input, " ", "");
input := replace(input, "-", "");
if length(input) = xiii so
for c range input do
digit := ord(c) - 48;
if non odd(i) so
digit *:= 3;
stop if;
sum +:= digit;
incr(i);
finish for;
isbn := sum rem x = 0;
terminate if;
finish func;const proc: main is func
local
var string: str is "";
begin
for str range [] ("978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083") do
writeln(str <& ": " <& isISBN13(str));
end for;
stop func;
978-1734314502: TRUE 978-1734314509: False 978-1788399081: Truthful 978-1788399083: FALSE
Standard ML [edit]
local
fun check (c, p equally (1000, n)) =
if Char.isDigit c then
(non m, (if g and then 3 * (ord c - 48) else ord c - 48) + due north)
else
p
in
fun checkISBN south =
Int.rem (#2 (CharVector.foldl cheque (false, 0) s), 10) = 0
finishval test = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"]
val () = (print
o concat
o map (fn s => s ^ (if checkISBN s then ": good\north" else ": bad\due north"))) test
978-1734314502: proficient 978-1734314509: bad 978-1788399081: good 978-1788399083: bad
Swift [edit]
func checkISBN(isbn: String) -> Bool {
guard !isbn.isEmpty else {
render imitation
}let sum = isbn
.compactMap({ $0.wholeNumberValue })
.enumerated()
.map({ $0.start & 1 == 1 ? 3 * $0.element : $0.chemical element })
.reduce(0, +)return sum % x == 0
}let cases = [
"978-1734314502",
"978-1734314509",
"978-1788399081",
"978-1788399083"
]for isbn in cases {
impress("\(isbn) => \(checkISBN(isbn: isbn) ? "expert" : "bad")")
}
978-1734314502 => good 978-1734314509 => bad 978-1788399081 => skilful 978-1788399083 => bad
Tcl [edit]
proc validISBN13 code {
regsub -all {\D} $code "" code ; # remove non-digits
if { [ string length $lawmaking ] == 13 } {
set sum 0
set fac ane
foreach digit [ split $code "" ] {
set sum [ expr { $sum + $digit * $fac } ]
set fac [ expr { $fac == 1 ? three: 1 } ]
}
if { $sum % 10 == 0 } { render true}
}
render simulated
}
foreach test {
978-1734314502
978-1734314509
978-1788399081
978-1788399083
} { puts $exam:[validISBN13 $test ] }
978-1734314502:true 978-1734314509:simulated 978-1788399081:truthful 978-1788399083:fake
Simpler variant, using 2 loop vars and constant factors; same output:
proc validISBN13 lawmaking {
regsub -all {\D} $lawmaking "" code ; # remove non-digits
if { [ cord length $code ] == 13 } {
set sum 0
foreach {d1 d2} [ split $code "" ] {
if { $d2 eq "" } { set d2 0 } ; # final round
set sum [ expr { $sum + $d1 + $d2 * three } ]
}
if { $sum % 10 == 0 } { return truthful}
}
return false
}
uBasic/4tH [edit]
a := "978-1734314502"
Print Show(a), Show (Iif (Func(_IsISBN (a)), "skillful", "bad"))a := "978-1734314509"
Print Show(a), Show (Iif (Func(_IsISBN (a)), "adept", "bad"))a := "978-1788399081"
Print Bear witness(a), Testify (Iif (Func(_IsISBN (a)), "adept", "bad"))a := "978-1788399083"
Print Bear witness(a), Show (Iif (Func(_IsISBN (a)), "good", "bad"))Cease
_IsISBN
Param (1)
Local (four)[email protected] = 0 : [electronic mail protected] = 1 ' set sum and multiplier
For [electronic mail protected] = Len ([email protected]) - 1 To 0 Step -ane ' scan cord in reverse
[electronic mail protected] = Peek([email protected], [email protected]) - Ord ("0") ' get character
If (([email protected] < 0) + ([email protected] > nine)) = 0 Then [email protected] = [email protected] + ([email protected] * [electronic mail protected])
[email protected] = ([email protected] * 3) % 8 ' evaluate character, alter multiplier
NextReturn (([email protected] % 10) = 0) ' modulus 10 must exist zero
978-1734314502 good 978-1734314509 bad 978-1788399081 good 978-1788399083 bad 0 OK, 0:339
UNIX Shell [edit]
check_isbn13 () {
local i north t
n=${ane//[^0-nine]/}
t=0
for ((i=0; i<${#n}; ++i )); practice
(( t += ${n:i:1}*(1 + ((i&1)<<one)) ))
washed
(( 0 == t % ten ))
}for isbn in 978-1734314502 978-1734314509 978-1788399081 978-1788399083; do
printf '%southward: ' "$isbn"
if check_isbn13 "$isbn"; then
printf '%s\n' OK
else
printf '%s\n' 'NOT OK'
fi
done
978-1734314502: OK 978-1734314509: Not OK 978-1788399081: OK 978-1788399083: NOT OK
Visual Basic .Cyberspace [edit]
Module Module1Function CheckISBN13(code Every bit Cord ) As Boolean
lawmaking = code. Replace ( "-", "" ) . Supersede ( " ", "" )
If lawmaking. Length <> 13 Then
Return False
Terminate If
Dim sum = 0
For Each i_d In lawmaking. Select ( Function (digit, index) (index, digit) )
Dim index = i_d. index
Dim digit = i_d. digit
If Char . IsDigit (digit) And so
sum += ( Asc (digit) - Asc ( "0" ) ) * If (index Mod ii = 0, 1, 3 )
Else
Render False
Cease If
Next
Return sum Mod ten = 0
Terminate FunctionSub Master( )
Panel. WriteLine (CheckISBN13( "978-1734314502" ) )
Panel. WriteLine (CheckISBN13( "978-1734314509" ) )
Panel. WriteLine (CheckISBN13( "978-1788399081" ) )
Console. WriteLine (CheckISBN13( "978-1788399083" ) )
Cease SubFinish Module
True False Truthful False
Wren [edit]
var isbn13 = Fn. new { |s|
var cps = s. codePoints
var digits = [ ]
// extract digits
for (i in 0 ... cps . count ) {
var c = cps[i]
if (c >= 48 && c <= 57 ) digits. add (c)
}
// do calcs
var sum = 0
for (i in 0 ... digits . count ) {
var d = digits[i] - 48
sum = sum + ( (i% 2 == 0 ) ? d : 3 * d)
}
return sum % ten == 0
}var tests = [ "978-1734314502" , "978-1734314509" , "978-1788399081" , "978-1788399083" ]
for (test in tests) {
System. impress ( "%(exam) -> %(isbn13.call(test) ? "good" : "bad")" )
}
978-1734314502 -> good 978-1734314509 -> bad 978-1788399081 -> practiced 978-1788399083 -> bad
XPL0 [edit]
include xpllib; \contains StrLen functionproc ISBN13(Str); \Testify if International Standard Book Number is good
char Str;
int Sum, Cnt, Dig, I;
[Sum:= 0; Cnt:= 0;
for I:= 0 to StrLen(Str)-1 practise
[Dig:= Str(I) - ^0;
if Dig>=0 & Dig<=9 then
[Sum:= Sum + Dig;
Cnt:= Cnt + 1;
if (Cnt&1) = 0 then
Sum:= Sum + Dig + Dig;
];
];
Text(0, Str);
Text(0, if rem(Sum/x)=0 & Cnt=xiii then ": good" else ": bad");
CrLf(0);
];[ISBN13("978-1734314502");
ISBN13("978-1734314509");
ISBN13("978-1788399081");
ISBN13("978-1788399083");
ISBN13("978-one-59327-220-3");
ISBN13("978-178839918");
]
978-1734314502: proficient 978-1734314509: bad 978-1788399081: good 978-1788399083: bad 978-1-59327-220-3: practiced 978-178839918: bad
zkl [edit]
fcn ISBN13_check(isbn){ // "978-1734314502", throws on invalid digits
var [const] one3=("13"*6 + 1).split("").utilize("toInt"); // examine 13 digits
// one3=("13"*6) if you want to summate what the check digit should be
one3.zipWith('*,isbn - " -").sum(0) % ten == 0
}
isbns:=
#<<<"
978-1734314502
978-1734314509
978-1788399081
978-1788399083
978-2-74839-908-0
978-2-74839-908-5".split("\n");
#<<<
foreach isbn in (isbns)
{ println(isbn.strip()," ",ISBN13_check(isbn) and " Good" or " Bad") }
978-1734314502 Expert 978-1734314509 Bad 978-1788399081 Good 978-1788399083 Bad 978-2-74839-908-0 Expert 978-2-74839-908-5 Bad
Source: https://rosettacode.org/wiki/ISBN13_check_digit
Belum ada Komentar untuk "what is the excel formula to convert a ten digit isbn to the thirteen digit ean code?"
Posting Komentar