I apologize for somewhat going off topic vis-a-vis the OP's thread here. My multiple efforts to post this as a new thread under my own account name (which I had not used in a while) failed. That's why I'm using this means to get my very pressing question/problem out. Thx.
OK, please, consider this seemingly simple, but knotty problem.
A binary string of length n (a string containing only '0's and '1's) is constructed according to the following special rule: every occurrence of '0' in the string must appear as a consecutive block (all '0's together) of length that is a multiple of k. That is, the number of consecutive '0's must be k, 2k, 3k, ...
Given n and k, write a function that determines the total number of valid binary strings that can be formed.
For example:
if n = 3, k = 2; then the function returns 3 (since valid strings are: 111, 100, 001)
if n = 4, k = 2; then the function returns 5 (since valid strings are: 1111, 1001, 0011, 1100, 0000)
I wrote the code snippet below and obtained correct results for the two cases above.
1 2 3 4 5 6 7 8 9 10 11
|
int validStr(int n, int k) {
int j {0};
int h {1};
while (h*k <= n){
for (int i = 0; i < n - h*k + 1; ++i){
++j;
}
++h;
}
return j + 1;
}
|
However, I got perturbed that my answer was deemed wrong when compared to the examiner's for some other cases. Such cases as I could easily manually prove I was right!
For instance, when n = 5 and k = 2, my code returns 7 (11111, 00111, 10011, 11001, 11100, 00001, 10000) but the examiner's (hidden) code says the answer is 8.
When n = 10 and k = 2, my code returns 26; the examiner's returns 89. My answer is so way off here!
I've concluded that there is something about the problem definition and/or interpretation I am not getting! Any ideas/insights?