Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.List;
- 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 String toString() {
- return "\nrow :: " + getRow() +
- "\ncol :: " + getCol() +
- "\nvalue :: " + getValue() + "\n";
- }
- }
- class SparseArray {
- private int numRows;
- private int numCols;
- private List<SparseArrayEntry> entries;
- public SparseArray() {
- entries = new ArrayList<SparseArrayEntry>();
- entries.add(new SparseArrayEntry(1, 4, 4));
- entries.add(new SparseArrayEntry(2, 0, 1));
- entries.add(new SparseArrayEntry(3, 1, -9));
- entries.add(new SparseArrayEntry(1, 1, 5));
- entries.add(new SparseArrayEntry(3, 2, 18));
- }
- public int getNumRows() {
- return numRows;
- }
- public int getNumCols() {
- return numCols;
- }
- public int getValueAt(int row, int col) {
- for (SparseArrayEntry entry : entries) {
- if (entry.getRow() == row && entry.getCol() == col)
- return entry.getValue();
- }
- return 0;
- }
- public void removeColumn(int col) {
- for (int i = 0; i < entries.size(); i++) {
- if (entries.get(i).getCol() == col) {
- entries.remove(i);
- i--;
- continue;
- }
- if (entries.get(i).getCol() > col)
- entries.set(i, new SparseArrayEntry(entries.get(i).getRow(), entries.get(i).getCol() - 1, entries.get(i).getValue()));
- }
- }
- public String toString() {
- return entries.toString().replaceAll("\\[", "").replaceAll("]", "").replaceAll(",", "");
- }
- }
- public class SparseArrayRunner {
- public static void main(String[] args) {
- SparseArray test = new SparseArray();
- System.out.println("entry at 3,1 is " + test.getValueAt(3, 1) + "\n");
- System.out.println("entry at 3,2 is " + test.getValueAt(3, 2) + "\n");
- test.removeColumn(1);
- System.out.println(test);
- System.out.println("entry at 3,1 is " + test.getValueAt(3, 1) + "\n");
- System.out.println("entry at 3,2 is " + test.getValueAt(3, 2) + "\n");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement