🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉
Avatar of bkhl

bkhl's solution

to Luhn in the D Track

Published at Aug 20 2019 · 0 comments
Instructions
Test suite
Solution

Given a number determine whether or not it is valid per the Luhn formula.

The Luhn algorithm is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers and Canadian Social Insurance Numbers.

The task is to check if a given string is valid.

Validating a Number

Strings of length 1 or less are not valid. Spaces are allowed in the input, but they should be stripped before checking. All other non-digit characters are disallowed.

Example 1: valid credit card number

4539 1488 0343 6467

The first step of the Luhn algorithm is to double every second digit, starting from the right. We will be doubling

4_3_ 1_8_ 0_4_ 6_6_

If doubling the number results in a number greater than 9 then subtract 9 from the product. The results of our doubling:

8569 2478 0383 3437

Then sum all of the digits:

8+5+6+9+2+4+7+8+0+3+8+3+3+4+3+7 = 80

If the sum is evenly divisible by 10, then the number is valid. This number is valid!

Example 2: invalid credit card number

8273 1232 7352 0569

Double the second digits, starting from the right

7253 2262 5312 0539

Sum the digits

7+2+5+3+2+2+6+2+5+3+1+2+0+5+3+9 = 57

57 is not evenly divisible by 10, so this number is not valid.

Getting Started

Make sure you have read D page on exercism.io. This covers the basic information on setting up the development environment expected by the exercises.

Passing the Tests

Get the first test compiling, linking and passing by following the three rules of test-driven development. Create just enough structure by declaring namespaces, functions, classes, etc., to satisfy any compiler errors and get the test to fail. Then write just enough code to get the test to pass. Once you've done that, uncomment the next test by moving the following line past the next test.

static if (all_tests_enabled)

This may result in compile errors as new constructs may be invoked that you haven't yet declared or defined. Again, fix the compile errors minimally to get a failing test, then change the code minimally to pass the test, refactor your implementation for readability and expressiveness and then go on to the next test.

Try to use standard D facilities in preference to writing your own low-level algorithms or facilities by hand. DRefLanguage and DReference are references to the D language and D standard library.

Source

The Luhn Algorithm on Wikipedia http://en.wikipedia.org/wiki/Luhn_algorithm

Submitting Incomplete Solutions

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

luhn.d

module luhn;

unittest
{
    immutable int allTestsEnabled = 0;

    // Single digit strings can not be valid
    assert(!valid("1"));

    static if (allTestsEnabled)
    {
        // A single zero is invalid
        assert(!valid("0"));

        // A simple valid SIN that remains valid if reversed
        assert(valid("059"));

        // A simple valid SIN that becomes invalid if reversed
        assert(valid("59"));

        // A valid Canadian SIN
        assert(valid("055 444 285"));

        // Invalid Canadian SIN
        assert(!valid("055 444 286"));

        // Invalid credit card
        assert(!valid("8273 1232 7352 0569"));

        // Valid number with an even number of digits
        assert(valid("095 245 88"));

        // Valid number with an odd number of spaces
        assert(valid("234 567 891 234"));

        // Valid strings with a non-digit added at the end become invalid
        assert(!valid("059a"));

        // Valid strings with punctuation included become invalid
        assert(!valid("055-444-285"));

        // Valid strings with symbols included become invalid
        assert(!valid("055# 444$ 285"));

        // Single zero with space is invalid
        assert(!valid(" 0"));

        // More than a single zero is valid
        assert(valid("0000 0"));

        // Input digit 9 is correctly converted to output digit 9
        assert(valid("091"));

        /*
        Convert non-digits to their ascii values and then offset them by 48 sometimes accidentally declare an invalid string to be valid. 
        This test is designed to avoid that solution.
        */

        // Using ascii value for non-doubled non-digit isn't allowed
        assert(!valid("055b 444 285"));

        // Using ascii value for doubled non-digit isn't allowed
        assert(!valid(":9"));
    }

}
module luhn;

import std.range;
import std.algorithm.iteration;
import std.string;

bool valid(string input)
{
    if (input.indexOfNeither("0123456789 ") != -1)
    {
        return false;
    }

    auto digits = input.filter!(c => c != ' ')
        .map!(c => c - '0')
        .array;

    if (digits.length < 2)
    {
        return false;
    }

    auto odd = digits.retro.stride(2);
    auto even = digits.retro.dropOne.stride(2).map!(n => n * 2 - ((n >= 5) ? 9 : 0));

    return (odd.sum + even.sum) % 10 == 0;
}

unittest
{
    // Single digit strings can not be valid
    assert(!valid("1"));

    // A single zero is invalid
    assert(!valid("0"));

    // A simple valid SIN that remains valid if reversed
    assert(valid("059"));

    // A simple valid SIN that becomes invalid if reversed
    assert(valid("59"));

    // A valid Canadian SIN
    assert(valid("055 444 285"));

    // Invalid Canadian SIN
    assert(!valid("055 444 286"));

    // Invalid credit card
    assert(!valid("8273 1232 7352 0569"));

    // Valid number with an even number of digits
    assert(valid("095 245 88"));

    // Valid number with an odd number of spaces
    assert(valid("234 567 891 234"));

    // Valid strings with a non-digit added at the end become invalid
    assert(!valid("059a"));

    // Valid strings with punctuation included become invalid
    assert(!valid("055-444-285"));

    // Valid strings with symbols included become invalid
    assert(!valid("055# 444$ 285"));

    // Single zero with space is invalid
    assert(!valid(" 0"));

    // More than a single zero is valid
    assert(valid("0000 0"));

    // Input digit 9 is correctly converted to output digit 9
    assert(valid("091"));

    /*
    Convert non-digits to their ascii values and then offset them by 48
    sometimes accidentally declare an invalid string to be valid.  This test is
    designed to avoid that solution.
    */

    // Using ascii value for non-doubled non-digit isn't allowed
    assert(!valid("055b 444 285"));

    // Using ascii value for doubled non-digit isn't allowed
    assert(!valid(":9"));
}

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?