我有一个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[i]=precomputedValues[x[i]]
填充输出out
。如果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