Mega Code Archive

 
Categories / Delphi / Algorithm Math
 

Check if an ISBN is valid

Title: Check if an ISBN is valid Question: Find out if a ISBN is valid... Answer: function ValidISBN(aISBN: string): boolean; var hNumber, hCheckDigit: string; hCheckValue, hCheckSum, Err: integer; i,Cnt: Word; begin Result := false; hCheckDigit := Copy(aISBN, Length(aISBN), 1); {Get rest of ISBN, minus check digit and its hyphen} hNumber := Copy(aISBN, 1, Length(aISBN) - 2); {Length of ISBN remainder must be 11 and check digit between 9 and 9 or X} if (Length(hNumber)=11)and(Pos(hCheckDigit, '0123456789X') 0) then begin {Get numeric value for check digit} if (hCheckDigit = 'X') then hCheckSum := 10 else Val(hCheckDigit, hCheckSum, Err); {Iterate through ISBN remainder, applying decode algorithm} Cnt := 1; for i := 1 to 12 do begin {Act only if current character is between "0" and "9" to exclude hyphens} if (Pos(hNumber[i], '0123456789') 0) then begin Val(hNumber[i], hCheckValue, Err); {Algorithm for each character in ISBN remainder, Cnt is the nth character so processed} hCheckSum := hCheckSum + hCheckValue * (11 - Cnt); Inc(Cnt); end; end; {Verify final value is evenly divisible by 11} if (hCheckSum mod 11 = 0) then Result := true else Result := false; end; end; This is how it works. A valid ISBN is: '0-672-31285-9'. Every digit is multiplied with the number of its position and than add up: 0*10 + 6*9 + 7*8 + 2* 7 etc. If the result is divisible trough 11 then the ISBN is valid!