Browse Source

perf: short code string convert

legacy
Dnomd343 2 years ago
parent
commit
621350ab83
  1. 4
      klotski/main.cc
  2. 18
      klotski/short_code.cc
  3. 36
      klotski/short_code.h

4
klotski/main.cc

@ -65,5 +65,9 @@ int main() {
std::cout << ShortCode::code_to_string(14323231) << std::endl;
std::cout << ShortCode::code_from_string("EP4HZ") << std::endl;
// for (int i = 0; i < 32; ++i) {
// std::cout << int(SHORT_CODE_TABLE[i] - 49) << ": " << i << std::endl;
// }
return 0;
}

18
klotski/short_code.cc

@ -33,23 +33,17 @@ uint32_t ShortCode::code_from_string(const std::string &short_code) { // 5-bits
uint32_t result = 0;
for (auto bit : short_code) {
result *= 32;
if (bit >= '1' && bit <= '9') { // 1 ~ 9
result += bit - 49;
continue;
if (bit >= 'a' && bit <= 'z') {
bit -= 32; // convert to uppercase
}
if (bit >= 'a' && bit <= 'z') { // a ~ z
bit -= ('a' - 'A'); // convert to A ~ Z
if (bit >= '1' && bit <= 'Z') {
result += (bit = SHORT_CODE_TABLE_REV[bit - 49]); // table convert
if (bit != -1) {
continue; // pass check
}
if (bit >= 'A' && bit <= 'Z') { // A ~ Z
bit = SHORT_CODE_TABLE_REV[bit - 65]; // table convert
if (bit == 0) {
throw std::runtime_error("invalid short code");
}
result += bit;
} else {
throw std::runtime_error("invalid short code");
}
}
if (!ShortCode::check(result)) {
throw std::range_error("short code out of range");
}

36
klotski/short_code.h

@ -11,28 +11,32 @@ const char SHORT_CODE_TABLE[32] = {
'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
};
const char SHORT_CODE_TABLE_REV[26] = {
// 00 01 02 03 04 05 06 07 08 09
9, 10, 11, 12, 13, 14, 15, 16, 0, 17,
// 10 11 12 13 14 15 16 17 18 19
18, 0, 19, 20, 0, 21, 22, 23, 24, 25,
// 20 21 22 23 24 25
const char SHORT_CODE_TABLE_REV[42] = {
// 00 01 02 03 04 05 06 07 08
0, 1, 2, 3, 4, 5, 6, 7, 8,
// 09 10 11 12 13 14 15
-1, -1, -1, -1, -1, -1, -1,
// 16 17 18 19 20 21 22 23 24 25
9, 10, 11, 12, 13, 14, 15, 16, -1, 17,
// 26 27 28 29 30 31 32 33 34 35
18, -1, 19, 20, -1, 21, 22, 23, 24, 25,
// 36 37 38 39 40 41
26, 27, 28, 29, 30, 31,
};
// 00: 1 -> 48
// 00: 1 -> 49 (00)
// ...
// 08: 9 -> 57
// 09: A -> 65 (00)
// 08: 9 -> 57 (08)
// 09: A -> 65 (16)
// ...
// 16: H -> 72 (07)
// 17: J -> 74 (09)
// 18: K -> 75 (10)
// 19: M -> 77 (12)
// 20: N -> 78 (13)
// 21: P -> 80 (15)
// 16: H -> 72 (23)
// 17: J -> 74 (25)
// 18: K -> 75 (26)
// 19: M -> 77 (28)
// 20: N -> 78 (29)
// 21: P -> 80 (31)
// ...
// 31: Z -> 90 (25)
// 31: Z -> 90 (41)
class ShortCode {
public:

Loading…
Cancel
Save