自从我使用C++已经有一段时间了。我被要求进行面试,以为降采样例程创建一个C++结构,该结构应满足以下接口(interface):

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

-具有以下行为:
  • 我们有一个此类的对象:deterministic_sample s;
  • 我们调用s() N次,并返回true M次。 M / N大致等于
  • 序列是确定性的,不是随机的,每次
  • 都应相同
  • 该类应为“工业强度”,以便在繁忙的流中使用。

  • 我的解决方案,版本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;
    }
    

    面试官说,此v2代码“部分”满足了要求。 v1没有构造函数(我的错误),并且没有处理int ivar的溢出。

    我在这里错过了什么使该类(class)更强大/更正确? 我认为这是我错过的“工业实力”的某些方面。

    ps。对于任何道德类型,我都已经提交了第二次尝试...只是让我不知道为什么这是“部分的” ...

    最佳答案

    您拥有的东西比必要的要复杂得多。您需要做的就是跟踪当前位置,并在超过阈值时返回true

    struct deterministic_sample
    {
        double sampRate;
        double position;
    
        deterministic_sample() : sampRate(0.1), position(0.0) {
        }
    
        void deterministic_rate( double rate ) {
            assert(rate <= 1.0); // Only one output is allowed per input
            sampRate = rate;  // Set the ivar. Not so necessary to hide data, but just complying with the interface, as given...
            // No need to reset the position, it will work with changing rates
        };
    
        bool operator()() {
            position += sampRate;
            if (position < 1.0)
                return false;
            position -= 1.0;
            return true;
        }
    };
    

    08-03 18:42
    查看更多