Hey, I'm attempting to use the function CrackP to try all possible combinations of "AAAA" through "ZZZZ" until CrackP's output equals P. I'd like a nudge in the right direction. Here's my current code:
My question is this: how can I run the for loops only until s = P?
For example, if P is AAAZ, I want to stop the execution of the for loops. I also want to print the number of iterations or attempts it took to "crack" the password.
I tried enclosing the for loops in
while ( s != P ), but that doesn't work because s is an empty string until later on in the loop.
BTW, there is a much more efficient way to do this by checking one character at a time. i.e. Don't enter the second loop until you've found a match on the first loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
void CrackP (const string & p)
{ for (char c1 = 'A'; c1 <= 'Z'; c1++)
if (p[0] == c1)
for (char c2 = 'A'; c2 <= 'Z'; c2++)
if (p[1] == c2)
for (char c3 = 'A'; c3 <= 'Z'; c3++)
if (p[2] == c3)
for (char c4 = 'A'; c4 <= 'Z'; c4++)
if (p[3] == c4)
{ cout << "Cracked " << p << endl;
return;
}
}
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
usingnamespace std;
const string ALPHABET = "ABC"; // For testing
// const string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // For real
constint CHOICES = ALPHABET.size();
//======================================================================
void nextWord( vector<int> &Iword ) // The next word (as defined by character indices)
{
for ( int i = 0; i < Iword.size(); i++ )
{
if ( Iword[i] < CHOICES - 1 ) // If can increment this position, do so and return
{
Iword[i]++;
return;
}
else // Otherwise cycle back and continue to next position
{
Iword[i] = 0;
}
}
}
//======================================================================
string word( vector<int> &Iword )
{
string result = "";
for ( int i : Iword ) result += ALPHABET[i];
return result;
}
//======================================================================
int main()
{
int N = 4; // Intended length of password
vector<int> Iword( N, 0 );
int MAXWORDS = pow( CHOICES, N );
cout << word( Iword ) << endl;
for ( int w = 2; w <= MAXWORDS; w++ )
{
nextWord( Iword );
cout << word( Iword ) << endl;
}
}
//======================================================================