turbo
turbo

Reputation: 589

Data structure design for 2D matrix

I have one 2D matrix. My problem requires me to logically divide it into 4 sub-matrices. e.g if my original matrix is 4*4 then there are 4 sub-matrices of 2*2. one starts at (0,0) other are (0,2), (2,0) and (2,2) index of original matrix. I am accessing and setting values many times during program. I want to access the sub-matrix element by something like matrix[x][y].at(row,col) where x,y specify sub-matrix number and row,col denote element withing that sub-matrix at(row,col). e.g matrix[2][2].at[0][0] --> should give first element in 4th sub-matrix.

Any help is deeply appreciated.

Thanks in Advance

Upvotes: 1

Views: 622

Answers (2)

alphazero
alphazero

Reputation: 27234

I'm not sure what the issue is here. Basically you just want a pseudo semantic api for addressing elements of a 2-d matrix. You note (presumed random) reads and writes to array. We'll assume you are not dealing with threading issues.

A 2-dim array of type Foo, Foo[][], certainly can work. You just basically need to wrap it.

public class Matrix<T> {
    public interface Quadrant<T> {
        T get(int i, int j);
        void set(T v, int i, int j);
    }
    public static final int XDIM = 4;
    public static final int YDIM = 4;
    private final Object[][] matrix = new Object[XDIM][YDIM];
    public Matrix() { /* .. */ }
    public Quadrant<T> quadrant(final int x, final int y) {
        return new Quadrant<T> () {
            @SuppressWarnings("unchecked")
            @Override public final T get(int i, int j) {
                return (T) matrix [x+i][y+j]; // todo: range checks, etc.
            }
            @Override public final void set(T v, int i, int j) {
                matrix [x+i][y+j] = v; // todo: range checks, etc.
            }
        };
    }
    public static void main(String[] args) {
        Matrix<Object> m = new Matrix<Object>();
        m.quadrant(2, 2).set("hi there!", 0, 1);
        System.out.format("{%d, %d}:(%d, %d) => %s\n", 2, 2, 0, 1, m.quadrant(2, 2).get(0, 1));
    }
}

Upvotes: 1

Cybercartel
Cybercartel

Reputation: 12592

You want to look in space-filling-curves. A sfc reduces the 2d complexity to a 1d complexity. It can help to understand a quadtree and also it can be used like a quadtree. You want to look into Nick's hilbert curve quadtree spatial index blog.

Upvotes: 0

Related Questions