c# - C#中的滑动窗口算法

标签 c# algorithm c#-3.0 sliding-window

我正在尝试在 C# 3.0 中的二维数组上实现简单的滑动窗口算法, 我发现this非常有用,但它只涉及一维数组。

The post还包括算法的代码,我完全无法将它用于我的场景...任何人都可以建议我如何继续吗?

场景:

http://parasu516.googlepages.com/matrix.jpg
(来源:googlepages.com)

上面的图像是 10X10 矩阵,需要使用任何算法得到 3X3 矩阵(滑动窗口会很棒)。红色矩形是第一组,绿色矩形是第二组。它会一直持续到所有行结束

PS:我用谷歌搜索了该算法,但没有运气:(

最佳答案

简单的实现:

private static IEnumerable<T[,]> GetWindows<T>(
    T[,] array,
    int windowWidth,
    int windowHeight)
{
    for (var y = 0; y < array.GetLength(1) - windowHeight + 1; y++)
    {
        for (var x = 0; x < array.GetLength(0) - windowWidth + 1; x++)
        {
            var slice = new T[windowWidth, windowHeight];
            CopyArray(array, x, y, slice, 0, 0, windowWidth, windowHeight);
            yield return slice;
        }
    }
}

在二维数组之间复制的辅助方法:

private static void CopyArray<T>(
    T[,] src, int srcX, int srcY,
    T[,] dst, int dstX, int dstY,
    int width, int height)
{
    for (var x = 0; x < width; x++)
    {
        for (var y = 0; y < height; y++)
        {
            dst[dstX + x, dstY + y] = src[srcX + x, srcY + y];
        }
    }
}

测试主要:

private static void Main(string[] args)
{
    var array = new string[5, 5];
    for (var y = 0; y < array.GetLength(1); y++)
    {
        for (var x = 0; x < array.GetLength(0); x++)
        {
            array[x, y] = string.Format("({0}|{1})", x, y);
        }
    }
    foreach (var window in GetWindows(array, 3, 3))
    {
        ShowArray(window);
    }
    Console.ReadLine();
}

private static void ShowArray<T>(T[,] array)
{
    for (var x = 0; x < array.GetLength(0); x++)
    {
        for (var y = 0; y < array.GetLength(1); y++)
        {
            Console.Write("    {0}", array[x, y]);
        }
        Console.WriteLine();
    }
    Console.WriteLine();
}

输出:

(0|0)    (0|1)    (0|2)
(1|0)    (1|1)    (1|2)
(2|0)    (2|1)    (2|2)

(1|0)    (1|1)    (1|2)
(2|0)    (2|1)    (2|2)
(3|0)    (3|1)    (3|2)

(2|0)    (2|1)    (2|2)
(3|0)    (3|1)    (3|2)
(4|0)    (4|1)    (4|2)

(0|1)    (0|2)    (0|3)
(1|1)    (1|2)    (1|3)
(2|1)    (2|2)    (2|3)

(1|1)    (1|2)    (1|3)
(2|1)    (2|2)    (2|3)
(3|1)    (3|2)    (3|3)

(2|1)    (2|2)    (2|3)
(3|1)    (3|2)    (3|3)
(4|1)    (4|2)    (4|3)

(0|2)    (0|3)    (0|4)
(1|2)    (1|3)    (1|4)
(2|2)    (2|3)    (2|4)

(1|2)    (1|3)    (1|4)
(2|2)    (2|3)    (2|4)
(3|2)    (3|3)    (3|4)

(2|2)    (2|3)    (2|4)
(3|2)    (3|3)    (3|4)
(4|2)    (4|3)    (4|4)

现在您所要做的就是应用该博客文章中所示的相同技术:)

关于c# - C#中的滑动窗口算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1187028/

相关文章:

c# - jQuery/ajax POST 一个数组/对象到后面的 C# 代码

c# - 在windows phone项目中使用可移植类库

algorithm - 一小部分输入的比较排序下限?

c# - 如何动态分配集合中的属性

c# - 在 using block 内捕获异常与在 using block 外捕获异常 - 哪个更好?

c# - 在运行时向 GroupBox 添加控件

c# - VS C# 与 VB 中的变量作用域

algorithm - 如何找出算法的最佳时间复杂度?

javascript - 超出合并排序调用堆栈

c# - 有没有好的解析C#3.0代码的方法?