2023-11-29 10:39:24 -05:00
|
|
|
---
|
|
|
|
minutes: 30
|
|
|
|
---
|
|
|
|
|
|
|
|
# Exercise: Luhn Algorithm
|
|
|
|
|
2022-12-21 16:36:30 +01:00
|
|
|
# Luhn Algorithm
|
|
|
|
|
|
|
|
The [Luhn algorithm](https://en.wikipedia.org/wiki/Luhn_algorithm) is used to
|
|
|
|
validate credit card numbers. The algorithm takes a string as input and does the
|
|
|
|
following to validate the credit card number:
|
|
|
|
|
2024-06-25 14:40:56 +01:00
|
|
|
- Ignore all spaces. Reject numbers with fewer than two digits.
|
2022-12-21 16:36:30 +01:00
|
|
|
|
2023-12-31 00:15:07 +01:00
|
|
|
- Moving from **right to left**, double every second digit: for the number
|
|
|
|
`1234`, we double `3` and `1`. For the number `98765`, we double `6` and `8`.
|
2022-12-21 16:36:30 +01:00
|
|
|
|
2023-12-31 00:15:07 +01:00
|
|
|
- After doubling a digit, sum the digits if the result is greater than 9. So
|
|
|
|
doubling `7` becomes `14` which becomes `1 + 4 = 5`.
|
2022-12-21 16:36:30 +01:00
|
|
|
|
2023-12-31 00:15:07 +01:00
|
|
|
- Sum all the undoubled and doubled digits.
|
2022-12-21 16:36:30 +01:00
|
|
|
|
2023-12-31 00:15:07 +01:00
|
|
|
- The credit card number is valid if the sum ends with `0`.
|
2022-12-21 16:36:30 +01:00
|
|
|
|
2023-11-29 10:39:24 -05:00
|
|
|
The provided code provides a buggy implementation of the luhn algorithm, along
|
2024-06-25 14:40:56 +01:00
|
|
|
with two basic unit tests that confirm that most of the algorithm is implemented
|
2023-11-29 10:39:24 -05:00
|
|
|
correctly.
|
2022-12-21 16:36:30 +01:00
|
|
|
|
2023-11-29 10:39:24 -05:00
|
|
|
Copy the code below to <https://play.rust-lang.org/> and write additional tests
|
|
|
|
to uncover bugs in the provided implementation, fixing any bugs you find.
|
2022-12-21 16:36:30 +01:00
|
|
|
|
|
|
|
```rust
|
2023-11-29 10:39:24 -05:00
|
|
|
{{#include exercise.rs:luhn}}
|
2022-12-21 16:36:30 +01:00
|
|
|
|
2023-11-29 10:39:24 -05:00
|
|
|
{{#include exercise.rs:unit-tests}}
|
2022-12-21 16:36:30 +01:00
|
|
|
}
|
|
|
|
```
|