Damm algorithm: Difference between revisions

Content added Content deleted
(Add MACRO-11)
m (→‎{{header|C++}}: Shortened code a bit)
Line 760: Line 760:
=={{header|C++}}==
=={{header|C++}}==
{{trans|C#|C sharp}}
{{trans|C#|C sharp}}
<syntaxhighlight lang="cpp">#include <sstream>
<syntaxhighlight lang="cpp">#include <string>


#include <cstdio>
const int TABLE[][10] = {

inline constexper int TABLE[][10] = {
{0, 3, 1, 7, 5, 9, 8, 6, 4, 2},
{0, 3, 1, 7, 5, 9, 8, 6, 4, 2},
{7, 0, 9, 2, 1, 5, 4, 8, 6, 3},
{7, 0, 9, 2, 1, 5, 4, 8, 6, 3},
Line 775: Line 777:
};
};


using std::string;
[[nodiscard]] bool damm(std::string s) noexcept {
bool damm(string s) {
int interim = 0;
int interim = 0;
for (char c : s) {
for (const auto c : s) {
interim = TABLE[interim][c - '0'];
interim = TABLE[interim][c - '0'];
}
}
Line 785: Line 786:


int main() {
int main() {
auto numbers = { 5724, 5727, 112946, 112949 };
for (const auto num : { 5724, 5727, 112946, 112949 }) {
if (damm(std::to_string(num))) {
for (int num : numbers) {
std::printf("%6d is valid\n", num);
using std::stringstream;
}
stringstream ss;
else std::printf("%6d is invalid\n", num);
ss << num;
bool isValid = damm(ss.str());
if (isValid) {
printf("%6d is valid\n", num);
} else {
printf("%6d is invalid\n", num);
}
}
}

return 0;
}</syntaxhighlight>
}</syntaxhighlight>
{{out}}
{{out}}