 # exklamationmark's solution

## to Luhn in the Go Track

Published at Jul 13 2018 · 2 comments
Instructions
Test suite
Solution

#### Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

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.

## Running the tests

To run the tests run the command `go test` from within the exercise directory.

If the test suite contains benchmarks, you can run these with the `--bench` and `--benchmem` flags:

``````go test -v --bench . --benchmem
``````

Keep in mind that each reviewer will run benchmarks on a different machine, with different specs, so the results from these benchmark tests may vary.

## Further information

For more detailed information about the Go track, including how to get help if you're having trouble, please visit the exercism.io Go language page.

## 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.

### cases_test.go

``````package luhn

// Source: exercism/problem-specifications
// Commit: 3930b0a luhn: add a test case of strings with non-digits (#1246)
// Problem Specifications Version: 1.2.0

var testCases = []struct {
description string
input       string
ok          bool
}{
{
"single digit strings can not be valid",
"1",
false,
},
{
"a single zero is invalid",
"0",
false,
},
{
"a simple valid SIN that remains valid if reversed",
"059",
true,
},
{
"a simple valid SIN that becomes invalid if reversed",
"59",
true,
},
{
"a valid Canadian SIN",
"055 444 285",
true,
},
{
"055 444 286",
false,
},
{
"invalid credit card",
"8273 1232 7352 0569",
false,
},
{
"valid strings with a non-digit included become invalid",
"055a 444 285",
false,
},
{
"valid strings with punctuation included become invalid",
"055-444-285",
false,
},
{
"valid strings with symbols included become invalid",
"055£ 444\$ 285",
false,
},
{
"single zero with space is invalid",
" 0",
false,
},
{
"more than a single zero is valid",
"0000 0",
true,
},
{
"input digit 9 is correctly converted to output digit 9",
"091",
true,
},
{
"strings with non-digits is invalid",
":9",
false,
},
}``````

### luhn_test.go

``````package luhn

import "testing"

func TestValid(t *testing.T) {
for _, test := range testCases {
if ok := Valid(test.input); ok != test.ok {
t.Fatalf("Valid(%s): %s\n\t Expected: %t\n\t Got: %t", test.input, test.description, test.ok, ok)
}
}
}

func BenchmarkValid(b *testing.B) {
for i := 0; i < b.N; i++ {
Valid("2323 2005 7766 3554")
}
}``````
``````package luhn

// Valid checks whether a string containing a sequence of digits is valid. It returns true iff:
// - There is only space (' ') and digits ('0' to '9') in the string
// - luhn sum of the digits in the string is divisible by 10
func Valid(str string) bool {
// count digits, don't wanna allocate a new string with strings.Replace() (good if the str is long)
count := 0
for i := 0; i < len(str); i++ {
switch {
default:
return false
case str[i] == ' ':
case '0' <= str[i] && str[i] <= '9':
count++
}
}

sum := 0
dgI := 0               // current digit's index (ignoring space)
chkParity := count % 2 // parity of check digit's index
for i := 0; i < len(str); i++ {
if str[i] == ' ' {
continue
}

digit := int(str[i] - '0')
dgI++
dgParity := dgI % 2
switch {
case dgParity == chkParity:
sum = sum + digit
case dgParity != chkParity && digit*2 > 9:
sum = sum + digit*2 - 9
case dgParity != chkParity && digit*2 <= 9:
sum += digit * 2
}

}

return dgI > 1 && sum%10 == 0
}``````

Find this solution interesting? Ask the author a question to learn more. I'm finding your switch/pattern matching preference to be quite a bit less readable than the corresponding if/else if construct here, although I certainly agree that using a bare switch can be much more readable in some situations.

In this case, the reader must carefully compare five redundant comparisons to understand the logic. With if/else if, the reader only needs to consider three non-redundant comparisons. It is really just DRY.

In fact, because Go will only execute the first true case in the switch, just remove the redundant comparisons, and then you've solved your DRY problem and I'll have much less to complain about. Solution Author
commented over 1 year ago

hey, thanks for the comment.

As you have spotted, some of the expressions is redundant.

What I wanted to express was 3 disjoint conditions to be handled. This doesn't map 1:1 to Go, I guess.

### 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?