假定一种编码的编码范围是a-y的25个字母,从一位到四位的编码,如果我们把该编码按字典序排序,形成一个数组如下:
a,aa,aaa,aaaa,aaab,aaac,... ...,b,ba,baa,baaa,baab,baac,... ...,yyyw,yyyx,yyyy;
其中a的Index为0,aa的Index为1,aaa的Index为2,以此类推。
编写一个函数,输出给定编码对应Index。如:baca --> 16331.
#include <stdio.h>
#include <string.h>
#define N3 1
#define N2 25
#define N1 (25 * 25)
#define N0 (25 * 25 * 25)
#define C3 N3
#define C2 (N2 + N3)
#define C1 (N1 + N2 + N3)
#define C0 (N0 + N1 + N2 + N3)
int main()
{
char code[11][5] = {"a", "aa", "aaa", "aaaa", "ab", "aba", "b", "ba", "bac", "baca", "yyyy"};
for(int i = 0; i < 11; i++){
int index = 0;
switch(strlen(code[i])){
case 1: index = C0 * (code[i][0] - 'a'); break;
case 2: index = C0 * (code[i][0] - 'a') + C1 * (code[i][1] - 'a') + 1; break;
case 3: index = C0 * (code[i][0] - 'a') + C1 * (code[i][1] - 'a') + C2 * (code[i][2] - 'a') + 2; break;
case 4: index = C0 * (code[i][0] - 'a') + C1 * (code[i][1] - 'a') + C2 * (code[i][2] - 'a') + C3 * (code[i][3] - 'a') + 3; break;
default: break;
}
printf("code = %-4s, strlen =%2d, index =%7d\n", code[i], strlen(code[i]), index);
}
return 0;
}
结果显示如下:
code = a , strlen = 1, index = 0
code = aa , strlen = 2, index = 1
code = aaa , strlen = 3, index = 2
code = aaaa, strlen = 4, index = 3
code = ab , strlen = 2, index = 652
code = aba , strlen = 3, index = 653
code = b , strlen = 1, index = 16276
code = ba , strlen = 2, index = 16277
code = bac , strlen = 3, index = 16330
code = baca, strlen = 4, index = 16331
code = yyyy, strlen = 4, index = 406899
完整截图:
改进版代码:
#include <stdio.h>
#include <string.h>
#define N3 1
#define N2 25
#define N1 (25 * 25)
#define N0 (25 * 25 * 25)
#define C3 N3
#define C2 (N2 + N3)
#define C1 (N1 + N2 + N3)
#define C0 (N0 + N1 + N2 + N3)
int main()
{
char code[11][5] = {"a", "aa", "aaa", "aaaa", "ab", "aba", "b", "ba", "bac", "baca", "yyyy"};
for(int i = 0; i < 11; i++){
int index = 0;
switch(strlen(code[i])){
case 4: index += C3 * (code[i][3] - 'a') + 1;
case 3: index += C2 * (code[i][2] - 'a') + 1;
case 2: index += C1 * (code[i][1] - 'a') + 1;
case 1: index += C0 * (code[i][0] - 'a');
/*
case 1: index = C0 * (code[i][0] - 'a'); break;
case 2: index = C0 * (code[i][0] - 'a') + C1 * (code[i][1] - 'a') + 1; break;
case 3: index = C0 * (code[i][0] - 'a') + C1 * (code[i][1] - 'a') + C2 * (code[i][2] - 'a') + 2; break;
case 4: index = C0 * (code[i][0] - 'a') + C1 * (code[i][1] - 'a') + C2 * (code[i][2] - 'a') + C3 * (code[i][3] - 'a') + 3; break;
*/
default: break;
}
printf("code = %-4s, strlen =%2d, index =%7d\n", code[i], strlen(code[i]), index);
}
return 0;
}
改进版完整截图: