简体   繁体   English

添加类 Cell 的对象值

[英]Adding object values of the class Cell

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 .注意:范围[fromCell:toCell]表示一个矩形,左上角在fromCell ,右下角在toCell

Limits:限制:
Maximum column number is 1000最大列数为 1000
Maximum row number is 1000最大行数为 1000
Maximum number of non-empty cells is 1000非空单元格的最大数量为 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如果 A1 为 1,A2 为 2,A3 为 3,则 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;
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM