Can you please tell me whether it is possible to optimize my array iteration function?

vector<string> brute(vector<string> alphabet, unsigned int max) { vector<int> temp{ -1 }; vector<string> result; for (size_t i = 0; i < max; i++) { bool over = true; for (size_t n = 0; n < temp.size(); n++) { if (abs(temp[n]) < alphabet.size() - 1) { over = false; } } if (over == true) { for (int n = 0; n < temp.size(); n++) { temp[n] = 0; } temp.resize(temp.size() + 1); string str; for (int n = 0; n < temp.size(); n++) { str = str + alphabet[temp[n]]; } result.push_back(str); } else { temp[0] = temp[0] + 1; for (int n = 0; n < temp.size() - 1; n++) { if (temp[n] > alphabet.size() - 1) { temp[n] = 0; temp[n + 1] = temp[n + 1] + 1; } } string str; for (int n = 0; n < temp.size(); n++) { str = str + alphabet[temp[n]]; } result.push_back(str); } } return result; } 
  • one
    and what exactly was the task, better attach the condition, perhaps there is another algorithm. - pavel
  • @pavel well, I would just like to sort through various combinations of strings with certain characters, so it works fine, but it seems to me that this can be done easier and the algorithm can be accelerated - alex-rudenkiy

2 answers 2

Well, I would do this:

 vector<string> brute(const vector<string>& al, int max) { vector<string> res = al; for(int pos = 0; res.size() < max; ++pos) { for(int sym = 0; sym < al.size() && res.size() < max; ++sym) res.push_back(res[pos] + al[sym]); } return res; } 

True, I don’t understand the logic of busting with substrings (why the alphabet is a set of strings, not characters), well, master-master, all of a sudden, he knows for sure that the password consists only of the substrings " khren " and " podberesh " in some order. ..

    The correct answer to your question: of course you can. First you need to get rid of the allocation of dynamic memory. It stands out where you add something to a string or vector, or resize . Memory needs to be allocated immediately somewhere in the global area. Then you need to get rid of operators of type + and the like, except for a wild waste of resources for the sake of convenience, they have little use. In short, write everything as if on pure C, then it will be much faster. If I understood the essence of the algorithm, I would most likely say that it was not optimally written, but I don’t know what you want, but I don’t feel like reading the code without explanation.

    • I think it was meant to optimize the complexity of the algorithm, otherwise the universal answer - write in assembly language :) - pavel
    • Well, then let the person give the algorithm in some description, and not just the code. When the code is given, I look at the code, and in the year it is full of “obvious universal retarders,” which I reported. If there is a brute force, then the algorithm is most likely not theoretically accelerated, you need to look at the context of its use and play on it. - Zealint