/****************************************************************************** * This program demonstrates the Luhn Algorithm for credit card validation. * * Copyright © 2021 Richard Lesh. All rights reserved. *****************************************************************************/ #undef NDEBUG #include "Utils.hpp" #include #include #include #include #include std::locale utf8loc(std::locale(), new std::codecvt_utf8); using namespace Utils; using namespace std; static vector GOOD_CASES = {L"4321123456789019", L"5432123456789020", L"65432101234567896"}; static vector BAD_CASES = {L"4321123456798019", L"4432123456789020", L"65431201234567896"}; bool luhn_check(wstring s) noexcept { int checksum = 0; int const LENGTH = s.length(); int const DOUBLE_DIGIT = LENGTH % 2; for (auto i = 0; i < LENGTH - 1; ++i) { int c = (int)(s[i]) - int(L'0'); if (i % 2 == DOUBLE_DIGIT) { c *= 2; if (c > 9) { c -= 9; } } checksum += c; } checksum *= 9; checksum %= 10; return (int)(s[LENGTH - 1]) - int(L'0') == checksum; } int main(int argc, char **argv) { setlocale(LC_ALL, "en_US.UTF-8"); wcout.imbue(utf8loc); wcin.imbue(utf8loc); wcout << L"Good Test Cases" << endl; for (auto s : GOOD_CASES) { wcout << s << L" is " << luhn_check(s) << endl; } wcout << L"Bad Test Cases" << endl; for (auto s : BAD_CASES) { wcout << s << L" is " << luhn_check(s) << endl; } return 0; }