jeudi 26 février 2015

"Industrial Strength" C++ struct


It's been a while since I used C++. I was asked for job interview to create a C++ struct for a downsampling routine which would meet the following interface:



struct deterministic_sample
{
deterministic_rate( double rate );
bool operator()();
};


-- with the following behaviour:



  • We have an object of that class: deterministic_sample s;

  • We call s() N times, and it returns true, W times. M / N is roughly equal to the rate

  • The sequence is deterministic, not random and should be the same each time

  • The class should be "industrial strength", for use on a busy stream.


My solution, version 2:



#include <iostream>
#include <cmath>
#include <climits>

using namespace std;

struct deterministic_sample
{
double sampRate;
int index;

deterministic_sample() {
sampRate = 0.1;
index = 0;
}

void deterministic_rate( double rate ) {
this->sampRate = rate; // Set the ivar. Not so necessary to hide data, but just complying with the interface, as given...
this->index = 0; // Reset the incrementer
};

bool operator()() {

if (this->index == INT_MAX) {
this->index = 0;
}

double multiple = this->index * this->sampRate;

this->index++; // Increment the index

if (fmod(multiple, 1) < this->sampRate) {
return true;
} else {
return false;
}

};
};

int main()
{
deterministic_sample s; // Create a sampler
s.deterministic_rate(0.253); // Set the rate
int tcnt = 0; // Count of True
int fcnt = 0; // Count of False

for (int i = 0; i < 10000; i++) {
bool o = s();
if (o) {
tcnt++;
} else {
fcnt++;
}
}

cout << "Trues: " << tcnt << endl;
cout << "Falses: " << fcnt << endl;

cout << "Ratio: " << ((float)tcnt / (float)(tcnt + fcnt)) << endl; // Show M / N

return 0;
}


The interviewer said this v2 code "partly" addressed the requirements. v1 didn't have the constructor (my error), and didn't deal with overflow of the int ivar.


What have I missed here to make this class robust/correct? I think it is some aspect of "industrial strength" that I've missed.


ps. for any ethical types, I've already submitted my second-chance attempt... It's just bothering me to know why this was "partly"...




Aucun commentaire:

Enregistrer un commentaire