Question

This question solves half of my problem because my sliding window can move outside the table, e.g. for 3x3 window, two columns of the window can be on the left end of the table and one column will be on the right end. These images show window moving to the left

enter image description here enter image description here enter image description here

I need algorithm for this sliding window, sliding window in the mentioned question doesn't move outside the table.

Was it helpful?

Solution

You can use the modulo operation (%) in order to confine the indexes.

Size arraySize = new Size(20, 15);
Size windowSize = new Size(3, 3);

double[,] array = new double[arraySize.Width, arraySize.Height];

// Set the location of the window
Point windowLocation = new Point(18, 14);

for (int x = 0; x < windowSize.Width; x++) {
    for (int y = 0; y < windowSize.Height; y++) {
        DoSomethingWith(array[(windowLocation.X + x) % arraySize.Width,
                              (windowLocation.Y + y) % arraySize.Height]);
    }
}

OTHER TIPS

I would create an adapter around your 2D object, which intercepts requested window position, consults the underlying 2D object, and returns an appropriately constructed result. This way you may use any underlying implementation (like the one you linked to) and get the desired result.

Think in terms of the following pseudo-code:

View getView(int leftX, int topY) {
    if (leftX >= 0 and
        topY >= 0 and
        leftX <= underlying.width() - viewWidth and
        topX <= underlying.height() - viewHeight)
    {
        return underlying.getView(leftX, topY);
    }
    // else make your own view and populate it
    View view = new View()
    for (int i = 0; i < viewWidth; ++i)
        for (int j = 0; j < viewHeight; ++j)
            view.set(i, j) = underlying.get((leftX + i) % underlying.width(), (topY + j) % underlying.height())
}

If you end up using this code, make sure that negative indices modulo something gives a positive result. If not, use viewWidth - negative_modulo to get the right index.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top