public class SparseArrayEntry {
private int row;
private int col;
private int value;
public SparseArrayEntry(int r, int c, int v) {
row = r;
col = c;
value = v;
}
public int getRow() {
return row;
}
public int getCol() {
return col;
}
public int getValue() {
return value;
}
}
public class SparseArray {
private int numRows;
private int numCols;
private List<SparseArrayEntry> entries;
public SparseArray(){
entries = new ArrayList<SparseArrayEntry>();
}
public int getNumRows(){
return numRows;
}
public int getNumCols(){
return numCols;
}
public void setNumRows(int numRows) {
this.numRows = numRows;
}
public void setNumCols(int numCols) {
this.numCols = numCols;
}
public void addEntry(SparseArrayEntry entry) {
entries.add(entry);
}
// Part A
public int getValueAt(int row, int col)
{
for(SparseArrayEntry entry : entries)
if(entry.getRow() == row && entry.getCol() == col)
return entry.getValue();
return 0;
}
// Part B
public void removeColumn(int col) {
for(int i = entries.size() - 1; i >= 0; i--) {
SparseArrayEntry entry = entries.get(i);
if(entry.getCol() == col)
entries.remove(i);
else if(entry.getCol() > col)
entries.set(i, new SparseArrayEntry(
entry.getRow(), entry.getCol() - 1, entry.getValue()));
}
numCols--;
}
public static void main(String[] args) {
SparseArray sparse = new SparseArray();
sparse.setNumRows(4);
sparse.setNumCols(4);
sparse.addEntry(
new SparseArrayEntry(0, 1, 1)
);
sparse.addEntry(
new SparseArrayEntry(1, 2, 2)
);
sparse.addEntry(
new SparseArrayEntry(2, 3, 3)
);
sparse.addEntry(
new SparseArrayEntry(3, 1, -9)
);
System.out.println("Value at (3,1) before removing column: " + sparse.getValueAt(3, 1));
System.out.println("Value at (2,3) before removing column: " + sparse.getValueAt(2, 3));
System.out.println("Number of columns before removing one: " + sparse.getNumCols());
sparse.removeColumn(1);
System.out.println("Value at (3,0) after removing column: " + sparse.getValueAt(3, 0));
System.out.println("Value at (2,2) after removing column: " + sparse.getValueAt(2, 2));
System.out.println("Number of columns after removing one: " + sparse.getNumCols());
}
}
SparseArray.main(null)