Other 2015 FR Questions FR other years Be Prepared Home
A-3
Part (a)
  public int getValueAt(int row, int col)
  {
    for (SparseArrayEntry e : entries)
      if (e.getRow() == row && e.getCol() == col)
        return e.getValue();
    return 0;
  }


Part (b)
  public void removeColumn(int col)
  {
    int i = 0;
    
    while (i < entries.size())
    {
      SparseArrayEntry e = entries.get(i);
      int c = e.getCol();
      if (c == col)
        entries.remove(i);
      else
      {
        if (c > col)
          entries.set(i, new SparseArrayEntry(e.getRow(), c-1, e.getValue()));
        i++;
      }
    }
    numCols--;
  } 1 
Notes:
  1. Alternative solution:
      public void removeColumn(int col)
      {
        for (int i = entries.size() - 1; i >= 0; i--)
        {
          SparseArrayEntry e = entries.get(i);
          int c = e.getCol();
          if (c == col)
            entries.remove(i);
          else if (c > col)
              entries.set(i, new SparseArrayEntry(e.getRow(), c-1, e.getValue()));
        }
        numCols--;
      }

Other 2015 FR Questions | Back to Contents

Copyright © 2015 by Skylight Publishing
support@skylit.com