Verhoeff algorithm: Difference between revisions
Content added Content deleted
Line 235: | Line 235: | ||
#include <iostream> |
#include <iostream> |
||
#include <string> |
#include <string> |
||
#include <array> |
|||
typedef std::pair<std::string, bool> data; |
typedef std::pair<std::string, bool> data; |
||
const std::array<const std::array<int32_t, 10>, 10> multiplication_table = { { |
|||
int multiplication_table[10][10] = { |
|||
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, |
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, |
||
{ 1, 2, 3, 4, 0, 6, 7, 8, 9, 5 }, |
{ 1, 2, 3, 4, 0, 6, 7, 8, 9, 5 }, |
||
Line 249: | Line 250: | ||
{ 8, 7, 6, 5, 9, 3, 2, 1, 0, 4 }, |
{ 8, 7, 6, 5, 9, 3, 2, 1, 0, 4 }, |
||
{ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 } |
{ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 } |
||
}; |
} }; |
||
const std::array<int32_t, 10> inverse = { 0, 4, 3, 2, 1, 5, 6, 7, 8, 9 }; |
|||
const std::array<const std::array<int32_t, 10>, 8> permutation_table = { { |
|||
int permutation_table[8][10] = { |
|||
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, |
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, |
||
{ 1, 5, 7, 6, 2, 8, 3, 0, 9, 4 }, |
{ 1, 5, 7, 6, 2, 8, 3, 0, 9, 4 }, |
||
Line 262: | Line 263: | ||
{ 2, 7, 9, 3, 8, 0, 6, 4, 1, 5 }, |
{ 2, 7, 9, 3, 8, 0, 6, 4, 1, 5 }, |
||
{ 7, 0, 4, 6, 9, 1, 3, 2, 5, 8 } |
{ 7, 0, 4, 6, 9, 1, 3, 2, 5, 8 } |
||
}; |
} }; |
||
int32_t verhoeff_checksum(std::string number, bool doValidation, bool doDisplay) { |
|||
if ( doDisplay ) { |
if ( doDisplay ) { |
||
std::string calculationType = doValidation ? "Validation" : "Check digit"; |
std::string calculationType = doValidation ? "Validation" : "Check digit"; |
||
Line 276: | Line 277: | ||
} |
} |
||
int32_t c = 0; |
|||
const |
const int32_t le = number.length() - 1; |
||
for ( |
for ( int32_t i = le; i >= 0; i-- ) { |
||
const |
const int32_t ni = number[i] - '0'; |
||
const |
const int32_t pi = permutation_table[(le - i) % 8][ni]; |
||
c = multiplication_table[c][pi]; |
c = multiplication_table[c][pi]; |
||
Line 296: | Line 297: | ||
int main( ) { |
int main( ) { |
||
data |
const std::array<data, 3> tests = { |
||
std::make_pair("123", true), std::make_pair("12345", true), std::make_pair("123456789012", false) }; |
std::make_pair("123", true), std::make_pair("12345", true), std::make_pair("123456789012", false) }; |
||
for ( data test : tests ) { |
for ( data test : tests ) { |
||
int32_t digit = verhoeff_checksum(test.first, false, test.second); |
|||
std::cout << "The check digit for " << test.first << " is " << digit << "\n" << std::endl; |
std::cout << "The check digit for " << test.first << " is " << digit << "\n" << std::endl; |
||