|
| 1 | +// C++ Program to test 1/e law for Secretary Problem : |
| 2 | +#include <iostream> |
| 3 | +#include <time.h> |
| 4 | +#define e 2.71828 |
| 5 | +using namespace std; |
| 6 | + |
| 7 | +// To find closest integer of num. |
| 8 | +int roundNo(float num) |
| 9 | +{ |
| 10 | + return num < 0 ? num - 0.5 : num + 0.5; |
| 11 | +} |
| 12 | + |
| 13 | +// Finds best candidate using n/e rule. candidate[] |
| 14 | +// represents talents of n candidates. |
| 15 | +void printBestCandidate(int candidate[], int n) |
| 16 | +{ |
| 17 | + // Calculating sample size for benchmarking. |
| 18 | + int sample_size = roundNo(n/e); |
| 19 | + cout << "\n\nSample size is " << sample_size << endl; |
| 20 | + |
| 21 | + // Finding best candidate in sample size |
| 22 | + int best = 0; |
| 23 | + for (int i = 1; i < sample_size; i++) |
| 24 | + if (candidate[i] > candidate[best]) |
| 25 | + best = i; |
| 26 | + |
| 27 | + // Finding the first best candidate that is |
| 28 | + // better than benchmark set. |
| 29 | + for (int i = sample_size; i < n; i++) |
| 30 | + if (candidate[i] >= candidate[best]) { |
| 31 | + best = i; |
| 32 | + break; |
| 33 | + } |
| 34 | + |
| 35 | + if (best >= sample_size) |
| 36 | + cout << endl << "Best candidate found is " |
| 37 | + << best + 1 << " with talent " |
| 38 | + << candidate[best] << endl; |
| 39 | + else |
| 40 | + cout << "Couldn't find a best candidate\n"; |
| 41 | +} |
| 42 | + |
| 43 | +int main() |
| 44 | +{ |
| 45 | + int n = 8; |
| 46 | + |
| 47 | + // n = 8 candidates and candidate array contains |
| 48 | + // talents of n candidate where the largest |
| 49 | + // number means highest talented candidate. |
| 50 | + int candidate[n]; |
| 51 | + |
| 52 | + // generating random numbers between 1 to 8 |
| 53 | + // for talent of candidate |
| 54 | + srand(time(0)); |
| 55 | + for (int i = 0; i < n; i++) |
| 56 | + candidate[i] = 1 + rand() % 8; |
| 57 | + |
| 58 | + cout << "Candidate : "; |
| 59 | + for (int i = 0; i < n; i++) |
| 60 | + cout << i + 1 << " "; |
| 61 | + cout << endl; |
| 62 | + cout << " Talents : "; |
| 63 | + for (int i = 0; i < n; i++) |
| 64 | + cout << candidate[i] << " "; |
| 65 | + |
| 66 | + printBestCandidate(candidate, n); |
| 67 | + |
| 68 | + return 0; |
| 69 | +} |
0 commit comments