views:

1156

answers:

6

I have a simple array, sort of like this

1 2 3 4 5 6 7 8 9
6 2 7 2 9 6 8 10 5
2 6 4 7 8 4 3 2 5
9 8 7 5 9 7 4 1 10
5 3 6 8 2 7 3 7 2

So, let's call this matrix[5][9]. I wish to now remove every row within this matrix that contains a certain value, in this case 10, so I am left with...

1 2 3 4 5 6 7 8 9
2 6 4 7 8 4 3 2 5
5 3 6 8 2 7 3 7 2
+1  A: 

You can't remove elements from the Java built-in array data structure. You'll have to create a new array that has a length one less than the first array, and copy all the arrays into that array EXCEPT the one you want to remove.

Kaleb Brasee
As I'm using the Matrix class to pass a Matrix in there's no problem with simply taking one in and outputting a shorter Matrix. I'm just stuck on how I would go about "removing" that row from my new Matrix once I had found the value within a cell.
AlexT
+2  A: 

Use System.arraycopy or use java.util.List instead of arrays. ArrayList have fast access to random element and slow remove method, it's opposite with LinkedList. You have to choose for yourself.

EDIT:

Rant: I had to use bit.ly for this link, because stackoverflow sucks at its core buisness of parsing html with regexps (it chokes on this:

<a href="http://java.sun.com/j2se/1.4.2/docs/api/java/lang/System.html#arraycopy(java.lang.Object, int, java.lang.Object, int, int)">System.arraycopy</a>

Krzysiek Goj
I think you just have to put %20 for the spaces
Yishai
+1  A: 

Here's a sample class you can run that I believe does what you're looking for. Removing rows from 2D arrays is tricky business because like @KalebBrasee said, you can't really "remove" them, but rather you have to make a whole new 2D array instead. Hope this helps!

import java.util.ArrayList;
import java.util.List;


public class Matrix
{
    private double[][] data;

    public Matrix(double[][] data)
    {
        int r= data.length;
        int c= data[0].length;
        this.data= new double[r][c];
        for(int i = 0; i < r; i++) {
            for(int j = 0; j < c; j++) {
                    this.data[i][j] = data[i][j];
            }
        }
    }

    /* convenience method for getting a 
       string representation of matrix */
    public String toString()
    {
     StringBuilder sb = new StringBuilder(1024);
     for(double[] row : this.data)
     {
      for(double val : row)
      {
       sb.append(val);
       sb.append(" ");
      }
      sb.append("\n");
     }

     return(sb.toString());
    }

    public void removeRowsWithValue(final double value)
    {
            /* Use an array list to track of the rows we're going to want to 
               keep...arraylist makes it easy to grow dynamically so we don't 
               need to know up front how many rows we're keeping */
     List<double[]> rowsToKeep = new ArrayList<double[]>(this.data.length);
     for(double[] row : this.data)
     {
      /* If you download Apache Commons, it has built-in array search
                      methods so you don't have to write your own */
      boolean found = false;
      for(double testValue : row)
      {
                            /* Using == to compares doubles is generally a bad idea 
                               since they can be represented slightly off their actual
                               value in memory */
       if(Double.compare(value,testValue) == 0)
       {
        found = true;
        break;
       }
      }

                    /* if we didn't find our value in the current row, 
                      that must mean its a row we keep */
      if(!found)
      {
       rowsToKeep.add(row);
      }
     }

            /* now that we know what rows we want to keep, make our 
               new 2D array with only those rows */
     this.data = new double[rowsToKeep.size()][];
     for(int i=0; i < rowsToKeep.size(); i++)
     {
      this.data[i] = rowsToKeep.get(i);
     }
    }

    public static void main(String[] args)
    {
     double[][] test = { {1, 2, 3, 4, 5, 6, 7, 8, 9},
          {6, 2, 7, 2, 9, 6, 8, 10, 5},
          {2, 6, 4, 7, 8, 4, 3, 2, 5},
          {9, 8, 7, 5, 9, 7, 4, 1, 10},
          {5, 3, 6, 8, 2, 7, 3, 7, 2} };

            //make the original array and print it out       
     Matrix m = new Matrix(test);
     System.out.println(m);

            //remove rows with the value "10" and then reprint the array
     m.removeRowsWithValue(10);
     System.out.println(m);
    }
}
Brent Nash
I'm trying out the code now and I'm getting an ArrayIndexOutOfBoundsException when it hits a 10.
AlexT
I think I've figured out the problem. Is there any chance you could look at my edit to see if it can be resolved?
AlexT
It definitely runs ok as pasted in here, so I'll take a look at your edits.
Brent Nash
The problem was my show method not working, but I've replaced it with your toString method. It works, although it leaves a gap where the row was removed. Either way, thanks for your help!
AlexT
A: 

My take:

import java.util.Arrays;

public class RemoveArrayRow {
    private static <T> T[] concat(T[] a, T[] b) {
        final int alen = a.length;
        final int blen = b.length;

        if (alen == 0) {
            return b;
        }

        if (blen == 0) {
            return a;
        }

        final T[] result = (T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), alen + blen);

        System.arraycopy(a, 0, result, 0, alen);
        System.arraycopy(b, 0, result, alen, blen);

        return result;
    }

    public static void main(String[] args) {
        double[][] d  = { {11, 2, 3, 4, 5, 6, 7, 8, 9, 0},
                          {12, 2, 3, 4, 5, 6, 7, 8, 9, 1},
                          {13, 2, 3, 4, 5, 6, 7, 8, 9, 2},
                          {14, 2, 3, 4, 5, 6, 7, 8, 9, 3},
                          {15, 2, 3, 4, 5, 6, 7, 8, 9, 4} };

        //remove the fourth row:

        // (1)
        double[][] d1 = concat(Arrays.copyOf(d, 3), Arrays.copyOfRange(d, 4, 5));

        // (2)
        double[][] d2 = new double[d.length - 1][d[0].length];
        System.arraycopy(d, 0, d2, 0, 3);
        System.arraycopy(d, 4, d2, 3, 1);

        System.out.print(d1.length);
        System.out.print(d2.length);
    }
}

(1)
If you exclude the concat() function used for concatenating two arrays, it's done in one line:
double[][] d1 = concat(Arrays.copyOf(d, 3), Arrays.copyOfRange(d, 4, 5));
See this question as well. That's where the code for the concat() function comes from.

(2)
This method is faster and only uses already available functions.

Marius Burz
+1  A: 

At the and you have to recreate the array and discard the old one. Changing the dimension of an existing array is not possible - if want this type of datastructure, then you should build the matrix based on Collections (ArrayList<ArrayList<Double>>), there you can remove a row easily.

Back to arrays - the idea is to collect all rows (double[] arrays) that you want to keep, create a result array with those rows and replace the old one with the new on on Matrix:

public void doSomethingWith(Matrix in) {
  List<double[]> survivingRows = new ArrayList<double[]>();
  for (double[] row:in.getRows()) {
    if (isAGoodOne(row)) {
      survivingRows.add(row);
    }
  }

  double[][] result = new double[survivingRows][];
  for (int i = 0; i < result.length; i++) {
    result[i] = survivingRows.get(i);
  }
  in.setArray(result);
}
Andreas_D
A: 

My java syntax is a little rusty, but the following, if treated as pseudocode will work

public Matrix removeRows(Matrix input) {
    int[][] output = new int[input.numRows][input.numColumns]();
    int i = 0;
    for (int[] row : input.rows()) {      // Matrix.rows() is a method that returns an array of all the rows in the matrix
        if (!row.contains(10)) {
            output[i] = row;
        }
    }
    return output
inspectorG4dget