ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

Published at Aug 25 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.

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.

```
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!

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

The Scala exercises assume an SBT project scheme. The exercise solution source should be placed within the exercise directory/src/main/scala. The exercise unit tests can be found within the exercise directory/src/test/scala.

To run the tests simply run the command `sbt test`

in the exercise directory.

For more detailed info about the Scala track see the help page.

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

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

```
import org.scalatest.{Matchers, FunSuite}
/** @version 1.2.0 */
class LuhnTest extends FunSuite with Matchers {
test("single digit strings can not be valid") {
Luhn.valid("1") should be(false)
}
test("a single zero is invalid") {
pending
Luhn.valid("0") should be(false)
}
test("a simple valid SIN that remains valid if reversed") {
pending
Luhn.valid("059") should be(true)
}
test("a simple valid SIN that becomes invalid if reversed") {
pending
Luhn.valid("59") should be(true)
}
test("a valid Canadian SIN") {
pending
Luhn.valid("055 444 285") should be(true)
}
test("invalid Canadian SIN") {
pending
Luhn.valid("055 444 286") should be(false)
}
test("invalid credit card") {
pending
Luhn.valid("8273 1232 7352 0569") should be(false)
}
test("valid strings with a non-digit included become invalid") {
pending
Luhn.valid("055a 444 285") should be(false)
}
test("valid strings with punctuation included become invalid") {
pending
Luhn.valid("055-444-285") should be(false)
}
test("valid strings with symbols included become invalid") {
pending
Luhn.valid("055Â£ 444$ 285") should be(false)
}
test("single zero with space is invalid") {
pending
Luhn.valid(" 0") should be(false)
}
test("more than a single zero is valid") {
pending
Luhn.valid("0000 0") should be(true)
}
test("input digit 9 is correctly converted to output digit 9") {
pending
Luhn.valid("091") should be(true)
}
test("strings with non-digits is invalid") {
pending
Luhn.valid(":9") should be(false)
}
}
```

```
object Luhn {
def valid: String => Boolean = cardNo => Some(cardNo).filter(validFormat).filter(validLuhn).isDefined
private def validLuhn(cardNo: String): Boolean =
cardNo.replaceAll("\\D", "").map(_.asDigit).reverse.zipWithIndex.map {
case (d, idx) if idx % 2 == 0 => d
case (d, _) if d > 4 => 2 * d - 9
case (d, _) if d <= 4 => 2 * d
}.sum % 10 == 0
private def validFormat(cardNo: String): Boolean = atLeastNDigits(2)(cardNo) && validRegex(cardNo)
private def validRegex: String => Boolean = s => """[\d ]{2,}""".r.pattern.matcher(s).matches
private def atLeastNDigits: Int => String => Boolean = n => s => s.filter(Character.isDigit).size >= n
}
```

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?

Level up your programming skills with 3,423 exercises across 52 languages, and insightful discussion with our volunteer team of welcoming mentors.
Exercism is
**100% free forever**.

## Community comments