Removing a Column in Java from a 2D Array

Remove a Column from a 2D Array

An array is a container of data that occupies a contiguous block of memory, its size should be defined when the array is being instantiated and can't be changed.

If you need an array of smaller or greater length, then you need to create a new one and copy all previously added elements that should be retained.

There's also no such thing in Java as "2D" arrays, we can create a nested array, i.e. an array containing other arrays.

And similarly to how we can reassign an integer value at a particular index in a plain array int[], we can change a reference in the array of arrays, i.e. we can make it point to another (newly created) array.

And that's what is required according to do in your assignment since the method is void. I.e. the given array needs to be changed by replacing all of its "rows", that greater or equal in length than the given column to remove col, with a new array that will retain all the previous element except for the one at index col.

private static void removeEntry(int[][] workArray, int col) {

for (int row = 0; row < workArray.length; row++) {

if (workArray[row].length <= col) { // no need to change anything
continue;
}

int newLength = workArray[row].length - 1;
int[] newRow = new int[newLength]; // creating a new row shorter by 1

for (int oldCol = 0, newCol = 0; oldCol < workArray[row].length; oldCol++, newCol++) {
if (oldCol == col) { // skipping the target column
newCol--; // newCol would be incremented automatically at the end of the iteration, but we want it to remain the same
continue;
}
newRow[newCol] = workArray[row][oldCol];
}

workArray[row] = newRow; // reassigning the row
}
}

main()

public static void main(String[] args) {
int[][] testArr =
{{1, 2},
{1, 2, 3},
{1, 2, 3, 4}};

removeEntry(testArr, 2);

// printing the testArr
for (int[] arr: testArr) {
System.out.println(Arrays.toString(arr));
}
}

Output:

[1, 2]
[1, 2]
[1, 2, 4]

A link to the Online Demo

If you've made the method to be void by mistake, you are required to return a new array, i.e. the return type int[] (check the requirements of your assignment carefully). Then a minor change needs to be applied to the logic explained and implemented above: every array should be replaced with a new one and then placed into the newly created resulting array.

Note Arrays.copyOf() allows creating a duplicate of the hole array, and System.arraycopy() can help you to copy the elements in the given range from one array into another, but because you are working on an assignment I suggest you to do it manually with loops because you are expected to demonstrate the knowledge on how to manipulate with arrays, not the knowledge of special utility features (unless otherwise specified in the assignment).

private static int[][] removeEntry(int[][] workArray, int col) {
int[][] result = new int[workArray.length][];

for (int row = 0; row < workArray.length; row++) {

int newLength = col < workArray[row].length ? workArray[row].length - 1 : workArray[row].length;
int[] newRow = new int[newLength];

for (int oldCol = 0, newCol = 0; oldCol < workArray[row].length; oldCol++, newCol++) {
if (oldCol == col) {
newCol--;
continue;
}
newRow[newCol] = workArray[row][oldCol];
}

result[row] = newRow; // reassigning the row
}

return result;
}

main()

public static void main(String[] args) {
int[][] testArr =
{{1, 2},
{1, 2, 3},
{1, 2, 3, 4}};

int[][] newArr = removeEntry(testArr, 2);

// printing the testArr
for (int[] arr: newArr) {
System.out.println(Arrays.toString(arr));
}
}

Output:

[1, 2]
[1, 2]
[1, 2, 4]

A link to the Online Demo

How do I remove a specific row and a specific column from a 2D Array in Java?

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;
}
}

how to delete 2D array column in java

You cannot change the dimension of an existing Array data-structure unless you destroy and rebuild it with the new dimension (you have to re-initialize and re-populate).

You can try something like this.

public int[][] deleteColumn(int[][] args,int col)
{
int[][] nargs;
if(args != null && args.length > 0 && args[0].length > col)
{
nargs = new int[args.length][args[0].length-1];
for(int i=0; i<args.length; i++)
{
int newColIdx = 0;
for(int j=0; j<args[i].length; j++)
{
if(j != col)
{
nargs[i][newColIdx] = args[i][j];
newColIdx++;
}
}
}
}
return nargs;
}

How to Delete a specific Row and Col in a 2D array in Java?

You cannot change the dimension of an existing Array data-structure unless you destroy and rebuild it with the new dimension (you have to re-initialise and re-populate).

Edited :

 for(int i=1; i<checkVertex.size() + 2; i++)

Why +2 ? Is the new matrix bigger than the original ? Can't be.

