Last active
November 8, 2021 17:27
-
-
Save mfukar/93a5d6c2ed56775933b2547ccec5559e to your computer and use it in GitHub Desktop.
The Luhn test in C++11
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
#include <numeric> | |
#include <iostream> | |
#include <vector> | |
/* | |
* Assuming an input of a string of digits, perform the Luhn test on the indicated sequence. | |
* Returns true if the given string passes the test, false otherwise. | |
*/ | |
bool luhn(const std::string& seq) { | |
static const int m[] = { 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 }; | |
bool is_odd = false; | |
auto lambda = [&](int a, char c) { | |
return a + ((is_odd = !is_odd) ? c - '0' : m[c - '0']); | |
}; | |
int sum = std::accumulate(seq.rbegin(), seq.rend(), 0, lambda); | |
return 0 == sum % 10; | |
} | |
int main (void) { | |
auto t_cases = {"49927398716", "49927398717", "1234567812345678", "1234567812345670"}; | |
auto print = [](const std::string & s) { std::cout << s << ": " << luhn (s) << std::endl; }; | |
std::for_each (t_cases.begin (), t_cases.end (), print); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment