五笔的编码范围是a ~ y的25个字母,从1位到4位的编码,如果我们把五笔的编码按字典序排序,形成一个数组如下:
a, aa, aaa, aaaa, aaab, aaac, … …, b, ba, baa, baaa, baab, baac … …, yyyw, yyyx, yyyy
其中a的Index为0,aa的Index为1,aaa的Index为2,以此类推。
- 编写一个函数,输入是任意一个编码,比如baca,输出这个编码对应的Index;
- 编写一个函数,输入是任意一个Index,比如12345,输出这个Index对应的编码
#include <stdio.h> #include <stdlib.h> #define SIZE 5 #define SERIES (3+25*25*25) const char fixCh = 'a'; //定位编码 int locate(char* str) { if (!str || *str == '\0') { return 0; } int len = strlen(str); if (len > 4) { return -1; } else if (len == 2 && *(str + 1) != fixCh) { return -1; } else if (len == 3 && (*(str + 1) != fixCh || *(str + 2) != fixCh)) { return -1; } char firstCh = *str; int fixIndex = (firstCh - fixCh) * SERIES + len - 1; if (len == 4) { int i = SIZE - 2; int base = 1; for (; i > 0; i--) { fixIndex += (*(str + i) - fixCh) * base; base *= 25; } } return fixIndex; } char* findStrByIndex(int index) { if (index < 0 || index > 390699) { puts("Invaild Index"); return NULL; } char result[SIZE]; int findIndex = index; result[0] = fixCh + (findIndex / SERIES); int nextIndex = findIndex % SERIES; int i = 1; if (nextIndex < 3 && nextIndex >= 0) { for (; i <= nextIndex; i++) { result[i] = fixCh; } } else { int base = 25 * 25; nextIndex = nextIndex - 3; for (; i < SIZE - 1; i++) { result[i] = fixCh + (nextIndex / base); nextIndex %= base; base /= 25; } } result[i] = '\0'; puts(result); } //定位测试 void test1() { //yyyy:390699 char str[SIZE] = "yyyy"; gets(str); int fixIndex; if ((fixIndex = locate(str)) > -1) { printf("%s index:%3d", str, fixIndex); } else { printf("%s Invalid Input", str); } } //查找测试 void test2() { int findIndex = 390699; scanf("%d", &findIndex); findStrByIndex(findIndex); } int main(void) { test1(); // test2(); return EXIT_SUCCESS; }