Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- class TemperatureGrid {
- private double[][] temps;
- public TemperatureGrid(double[][] temps) {
- this.temps = new double[temps.length][temps[0].length];
- for (int i = 0; i < temps.length; i++) {
- System.arraycopy(temps[i], 0, this.temps[i], 0, temps[0].length);
- }
- }
- private double computeTemp(int row, int col) {
- if (row == 0 || col == 0 || row == temps.length - 1 || col == temps[0].length - 1)
- return temps[row][col];
- return ((temps[row - 1][col] + temps[row + 1][col] + temps[row][col - 1] + temps[row][col + 1]) / 4);
- }
- public boolean updateAllTemps(double tolerance) {
- boolean flag = true;
- double[][] updated = new double[temps.length][temps[0].length];
- for (int row = 0; row < temps.length; row++)
- for (int col = 0; col < temps[0].length; col++) {
- updated[row][col] = computeTemp(row, col);
- if ((Math.abs(temps[row][col] - updated[row][col])) > tolerance)
- flag = false;
- }
- for (int r = 0; r < temps.length; r++)
- for (int c = 0; c < temps[0].length; c++)
- temps[r][c] = updated[r][c];
- return flag;
- }
- public String toString() {
- String output = "";
- for (double[] temp : temps)
- output += Arrays.toString(temp) + "\n";
- return output;
- }
- }
- public class TemperatureGridRunner {
- public static void main(String[] args) {
- double[][] arr = new double[][]{
- {95.5, 100, 100, 100, 100, 110.3},
- {0, 50, 50, 50, 50, 0},
- {0, 40, 40, 40, 40, 0},
- {0, 20, 20, 20, 20, 0},
- {0, 0, 0, 0, 0, 0},
- };
- TemperatureGrid runner = new TemperatureGrid(arr);
- System.out.println(runner);
- boolean test = runner.updateAllTemps(15);
- System.out.println(runner);
- System.out.println(test);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement