- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我已经有一段时间没有使用 C++ 了。我被要求参加工作面试,为满足以下接口(interface)的下采样例程创建 C++ 结构:
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)健壮/正确?我认为这是我错过的“工业实力”的某些方面。
附言。对于任何道德类型,我已经提交了我的第二次机会尝试......我只是很困扰知道为什么这是“部分”......
最佳答案
您所拥有的远比必要的复杂。您需要做的就是跟踪当前位置,并在超过阈值时返回 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;
}
};
关于c++ - "Industrial Strength"C++ 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28754041/
我已经有一段时间没有使用 C++ 了。我被要求参加工作面试,为满足以下接口(interface)的下采样例程创建 C++ 结构: struct deterministic_sample {
关闭。这个问题是opinion-based .它目前不接受答案。 想改进这个问题?更新问题,以便 editing this post 可以用事实和引用来回答它. 3年前关闭。 Improve this
我在 Orchard CMS 上跌跌撞撞,想覆盖 Vandelay Industries 的 RemoteRSS 小部件的默认模板。当前模板位于: ~/Modules/Vandelay.Industr
我正在阅读 Google 的测试博客 entry about how Google partitions its tests into small, medium, and large tests ,
我无法通过 r_fullprofile 权限从 linkedIn 获取 'bio'、'bio'、'industry'、'professional headline' 和 'number of conn
我是一名优秀的程序员,十分优秀!