Ci3
Ci3

Reputation: 4842

How to convert a 2D array to 1D array with the value as the index?

I have a 2D array that gets dynamically created by any integer N. Initially, I need to set all values in the array to a value that represents it being "uninitialized" where I use the number "-1". However, I want to convert this 2D array to a 1D array and assign every value to be equal to its index in the new 1D array.

public class Percolation {

private int[][] id;
private int[] array1D;
private int blocked = -1;   //a number that doesn't exist in the array

// create N-by-N grid, with all sites blocked
public Percolation(int N){

    id = new int[N][N];
    for (int k = 0; k < N; k++)
    { for (int i = 0; i < N; i++) id[k][i] = blocked; } 
}


// open site (row i, column j) if it is not already
public void open(int i, int j){


}

In the open method it should change the value at the given indexes to be the corresponding index in a 1D array. For example:

[-1] [-1]

[-1] [-1]

Would then become:

[0] [1] [2] [3]

Unfortunately, since this is homework I'm unsure how I can share the grid size "N" to be able to create a new 1D array with the indexes as the values.

Upvotes: 0

Views: 1267

Answers (3)

gdz
gdz

Reputation: 3

You could also have done something like that, considering N is a given parameter to your constructor:

public class Percolation {
     private int size;
     //...

    public Percolation(int N){
         size = N;
         //...    
    }
}

The scope of the variable is all your class. If you set it public, you could also access it with p.size, where p is an instance of Percolation

Upvotes: 0

halex
halex

Reputation: 16403

You get the grid size N in your class with id.length.

Upvotes: 1

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33864

Im not sure if this helps answer your question but the following algorithm is for indexing a one dimensional matrix that represents a two dimensional matrix:

colSize*row+col

where colSize is the max number of columns.

For example the following matrix:

 [0, 1, 2, 3;
  4, 5, 6, 7;
  8, 9, 10, 11]

so to access row 1 col 3 (ie 6 which is the index number can be found by:

3*1+3 = 6;

So you should be able to fill out your 1D matrix with just the number of columns and rows using this formula.

Upvotes: 2

Related Questions