// Arup Guha
// 4/15/2019
// Solution to 2013 AP Comp Sci A FR Question 4: SkyView

import java.util.*;

public class SkyView {

	private double[][] view;
	
	/*** Solution to Part A. ***/
	public SkyView(int numRows, int numCols, double[] scanned) {
		
		// Allocate space for the array.
		view = new double[numRows][numCols];
		
		// Column index and change.
		int y=0, dy=1, i=0;
		
		// Go row by row.
		for (int x=0; x<numRows; x++) {

			// This is tricky - iter counts how many times it goes, (x,y) index view, 
			// and i indexes scanned. Break into more lines of code to make it easier.
			for (int iter=0; iter<numCols; iter++,y+=dy,i++)
				view[x][y] = scanned[i];
			
			// Here is how y and dy change from row to row.
			dy = -dy;
			y += dy;
		}
	}
	
	// For testing.
	public String toString() {
		String res = "";
		for (int i=0; i<view.length; i++) {
			res = res + "[";
			for (int j=0; j<view[i].length; j++) {
				res = res + view[i][j];
				if (j <view[i].length-1) res = res + ", ";
			}
			res = res + "]\n";
		}
		return res;
	}
	
	/*** Solution to Part B. ***/
	public double getAverage(int startRow, int endRow, int startCol, int endCol) {
		
		// Add up each relevant square.
		double sum = 0;
		for (int i=startRow; i<=endRow; i++)
			for (int j=startCol; j<=endCol; j++)
				sum += view[i][j];
			
		// Divide this by the number of squares; pay attention to order of ops and int vs. double division.
		return sum/(endRow-startRow+1)/(endCol-startCol+1);
	}
	
	public static void main(String[] args) {
		
		double[] vals = {.3, .7, .8, .4, 1.4, 1.1, .2, .5, .1, 1.6, .6, .9};
		
		// Test their way.
		SkyView sv = new SkyView(4, 3, vals);
		System.out.println(sv);
		System.out.println("Avg r12c01 = "+sv.getAverage(1, 2, 0, 1));
		System.out.println();
		
		// A different grid with the same numbers.
		sv = new SkyView(2, 6, vals);
		System.out.println(sv);
		System.out.println("Avg r01c24 = "+sv.getAverage(0, 1, 2, 4));

		System.out.println();	

		// A third view.
		sv = new SkyView(6, 2, vals);
		System.out.println(sv);
		System.out.println("Avg r35c01 = "+sv.getAverage(3, 5, 0, 1));
		System.out.println();		
	}


}