【C#】数组转置

【需求】

现有一个需求,3行4列的从左到右从上到下的数组,转成4行3列,如图所示:

 【实现方法】

通过C#编码实现,两种方法:

第一种方法:

 public double[] transpose(double[] src, int w, int h)
 {
     double[] dst = null;
     if (src == null || src.Length != w * h || w == 0 || h == 0)
     {
         return dst;
     }
     dst = new double[w * h];
     for (int yy = 0; yy < h; yy++)
     {
         for (int xx = 0; xx < w; xx++)
         {
             dst[xx * h + yy] = src[yy * w + xx];
         }
     }
     return dst;
 }

 

第二种方法,通过指针实现:

public double[] transpose2(double[] src, int w, int h)
{
    double[] dst = null;
    if (src == null || src.Length != w * h || w == 0 || h == 0)
    {
        return dst;
    }
    dst = new double[w * h];
    unsafe
    {
        fixed (double* srcInptr = src)
        {
            double* psrc = srcInptr;
            fixed (double* dstInptr = dst)
            {
                for (int yy = 0; yy < h; yy++)
                {
                    double* pdst = dstInptr + yy;
                    for (int xx = 0; xx < w; xx++, ++psrc, pdst += h)
                    {
                        *pdst = *psrc;
                    }
                }
            }
        }
    }
    return dst;
}

 

【实现效果】

输入数组{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12},输出转置后的数组{1,5,9,2,6,10,3,7,11,4,8,12}

 

 

posted @ 2024-08-27 14:42  春天花会开,  阅读(146)  评论(0)    收藏  举报