Look at the end of this program to see how it can be done..Hope it helps.

    public static void main(String[] args) {

int rows=5;
int cols=5;
double[][] matrix = new double[rows][cols];

int counter =0;

for(int i=0; i<rows; i++)
for(int j=0; j<cols; j++){

matrix[i][j] = Math.random();
// counter++;
// System.out.println("First test ("+counter+") : " + matrix[i][j]);

}

//keep copy of original matrix
double[][] matrixCopy = matrix.clone();

//Assume
int rowToRemove = 2;
int colToRemove = 3;


// re-initialise matrix with dimension i-1 , j-1
matrix = new double[rows-1][cols-1];
counter = 0;

//row and column counter for the new matrix
int tmpX=-1;
int tmpY=-1;


//re-populate new matrix by searching through the original copy of matrix, while skipping useless row and column
// works only for 1 row and 1 column in a 2d array but by changing the conditional statement we can make it work for n number of rows or columns in a 2d array.
for(int i=0; i<rows; i++)
{
tmpX++;
if(i==rowToRemove){
tmpX--;
}
tmpY=-1;
for(int j=0; j<cols; j++){


tmpY++;
if(j==colToRemove){
tmpY--;
}

if(i!=colToRemove&&j!=colToRemove){
counter++;
matrix[tmpX][tmpY] = matrixCopy[i][j];

System.out.println(counter+" :"+matrix[tmpX][tmpY]);
}


}

}

How do I remove a row and a column from a jagged 2d array?

A bidimensional array, jagged or not, is more an array of array than anything else. You have to create each row by hand and thus, you can choose any size for each individual row.

import java.util.Arrays;

public class Temp {
public static void main(String[] args) {
int[][] jagged = {{1, 2, 3}, {4, 5, 6, 7, 8}, {9, 10, 11, 12, 13, 14, 15, 16}};
System.out.println("Jagged: " + Arrays.deepToString(jagged));
System.out.println("Smaller 1: " + Arrays.deepToString(removeRowAndCol(jagged, 0, 0)));
System.out.println("Smaller 2: " + Arrays.deepToString(removeRowAndCol(jagged, 1, 1)));
System.out.println("Smaller 3: " + Arrays.deepToString(removeRowAndCol(jagged, 2, 2)));
}

private static int[][] removeRowAndCol(int[][] jagged, int i, int j) {
int[][] smaller = new int[jagged.length - 1][];

// WARN: outofbounds checks are not implemented!
for (int smallerI = 0; smallerI < smaller.length; smallerI++) {
int sourcedI = smallerI;
if (smallerI >= i) {
sourcedI++;
}

smaller[smallerI] = new int[jagged[sourcedI].length - 1];

for (int smallerJ = 0; smallerJ < smaller[smallerI].length; smallerJ++) {
int sourcedJ = smallerJ;
if (smallerJ >= j) {
sourcedJ++;
}
smaller[smallerI][smallerJ] = jagged[sourcedI][sourcedJ];
}
}

return smaller;
}
}

Which outputs:

Jagged: [[1, 2, 3], [4, 5, 6, 7, 8], [9, 10, 11, 12, 13, 14, 15, 16]]
Smaller 1: [[5, 6, 7, 8], [10, 11, 12, 13, 14, 15, 16]]
Smaller 2: [[1, 3], [9, 11, 12, 13, 14, 15, 16]]
Smaller 3: [[1, 2], [4, 5, 7, 8]]

Removing a row matching a condition from a 2D array using for loop

Here's a simple method that turns rows into null values if the 4th column is smaller than priceLimit, you'll have an array with null values after calling the method, but you can look up here Remove Null Value from String array in java to figure out how to remove null values from the array.

    public static void main(String[] args) {
int lines = 4;
int columns = 4;
String[][] twoDArray = new String [lines][columns];
for (int i = 0; i < lines; i++) {
for (int j = 0; j < columns; j++) {
twoDArray[i][j] = "test";
}
}
twoDArray[0][3] = "5";
twoDArray[1][3] = "10";
twoDArray[2][3] = "15";
twoDArray[3][3] = "20";
System.out.println(Arrays.toString(twoDArray));
deleteMatchingRow(twoDArray, 16);
System.out.println(Arrays.toString(twoDArray));
}

public static void deleteMatchingRow (String[][] twoDArray, int priceLimit) {
for (int i = 0; i < twoDArray.length; i++) {
if (Integer.parseInt(twoDArray[i][3]) < priceLimit) {
twoDArray[i] = null;
}
}
}

Now regarding your exception java.lang.NumberFormatException you just have to make sure that in every row, the 4th column is indeed a parsable Integer and not a random String.
Notice how in the main method I filled all the two D array with "test" and then reassigned the 4th column of every row into String numbers so they can be parsed by Integer.parseInt()

Delete column and row of 2d Array after every iteration

Just summing up the comments to build a proper answer:

Instead of putting zeroes in the cells, maintain two Set's - usedRows and usedColumns - that keeps tracked of the rows and columns you've crossed out, and ship those using an extra if statement just before if(scores[i][j] >= max)

Remember to reset max in the beginning of each iteraton:

max = Float.MIN_VALUE


Related Topics



Leave a reply



Submit