2012-07-25 32 views
2

我正在CS106L中进行有关STL算法的练习,其中一个问题是使用random_shuffle询问替换加密。使用STL的单字母排序加密使用STL,cs106l

问题是 使用random_shuffle实现一个函数MonoalphabeticSubstitutionEncrypt接受源字符串并使用随机单字母替代密码对其进行加密。

这意味着一开始我有 “AB..XYZ”,只是叫random_shuffle至A-Z 并产生类似“KVDQ ...... MSB” ,然后做加密原始字符串的映射。

我可以使用映射来做到这一点,但它应该通过仅使用这些STL算法来完成。

任何人有想法吗?谢谢!

我这样做是这样,但好像我不是使用STL算法的力量

string MonoSubsitutionEncrypt(string line){ 
    string original = "abcdefghijklmnopqrstuvwxyz"; 
    string excrypt = original; 
    random_shuffle(encrypt.begin(), encrypt.end()); 
    map<char, char> m; 
    for (int i = 0;i < original.length(); i++) 
     m.insert(make_pair(original[i],encrypt[i])); 
    string result; 
    for (int i = 0; i < line.length(); i++) 
     result += m[line[i]]; 
    return result; 
} 
+0

+1我喜欢给你任务的教授。很高兴听到教授们正在推广STL算法:) – Mahesh 2012-07-25 22:45:20

+0

通常人们“忘记”作业标签。 :) – Wug 2012-07-25 22:47:01

回答

0

我会用它创建和洗牌在创建数组/向量,和过载operator()映射类返回输入的加密版本。为了更加有用,您还需要一个成员函数(或者可能是运算符)来检索混淆字母表以用作解密密钥。

因此,使用std::transform进行加密本身应该是非常简单的。

+0

yaaa ..多数民众赞成在我看来,但是有可能不使用映射,并只使用STL?我们可以做得更好吗? – 2012-07-25 22:54:09

+1

@TimothyLeung:鉴于单字母取代*是映射,映射无疑是最明显的方法。我认为还有其他可以做的事情,但它必须是令人印象深刻的,才能被认定为“更好”。 – 2012-07-25 22:59:25

1

我刚刚写了一个随机将字节混入其他字节的版本。你将不得不经过一些箍来让它只接受和输出ascii字符。我专门处理了空字符,因为它应该被保留以指示字符串的结尾。

伪代码为我的算法如下:

#include <algorithm> 
#include <iostream> 
#include <vector> 
#include <string> 

template class Filler (T) 
    constructor Filler(T item) 
     initial = item 

    T operator()() 
     return initial++ 

    private T initial 

template class Encryptor (T1, T2) 
    constructor Encryptor(T1 mapping) 
     cipher = mapping 

    T2 operator() (T2 value) 
     return cipher[value] 

    private T1 cipher 

int main (int c, char * v[]) 
    // stl class, big enough to hold each char 
    vector<unsigned char> alphabet(256)  

    // creates a filler object described above 
    Filler<unsigned char> filler(0)   

    // stl function, fills alphabet with one of each char 
    generate_n(alphabet.begin(), 256, filler) 

    // stl function, shuffles alphabet (start at 1, leave NULL character at beginning) 
    random_shuffle(alphabet.begin() + 1, alphabet.end()) 

    // creates a generator to be passed to transform 
    Encryptor<vector<unsigned char>, unsigned char> e(alphabet) 

    // get input value: either first parameter, or nothing if no parameters 
    string input = c > 1 ? v[1] : "" 

    // stl function, uses encryptor containing alphabet mapping to obfuscate input 
    transform(input.begin(), input.end(), input.begin(), e) 

    // printing the string yields garbled crap 
    cout << input << endl; 

的STL类的文档使用:使用 string vector ostream

的STL方法文档:generate_nrandom_shuffletransform

如果这帖子给了太多,索姆一个人编辑它。