Avatar of davearonson

davearonson's solution

to ISBN Verifier in the Elixir Track

Published at Jul 26 2019 · 0 comments
Instructions
Test suite
Solution

Note:

This exercise has changed since this solution was written.

The ISBN-10 verification process is used to validate book identification numbers. These normally contain dashes and look like: 3-598-21508-8

ISBN

The ISBN-10 format is 9 digits (0 to 9) plus one check character (either a digit or an X only). In the case the check character is an X, this represents the value '10'. These may be communicated with or without hyphens, and can be checked for their validity by the following formula:

(x1 * 10 + x2 * 9 + x3 * 8 + x4 * 7 + x5 * 6 + x6 * 5 + x7 * 4 + x8 * 3 + x9 * 2 + x10 * 1) mod 11 == 0

If the result is 0, then it is a valid ISBN-10, otherwise it is invalid.

Example

Let's take the ISBN-10 3-598-21508-8. We plug it in to the formula, and get:

(3 * 10 + 5 * 9 + 9 * 8 + 8 * 7 + 2 * 6 + 1 * 5 + 5 * 4 + 0 * 3 + 8 * 2 + 8 * 1) mod 11 == 0

Since the result is 0, this proves that our ISBN is valid.

Task

Given a string the program should check if the provided string is a valid ISBN-10. Putting this into place requires some thinking about preprocessing/parsing of the string prior to calculating the check digit for the ISBN.

The program should be able to verify ISBN-10 both with and without separating dashes.

Caveats

Converting from strings to numbers can be tricky in certain languages. Now, it's even trickier since the check digit of an ISBN-10 may be 'X' (representing '10'). For instance 3-598-21507-X is a valid ISBN-10.

Bonus tasks

  • Generate a valid ISBN-13 from the input ISBN-10 (and maybe verify it again with a derived verifier).

  • Generate valid ISBN, maybe even from a given starting ISBN.

Running tests

Execute the tests with:

$ elixir isbn_verifier_test.exs

Pending tests

In the test suites, all but the first test have been skipped.

Once you get a test passing, you can unskip the next one by commenting out the relevant @tag :pending with a # symbol.

For example:

# @tag :pending
test "shouting" do
  assert Bob.hey("WATCH OUT!") == "Whoa, chill out!"
end

Or, you can enable all the tests by commenting out the ExUnit.configure line in the test suite.

# ExUnit.configure exclude: :pending, trace: true

If you're stuck on something, it may help to look at some of the available resources out there where answers might be found.

Source

Converting a string into a number and some basic processing utilizing a relatable real world example. https://en.wikipedia.org/wiki/International_Standard_Book_Number#ISBN-10_check_digit_calculation

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

isbn_verifier_test.exs

if !System.get_env("EXERCISM_TEST_EXAMPLES") do
  Code.load_file("isbn_verifier.exs", __DIR__)
end

ExUnit.start()
ExUnit.configure(exclude: :pending, trace: true)

defmodule ISBNVerifierTest do
  use ExUnit.Case

  # @tag :pending
  test "valid isbn number" do
    assert ISBNVerifier.isbn?("3-598-21508-8")
  end

  @tag :pending
  test "invalid isbn check digit" do
    refute ISBNVerifier.isbn?("3-598-21508-9")
  end

  @tag :pending
  test "valid isbn number with a check digit of 10" do
    assert ISBNVerifier.isbn?("3-598-21507-X")
  end

  @tag :pending
  test "check digit is a character other than X" do
    refute ISBNVerifier.isbn?("3-598-21507-A")
  end

  @tag :pending
  test "invalid character in isbn" do
    refute ISBNVerifier.isbn?("3-598-2K507-0")
  end

  @tag :pending
  test "X is only valid as a check digit" do
    refute ISBNVerifier.isbn?("3-598-2X507-0")
  end

  @tag :pending
  test "valid isbn without separating dashes" do
    assert ISBNVerifier.isbn?("3598215088")
  end

  @tag :pending
  test "isbn without separating dashes and X as check digit" do
    assert ISBNVerifier.isbn?("359821507X")
  end

  @tag :pending
  test "isbn without check digit and dashes" do
    refute ISBNVerifier.isbn?("359821507")
  end

  @tag :pending
  test "too long isbn and no dashes" do
    refute ISBNVerifier.isbn?("3598215078X")
  end

  @tag :pending
  test "isbn without check digit" do
    refute ISBNVerifier.isbn?("3-598-21507")
  end

  @tag :pending
  test "too long isbn" do
    refute ISBNVerifier.isbn?("3-598-21507-XA")
  end

  @tag :pending
  test "check digit of X should not be used for 0" do
    refute ISBNVerifier.isbn?("3-598-21515-X")
  end
end
defmodule ISBNVerifier do
  @doc """
    Checks if a string is a valid ISBN-10 identifier

    ## Examples

      iex> ISBNVerifier.isbn?("3-598-21507-X")
      true

      iex> ISBNVerifier.isbn?("3-598-2K507-0")
      false

  """
  @spec isbn?(String.t()) :: boolean
  def isbn?(isbn) do
    new_isbn = remove_legit_dashes(isbn)
    if String.match?(new_isbn, ~r/^\d{9}(\d|X)$/) do
      try_checksum(new_isbn)
    else
      false
    end
  end

  defp checksum([]       , _ , acc), do: {:ok, acc }
  defp checksum([digit|rest], digit_number, acc) do
    # we've ensured, by regex call up top, that the X can only be last
    digit_value = if digit == "X", do: 10, else: String.to_integer(digit)
    new_acc = acc + digit_value * (11 - digit_number)
    checksum(rest, digit_number + 1, new_acc)
  end

  # remove dashes from ONLY where there are OK;
  # there are many styles but they all have in common that
  # the only legit place for a dash is between two digits
  defp remove_legit_dashes(string) do
    # Why dip, er, replace twice?  If you have one digit between
    # two dashes, replace will pick up from AFTER the replacement,
    # so it won't see the second dash as being preceded by a digit.  :-(
    # Could solve this with a more complex but efficient function,
    # but I don't wanna right now.  As is, this passes the ISBN rules
    # even for many non-English-speaking locations.
    string
      |> String.replace(~r/(\d)-(\d|X)/, "\\1\\2")
      |> String.replace(~r/(\d)-(\d|X)/, "\\1\\2")
  end

  defp try_checksum(isbn) do
    {status, result} =
      isbn
      |> String.graphemes
      |> checksum(1, 0)
    status == :ok && rem(result, 11) == 0
  end

end

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?