嗯,分析模式需要一些时间。
当然,我首先使用http://www.onlineocr.net/ 来从屏幕截图中获取文本。然后我开始匹配突出显示以发现模式。
- 您可以看到
make_cube 有效地占用了两个(x,y,z) 元组
- 三个组或行以相同的
z 值结尾
- 这三个组由三个以相同
(y,z) 元组结尾的子组组成
- x、y 和 z 值为每个组枚举相同的值对。
这使它成为生成循环的“明显”材料。经过大约 20 分钟的重构后,我终于到了
for (auto&& zs : { tie(rmin_z, imin_z), tie(imin_z, imax_z), tie(imax_z, rmax_z) })
for (auto&& ys : { tie(rmin_y, imin_y), tie(imin_y, imax_y), tie(imax_y, rmax_y) })
for (auto&& xs : { tie(rmin_x, imin_x), tie(imin_x, imax_x), tie(imax_x, rmax_x) })
{
*out++ = make_cube(get<0>(xs), get<0>(ys), get<0>(zs), get<1>(xs), get<1>(ys), get<1>(zs));
}
但您会注意到循环范围的规律性。实际上我们有一个类似的序列
coord const sequence[] = { rmin, imin, imax, rmax };
我们选择连续的对:(rmin, imin), (imin, imax), (imax, rmax)
// we take all consecutive pairs (warning: ignoring the `(rmax, rmin)` closing pair here)
vector<pair<coord, coord>> pairs;
transform(begin(sequence), prev(end(sequence)), back_inserter(pairs), [](coord const& it) { return std::make_pair(*(&it+0), *(&it+1)); });
现在我们可以更直接地循环它。我还发明了一个简单的Cube 类型,它允许我们漂亮地打印生成器循环的结果,以便您可以在DEBUG 模式下验证结果:
for (auto zs : pairs) for (auto ys : pairs) for (auto xs : pairs)
*out++ = Cube { { xs.first.x, ys.first.y, zs.first.z }, { xs.second.x, ys.second.y, zs.second.z } };
Live On Coliru
#include <iostream>
#include <algorithm>
#include <vector>
#include <array>
int main() {
#ifdef NDEBUG
typedef double T;
struct coord { T x,y,z; };
coord rmin { 0, 1, 2 },
imin { 3, 4, 5 },
imax { 6, 7, 8 },
rmax { 9, 10, 11 };
#else
typedef const char* T;
struct coord { T x,y,z; };
coord rmin { "rmin_x", "rmin_y", "rmin_z" },
imin { "imin_x", "imin_y", "imin_z" },
imax { "imax_x", "imax_y", "imax_z" },
rmax { "rmax_x", "rmax_y", "rmax_z" };
#endif
using namespace std;
// the source sequence
coord const sequence[] = { rmin, imin, imax, rmax };
// we take all consecutive pairs (warning: ignoring the `(rmax, rmin)` closing pair here)
vector<pair<coord, coord>> pairs;
transform(begin(sequence), prev(end(sequence)), back_inserter(pairs), [](coord const& it) { return std::make_pair(*(&it+0), *(&it+1)); });
// Now we build cubes. The `make_cube` interface implied it requires two
// coordinates to be constructed:
struct Cube { coord p1, p2; };
std::array<Cube, 3*3*3> cubes;
// generate!
auto out = cubes.begin();
for (auto zs : pairs) for (auto ys : pairs) for (auto xs : pairs)
*out++ = Cube { { xs.first.x, ys.first.y, zs.first.z }, { xs.second.x, ys.second.y, zs.second.z } };
// debug print
for(auto const& c : cubes)
std::cout << "make_cube(" << c.p1.x << ", " << c.p1.y << ", " << c.p1.z << ", " << c.p2.x << ", " << c.p2.y << ", " << c.p2.z << ")\n";
}
结论:
- 我的代码看起来更复杂。它可能是。但是查看是否有错别字要容易得多
-
关于问题
这真的有问题吗?
好吧,让我们这样说吧。上面的代码也可能是错误的
确实,我有点怀疑您是否涵盖了所有案件。见第一条评论:
// we take all consecutive pairs (warning: ignoring the `(rmax, rmin)` closing pair here)