예제 #1
0
// Perform the precomputation step here
GridSum::GridSum (TwoD_Array<int>& grid) {
    // TODO
    int left;
    int top;
    int topLeft;
    //TwoD_Array<int> grid(size, size);
    pg = new TwoD_Array<int>(grid.getNumRows(),grid.getNumCols());
    pg->at(0,0) = grid.at(0,0);    //initialize (0,0) to the grid(0,0)

    for(int i = 0; i < grid.getNumRows(); i++){
        for(int j = 0; j < grid.getNumCols(); j++){
            if(i == 0 && j ==0){    //special case, already handled
                continue;
            }
            else if(j == 0){
                left = 0;            //LEFT IS EMPTY
                top = pg->at(i-1,j);
                topLeft = 0;
            }
            else if(i == 0){
                top = 0;            //TOP IS EMPTY
                left = pg->at(i,j-1);   
                topLeft = 0;
            }
            else{
                left = pg->at(i,j-1);  
                top = pg->at(i-1,j);
                topLeft = pg->at(i-1,j-1);
            }
            pg->at(i,j) = grid.at(i,j) + left + top - topLeft;
        }
    }
}
예제 #2
0
// Perform the precomputation step here
GridSum::GridSum (TwoD_Array<int>& grid) {
    // TODO

	//calculate N size for the matrix 
    int N = grid.getNumRows();

    //Initilize the 2D array for pre-computation 
    pg = new TwoD_Array<int> (N,N);
	
	int row = grid.getNumRows();
    int col = grid.getNumCols();


    pg->at(0,0) = grid.at(0,0);

    for(int i = 0; i < row; i++){
    	for(int j = 0; j < col; j ++){

            if(i == 0 && j == 0) continue;

    		//handle the first row
    		if(!hasAboveElement(i)){
    			//if no above, just add left 
    			pg->at(i,j) = grid.at(i,j) + pg->at(i,j-1);
    		}

    		if(!hasLeftElement(j)) {
    			//if no left just add above 
    			pg->at(i,j) = grid.at(i,j) + pg->at(i-1,j);
    		}

    		//set the current cordiation as the sum of current and the one above
    		if(hasAboveElement(i) && hasLeftElement(j)) {    			
    			pg->at(i,j) = pg->at(i-1,j) + pg->at(i,j-1) - pg->at(i-1,j-1) + grid.at(i,j);
    		}
    		
    	}
    }

    //pg->printOut();

}
// Perform the precomputation step here
// Compute sum for (0, 0) to (n, m)
GridSum::GridSum (TwoD_Array<int>& grid) {
    // TODO
    int colSum = 0;
    pg = new TwoD_Array<int>(grid.getNumRows(), grid.getNumCols());
    pg->at(0, 0) = grid.at(0, 0);

    //first row of sum aray
    for(int col = 1; col < grid.getNumCols(); col++) {
        pg->at(0, col) = pg->at(0, col - 1) + grid.at(0, col);
    }

    //first colomn of sum array
    for(int row = 1; row < grid.getNumRows(); row++) {
        pg->at(row, 0) = pg->at(row - 1, 0) + grid.at(row, 0);            
    }    
    for(int col = 1; col < grid.getNumCols(); col++) {
        colSum = grid.at(0, col);
        for(int row = 1; row < grid.getNumRows(); row++) {
            pg->at(row, col) = pg->at(row, col - 1) + grid.at(row, col) + colSum;
            colSum += grid.at(row, col);
        }    
    }

}