In: Advanced Math
(a) Design an algorithm that reveals some secret integer number from the set {1, 2, ... , n} by guessing random numbers within the given range until the secret number has been guessed. Numbers should be replaced after being guessed such that it is possible to guess 2 and then 2 again, assuming 2 is in the given range. The algorithm should return both the secret number as well as the number of guesses taken.
(b) If possible, calculate the tightest Big-O approximation for the average runtime complexity of the algorithm from part (a). If it is not possible, explain why not. Note: assume that choosing a random number takes O(1) time.
(c) If possible, calculate the tightest Big-O approximation for the worst case runtime complexity of the algorithm from part (a). If it is not possible, explain why not. Note: assume that choosing a random number takes O(1) time.
(d) In a single run, is it possible that of the algorithm from part (a) finds the secret number in fewer guesses than a standard binary search algorithm? If so, please provide a concrete example of one such situation.
IF YOU HAVE ANY DOUBTS COMMENT BELOW I WILL BE TTHERE TO HELP YOU..ALL THE BEST
ANSWER:
code and explanation:
1)
assuming set containing secret intezer is all intezers from 1 to N
implementation of algorithm in c++:
#include <iostream>
#include <algorithm>
#include <random>
#include <time.h>
using namespace std;
#define N 20 //let n be 20
int main()
{
srand(time(0));
int secret_number = 2;
//let
secret number be 2
int count = 0;
//number
of guesses taken
int current_guess = rand() % N + 1;
//choosing random between 1 to n
count++;
//increement
count
while (current_guess != secret_number)
//repeat till we encounter secret number
{
current_guess =
rand() % N + 1; //again choosing random number between 1 to n
count++;
//increement
count
}
cout << "Secret number is " <<
secret_number << " and number of gueses taken is " <<
count;
}
2nd and 3rd Q are more or less same
Q asks if we can approximate runtime complexity of
this algorithm, but the answer is we can't
atleast for this algorithm because we are initializing rand() using
srand(time(0)) which always
generates different random intezer each time program
runs.
screenshot is attatched which states different number of guesses each time we run program
But if we assumes random number generator generates
purely random intezer from 1 to n
based on probabilities,
then runtime complexity both average as well as worst case is O(n).
4)
Yes it is possible that this
algorithm takes fewer guesses than binary search algorithm
example is shown in screenshot. Where n is
20 and secret number is 2.
here complexity of binary
search algorithm is log(n), so log(20) ie more than 4 but
in screenshot below it can be seen that in some cases number of
guesses is 3 also which
is less than 4.
I HOPE YOU UNDERSTAND..
PLS RATE THUMBS UP..ITS HELPS ME ALOT..
THANK YOU...!!