0

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.

1
  • 1
    Concerning your last paragraph: You get the grid size N in your class with id.length. Commented Aug 22, 2012 at 5:21

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Ben. I knew that much, but my problem was getting the grid size as halex mentioned.
1

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

1 Comment

I can't believe it was so simple! Thanks again!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.