I am given a class and an interface, and I am asked to implement the interface:
public class Cell {
private int column;
private int row;
public int getColumn(){ return column;}
public void setColumn(int column){this.column = column;}
public int getRow(){return row;}
public void setRow(int row){this.row = row;}
}
public interface ITable {
void set(Cell cell, long value); //sets the value of the cell
long get(Cell cell); //gets the value of the cell
long sum(Cell fromCell, Cell toCell); //adds all the cell values between fromCell to toCell
long avg(Cell fromCell, Cell toCell); //computes average between the values of fromCell to toCell
}
Note: Range [fromCell:toCell]
means a rectangle with top left corner in fromCell
and right bottom corner in toCell
.
Limits:
Maximum column number is 1000
Maximum row number is 1000
Maximum number of non-empty cells is 1000
This is one of the interview questions, I couldn't solve it during the interview or after. I even asked the interviewer for the solution but he couldn't provide. I am very curious to see the solution to this question.
If A1 is 1, A2 is 2 and A3 is 3, then sum(A1,A3) = 6
The question is not asking you to add an object to a Cell. Cell objects are simply a way of holding row and column data. Any long values you want to retrieve will be stored in the new class you create.
For Example:
public class MyTable implements ITable {
long[][] table;
public MyTable(int r, int c) {
table = new long[r][c];
}
void set(Cell cell, long value) {
table[cell.getRow()][cell.getColumn()] = value;
}
long get(Cell cell) {
return table[cell.getRow()][cell.getColumn()];
}
long sum(Cell fromCell, Cell toCell) {
long sum = 0;
for(int r = fromCell.getRow(); r <= toCell.getRow(); r++) {
for(int c = fromCell.getColumn(); c <= toCell.getColumn(); c++) {
sum += table[r][c];
}
}
return sum;
}
long avg(Cell fromCell, Cell toCell) {
long num = 0;
long sum = 0;
for(int r = fromCell.getRow(); r <= toCell.getRow(); r++) {
for(int c = fromCell.getColumn(); c <= toCell.getColumn(); c++) {
sum += table[r][c];
num++;
}
}
return sum/num;
}
}