有些时候出于不可告人的目的,我们可能希望把某些字符1对1地映射到另一个字符。比如'0'用'1'代替,'1'用'2'代替……。这个一般用混淆字典和其对偶字典就可以很高效(都是O(1))的搞定。不过我下午发现构造混淆字典很容易,构造其对偶字典则很痛苦,脑筋纠结,于是一咬牙一跺脚写了个程序来干这件事情。写完后发现不知道该把代码放哪,于是干脆贴在blog上备忘。
========================代码的分割线============================
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
// gene dicts
to map [min-max] to [min-max] and against
void geneDict(int min, int max)
{
int cnt =
max - min + 1;
if (cnt
<= 0)
{
return;
}
//
initial
int* dict =
new int[cnt];
int* agDict
= new int[cnt];
for (int i =
0; i < cnt; i++)
{
dict[i] =
min + i;
}
// random
arrange algo
srand((unsigned)time(NULL));
for (int i =
0; i < cnt; i++)
{
int swap_pos
= rand() % cnt;
if (i !=
swap_pos)
{
int tmp =
dict[i];
dict[i] =
dict[swap_pos];
dict[swap_pos] = tmp;
}
}
// get
against dict
for (int i =
0; i < cnt; i++)
{
agDict[dict[i] - min] = i + min;
}
//
print
cout
<< "char FUZZY_DICT[] = {";
for (int i =
0; i < cnt; i++)
{
if (i !=
0)
{
cout
<< ", ";
}
cout
<< "'"
<< ((char)dict[i])
<< "'";
}
cout
<< "};"
<< endl;
cout
<< "char DEFUZZY_DICT[] = {";
for (int i =
0; i < cnt; i++)
{
if (i !=
0)
{
cout
<< ", ";
}
cout
<< "'"
<< ((char)agDict[i])
<< "'";
}
cout
<< "};"
<< endl;
delete[]
dict;
delete[]
agDict;
}
int main(int argc, char* argv[])
{
int MIN_NUM
= '0';
int MAX_NUM
= '9';
geneDict(MIN_NUM, MAX_NUM);
return
0;
}
=====================================
以上代码用来生成'0'-'9'之间的ASCII码混淆字典。将MIN_NUM和MAX_NUM设为'a'和'z'则可混淆小写英文字母。设为'A'和'Z'则可混淆大写英文字母。