galoosh33
galoosh33

Reputation: 326

Create a List of Grid Points in Java

I'm trying to create a list of grid points in Java.

For example, for a 10x10 grid, this can be done very nicely in Python:

xv, yv = np.meshgrid(np.linspace(1, 10, 10), np.linspace(1, 10, 10))
grid = np.dstack((xv, yv)).reshape(-1, 2)

Result:

array([[  1.,   1.],
       [  2.,   1.],
       [  3.,   1.],
       ..., 
       [  8.,  10.],
       [  9.,  10.],
       [ 10.,  10.]])

How could this be done efficiently in "pure" Java?

Upvotes: 0

Views: 1627

Answers (3)

BackSlash
BackSlash

Reputation: 22233

One way would be with plain arrays:

int[][] array = new int[100][];

for(int i = 0; i < array.length; i++) {
    array[i] = new int[] {i % 10 + 1, i / 10 + 1};
}

You might want to change int[][] array = new int[100][]; to double[][] array = new double[100][];.

Tested your python code, this code gives the exact same output.

DEMO

Upvotes: 2

Deepesh Choudhary
Deepesh Choudhary

Reputation: 677

int x = 1;
for(in i = 0; i < numbers.length; i++){
    for(int j = 0; j < numbers[0].length; j++){
        numbers[i][j] = x;
        x++;
    }
}

Upvotes: -1

OldCurmudgeon
OldCurmudgeon

Reputation: 65793

If you don't need to modify the list after generation you could do it much more efficiently using an object.

class GridPoints {
    private final int size;

    public GridPoints(int size) {
        this.size = size;
    }

    public int[] get(int i) {
        return new int[] {
                (i % size) + 1,
                (i / size) + 1
        };
    }
}

public void test() {
    GridPoints g = new GridPoints(10);
    for ( int i = 0; i < 100; i++) {
        System.out.println(Arrays.toString(g.get(i)));
    }
}

Upvotes: 1

Related Questions