映射向量

时间:2010-06-14 21:36:34

标签: c# vector mapping

有没有一种很好的方法来映射矢量?这是我的意思的一个例子:

vec0 = [0,0,0,0,0,0,0,0,0,0,0]
vec1 = [1,4,2,7,3,2]
vec2 = [0,0,0,0,0,0,0,0,0]
vec2 = [7,2,7,9,9,6,1,0,4]
vec4 = [0,0,0,0,0,0]

mainvec =
[0,0,0,0,0,0,0,0,0,0,0,1,4,2,7,3,2,0,0,0,0,0,0,0,0,0,7,2,7,9,9,6,1,0,4,0,0,0,0,0,0]

让我们说mainvec不存在(我只是向你展示,所以你可以看到一般的数据结构。

现在说我想要mainvec(12)将是4.有没有一种很好的方法来映射这些向量的调用而不必将它们拼接成一个mainvec?我意识到我可以制作一堆if语句来测试mainvec的索引,然后我可以根据调用在其中一个向量中的位置来偏移每个调用,例如:

mainvec(12) = vec1(1)

我能做到:

mainvec(index)
if (index >=13)
    vect1(index-11);

我想知道在没有if语句的情况下是否有一种简洁的方法。有任何想法吗?

4 个答案:

答案 0 :(得分:1)

我会使用锯齿状数组。

你仍然需要一个循环,但你可以保持单独的向量没有冗余:

var mainvec = new int[][]{vec0, vec1, vec2, vec3, vec4};

int desiredInd = 12, totalInd = 0, rowInd = 0, result;

while(rowInd < mainvec.Length && (totalInd + mainvec[rowInd].Length) <= desiredInd)
{ 
    totalInd += mainvec[rowInd++].Length;
}

if(rowInd < mainvec.Length && (desiredInd - totalInd) < mainvec[rowInd].Length)
{
  result = mainvec[rowInd][desiredInd - totalInd];
}

答案 1 :(得分:1)

我会创建一个接收数组长度的类,并且有一个方法可以为组合列表中给定索引的数组提供数组和索引。

它将被一个类包装,该类将获得对实际数组的引用,并使用索引器将您带到正确的元素。

答案 2 :(得分:1)

看起来你在做基本列表连接,在这种情况下,Concat函数似乎是最直接的做事方式。在实际代码术语中,有些像:

var vec0 = new[] {0,0,0,0,0,0,0,0,0,0,0};
var vec1 = new[] {1,4,2,7,3,2};
var vec2 = new[] {0,0,0,0,0,0,0,0,0}; 
var vec3 = new[] {7,2,7,9,9,6,1,0,4};
var vec4 = new[] { 0, 0, 0, 0, 0, 0 };

var mainvec = vec0.Concat(vec1).Concat(vec2).Concat(vec3).Concat(vec4).ToList();
mainvec[12] == 1;

我不太确定你想做什么背后的背景,所以可能有更直接的做事方式,但根据你所拥有的,这对我来说似乎是最简单的。

答案 3 :(得分:1)

你在找这样的东西吗?

using System.Collections.Generic;
namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] vec0 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            int[] vec1 = { 1, 4, 2, 7, 3, 2 };
            int[] vec2 = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            int[] vec3 = { 7, 2, 7, 9, 9, 6, 1, 0, 4 };
            int[] vec4 = { 0, 0, 0, 0, 0, 0 };
            List<int> temp = new List<int>();
            temp.AddRange(vec0);
            temp.AddRange(vec1);
            temp.AddRange(vec2);
            temp.AddRange(vec3);
            temp.AddRange(vec4);
            int[] mainvec = temp.ToArray();
        }
    }
}