Report

EXAMPLES (Arrays) Example • Many engineering and scientific applications represent data as a 2-dimensional grid of values; say brightness of pixels in a video image. A common algorithm on these grids is to smooth the data by updating the value of each point to be the average of its old value and the points immediately surrounding it. – • If the point were on the edge of the grid, the average would include only that point and its immediate neighbors that are on the grid. Write a Java method that smoothes the values in a 2-D grid. private static void smoothImage(double [][] A){ double [][]temp = new double[A.length][A[0].length]; int i, j, x, y, count; for (i = 0; i < A.length; i++) for (j = 0; j < A[0].length; j++) temp[i][j] = A[i][j]; for (i = 0; i < A.length; i++) for (j = 0; j < A[0].length; j++){ count = 0; A[i][j] = 0; for (x = -1; x <= 1; x++) for (y = -1; y <= 1; y++) if ((i+x >= 0) && (i+x < A.length) && (j+y >= 0) && (j+y < A[0].length)){ A[i][j] += temp[i + x][j + y]; count++; } A[i][j] /= count; } } Example • Suppose that you are given a 2-D array with integers and an integer value. Write a Java method that determines whether or not the integer is written as the summation of the successive values in the 2-D array. private static boolean subsequenceSum(int [][]A, int value){ for (int i = 0; i < A.length; i++) for (int j = 0; j < A[0].length; j++){ if (value == A[i][j]) return true; int total = A[i][j]; for (int k = i + 1; k < A.length; k++){ total += A[k][j]; if (value == total) return true; } total = A[i][j]; for (int k = j + 1; k < A[0].length; k++){ total += A[i][k]; if (value == total) return true; } } return false; } Example • The Bell triangle is the number triangle obtained by beginning the first row with the number one, and beginning subsequent rows with last number of the previous row. Rows are filled out by adding the number in the preceding column to the number above it. 1 12 235 5 7 10 15 15 20 27 37 52 • Write a complete Java program to compute the values in the bell triangle when the row number is specified. import java.util.*; public class BellTriangle{ public static void main(String [] args){ int [][] A; Scanner s = new Scanner(System.in); System.out.print("Enter a row number: "); int size = s.nextInt(); if (size <= 0) System.out.println("Enter a positive integer"); else A = computeBellTriangle(size); } private static int [][] computeBellTriangle(int size){ int [][] T; T = new int[size][]; for (int i = 0; i < size; i++) T[i] = new int[i+1]; T[0][0] = 1; for (int i = 1; i < T.length; i++){ T[i][0] = T[i-1][i-1]; for (int j = 1; j < T[i].length; j++) T[i][j] = T[i][j-1] + T[i-1][j-1]; } return T; } }