- Forward


Neighborhoods
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • The Idea:
    • You often need to perform calculations on the elements of an array that "near" a particular element
  • Involving Arrays:
    • We need to perform an operation on the elements to the left and/or right of a given element
  • Involving Arrays of Arrays:
    • We need to perform an operation on the elements surrounding a given element
Motivation (cont.)
Back SMYC Forward

Visualization of an Example Array
Neighborhoods_Array

Visualization of an Example Array of Arrays
Neighborhoods_Matrix

Review
Back SMYC Forward
  • Using the Subarrays Pattern:
    • The subset would be described using an offset and length for each dimension
  • A Shortcoming:
    • It is not consistent with the way domain experts think about the problem
Thinking About the Problem
Back SMYC Forward
  • Involving Arrays:
    • Domain experts think about the middle element and the size (which is usually odd, meaning there are the same number of elements to the left and right)
  • Involving Arrays of Arrays:
    • Domain experts think about the middle element (which has a row and column) and a single odd size (making the neighborhood square)
The Pattern
Back SMYC Forward
  • The Idea:
    • Add parameters to the signature of the method
  • For Arrays:
    • An index and a size
  • For Arrays of Arrays:
    • A row, col, and size
Examples
Back SMYC Forward
Using an Array
javaexamples/programmingpatterns/Neighborhoods.java (Fragment: 0)
 
Examples (cont.)
Back SMYC Forward
Using an Array of Arrays
javaexamples/programmingpatterns/Neighborhoods.java (Fragment: 1)
 
Examples (cont.)
Back SMYC Forward
Using an Array of Arrays - Ignoring the Center Element
javaexamples/programmingpatterns/Neighborhoods.java (Fragment: 3)
 
Examples (cont.)
Back SMYC Forward
Using an Array of Arrays - A Plus-Sign-Shaped Neighborhood
javaexamples/programmingpatterns/Neighborhoods.java (Fragment: 2)
 
There's Always More to Learn
Back -