4

If I have a method that accepts an int[][] , a row number to remove, and a column number to remove, how would I remove that specific row and column from the Array and return the new reduced Array?

I want to do it by taking everything except the row/column I want to remove and then putting it into two temporary ArrayLists, then constructing a new Array to return from the values in the two Arrays. I think I can remove a specific row just fine, however I don't know how to remove the column as well.

1
  • 1
    If I am understanding this right, couldn't you allocate a new array of size int[m-1][n-1], then iterate through the original, copying over elements but skipping the row/column you want to remove? Commented Nov 15, 2011 at 1:38

2 Answers 2

6

I think the best approach is create a new array of

int[xsize-1][ysize-1]

Have a nested for loop to copy from source array to destination. And skip for a specific i and j

static void TestFunction()
    {
        int rows = 5;
        int columns = 6;
        int sourcearr[][] = new int[rows][columns];
        int destinationarr[][] = new int[rows-1][columns-1];

        int REMOVE_ROW = 2;
        int REMOVE_COLUMN = 3;
        int p = 0;
        for( int i = 0; i < rows; ++i)
        {
            if ( i == REMOVE_ROW)
                continue;


            int q = 0;
            for( int j = 0; j < columns; ++j)
            {
                if ( j == REMOVE_COLUMN)
                    continue;

                destinationarr[p][q] = sourcearr[i][j];
                ++q;
            }

            ++p;
        }
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Seems good, however what is the purpose of the " sourcearr[i][j] = 10 * i + j;" line?
Just some test data.. nothing more... your sourcearr will have input data so please ignore it
do you need the p and q variables?
0

I'm trying to remove both 3 in two columns, under the index 2, how to achieve it?

public class For_petlja {

    public static void main(String[] args) {

        int[][] niz = {
            {9, 2, 3, 6, 7},
            {4, 7, 3, 5, 1}
        };
        int j;
        for (int i = 0; i < niz.length; i++) {
            for (j = 0; j < niz[i].length; j++) {
                if (i == 2) {
                    continue;
                }
            } // for 'j'
            System.out.println(Arrays.toString(niz[j]));
        } // for 'i'
    } // main method.
} // class

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.