我想将三维向量vec3
的维度x,y和z移动数字n。
vec3 shift(int n, vec3 vector);
如何改进算法以获得最佳性能并简化逻辑?我想这个任务有一个共同的方法,是吗?
vec3 shift(int Dimension, vec3 Vector)
{
float in[3] = { Vector.x, Vector.y, Vector.z };
float out[3];
for(int i = 0; i < 3; ++i)
{
int n = i + Dimension;
while(n > Dimension - 1) n -= Dimension;
out[i] = in[n];
}
return vec3(out[0], out[1], out[2]);
}
例如shift(2, vec3(12, 42, 30))
应该给我vec3(42, 30, 12)
。
答案 0 :(得分:2)
在你的情况下,你可以换2次,第三次是原来的。因此,我建议不要为2个不同的班次制作一个通用函数,而是建立两个更简单的函数。
vec3 shiftOnce(vec3 Vector)
{
return vec3(Vector.z, Vector.x, Vector.y);
}
vec3 shiftTwice(vec3 Vector)
{
return vec3(Vector.y, Vector.z, Vector.x);
}
这将更快更容易阅读。我不是代码重复的朋友,但在像这样的小案例中,它只是首选的解决方案。
如果您需要尺寸参数:
vec3 shift(int dimension, vec3 v)
{
if(dimension % 3 == 1) return vec3(v.z, v.x, v.y); // shift once
else if(dimension % 3 == 2) return vec3(v.y, v.z, v.x); // shift twice
else return v;
}
答案 1 :(得分:1)
您可以更多地优化算法:
// copy a reference of your vector, is better than copy all it´s components.
vec3 shift (int dimension, const vec3& Vector)
{
float in [3] = { Vector.x , Vector.y , Vector.z };
float out [3];
for (int i = 0; i < 3; i++)
out [ (i + dimension) % 3 ] = in [i];
return vec3 (out [0], out [1], out [2])
}
为了移动矢量分量,一种方法是获得除法的模块
在索引的总和加上维度值和
的维度之间
矢量,这是三个。
。 在你的情况下。 输入向量(in):12,42,30
维度:2
输出向量(out)
out [(0 + 2) % 3] = in [0] => out [2%3] = in [0] => out [2] = in [0]
z holds the value of the x component.
out [(1 + 2) % 3] = in [1] => out [3%3] = in [1] => out [0] = in [1]
x holds the value of the y component
out [(2 + 2) % 3] = in [2] => out [4%3] = in [2] => out [1] = in [2]
y holds the value of z component.
所以,输出向量必须是: 在[1],[2],[0] = vec3(42,30,12)
中