# include # include bool open ( int n, int d[] ); using namespace std; int main ( ) // // LOCK_COUNTING uses the COUNTING algorithm to determine the combination of a lock. // { int d[4], dmin = 0, dmax = 9, i, inc, n = 4; bool found; // // Initialize. // for ( i = 0; i < n; i++ ) { d[i] = dmin; } found = false; while ( true ) { // // Is this the correct combination? // if ( open ( n, d ) ) { found = true; cout << "\n"; cout << " Found the combination: "; for ( i = 0; i < n; i++ ) { cout << " " << d[i]; } cout << "\n"; break; } // // Try the next combination. // inc = -1; for ( i = n - 1; 0 <= i; i-- ) { if ( d[i] == dmax ) { d[i] = dmin; } else { inc = i; d[i] = d[i] + 1; break; } } // // If INC is still -1, we didn't find anything to increment, and we are done! // if ( inc == -1 ) { break; } } if ( !found ) { cout << "\n"; cout << "We did not find the combination!\n"; } return 0; } bool open ( int n, int d[] ) { bool value; if ( d[0] == 2 && d[1] == 0 && d[2] == 1 && d[3] == 1 ) { value = true; } else { value = false; } return value; }