【发布时间】:2016-11-07 19:27:55
【问题描述】:
我有一个mainFun,它接受四个参数x、a、b 和c,它们都是向量值并且可能具有不同的长度。这个函数调用expensiveFun 计算量很大,所以我想减少对expensiveFun 的调用次数。需要为x[i]、a[i]、b[i]、c[i] 中的每个值调用此函数,如果a、b 或c 的长度较短,则它们需要为 "包裹”(它们的索引以 a[i % a.size()] 为模)。最好为 x 的每个可能的不同值(即所有整数 0,...,max(x))预先计算 expensiveFun,然后将输出 out 填入 out[i] = precomputedValues[x[i]] .如果a、b 和c 具有相同的长度(下面的示例),这可以很容易地实现,但如果它们不是,它会变得很难看。当参数向量的长度不同时,有什么方法可以提高效率?
下面我提供了一个可重现的例子。这是一个简化的代码,仅作为示例编写。
std::vector<int> expensiveFun(int x, int a, int b, int c) {
std::vector<int> out(x+1);
out[0] = a+b*c;
for (int i = 1; i <= x; i++)
out[i] = out[i-1] * i + a * (b+c);
return out;
}
std::vector<int> mainFun(
std::vector<int> x,
std::vector<int> a,
std::vector<int> b,
std::vector<int> c
) {
int n = x.size();
int a_size = a.size();
int b_size = b.size();
int c_size = c.size();
std::vector<int> out(n);
// easy
if (a_size == b_size && b_size == a_size) {
int max_x = 0;
for (int j = 0; j < n; j++)
if (x[j] > max_x)
max_x = x[j];
for (int i = 0; i < a_size; i++) {
int max_x = 0;
for (int j = 0; j < n; j += a_size) {
if (x[j] > max_x)
max_x = x[j];
}
std::vector<int> precomputedValues = expensiveFun(max_x, a[i], b[i], c[i]);
for (int j = i; j < n; j += a_size) {
out[j] = precomputedValues[x[j]];
}
}
// otherwise give up
} else {
for (int j = 0; j < n; j++) {
out[j] = expensiveFun(x[j], a[j % a_size], c[j % c_size], c[j % c_size]).back();
}
}
return out;
}
示例输入:
x = {0, 1, 5, 3, 2, 1, 0, 4, 4, 2, 3, 4, 1}
a = {1, 2, 3}
b = {1, 2}
c = {3, 4, 5, 6}
参数应该被折叠成:
x = {0, 1, 5, 3, 2, 1, 0, 4, 4, 2, 3, 4, 1}
a = {1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1}
b = {1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1}
c = {3, 4, 5, 6, 3, 4, 5, 6, 3, 4, 5, 6, 3}
目前输出并不重要,因为这里的主要问题是关于有效处理可变大小的参数向量。
【问题讨论】:
-
如果
a_size == b_size成立,通常b_size == a_size也成立:-P 也许你的意思是c_size? -
@j_random_hacker 确实是我的意思。
标签: c++ algorithm performance combinatorics