JMU
Accumulators
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Motivation
Review
Review (cont.)

Getting Started

javaexamples/programmingpatterns/accumulators/Accumulators.java (Fragment: loop)
                for (int i = 0; i < n; i++) {
            // Do something with data[i]
        }
        

What "needs to be done" at each iteration?

Thinking About the Problem
The Pattern
Types of Accumulators
A Numeric Example

Finding the Maximum

javaexamples/programmingpatterns/accumulators/Accumulators.java (Fragment: max)
                double maximum;       
        int n;
       
        n = Array.getLength(data);       
        maximum = Double.NEGATIVE_INFINITY;       

        for (int i = 0; i < n; i++) {
            if (data[i] > maximum) maximum = data[i];
        }
        
A Boolean Example

Containment

javaexamples/programmingpatterns/accumulators/Accumulators.java (Fragment: contains)
                boolean      found;       
        int          n;
       
        n = Array.getLength(data);       
        found = false;

        for (int i = 0; ((i < n) && !found); i++) {
            if (target == data[i]) found = true;
        }
        
Examples with Multiple Accumulators

The Mean After Dropping the Lowest Value

javaexamples/programmingpatterns/accumulators/Accumulators.java (Fragment: droplowest)
                double lowest, result, total;       
        int n;
       
        n = Array.getLength(data);       
        total = 0.0;       
        lowest = Double.POSITIVE_INFINITY;

        for (int i = 0; i < n; i++) {
            total += data[i];
            if (data[i] < lowest) lowest = data[i];
        }
        result = (total - lowest) / (n - 1);
        
An Example with a Common "Twist"

The Index of the Largest Element

javaexamples/programmingpatterns/accumulators/Accumulators.java (Fragment: argmax)
                double maximum;       
        int index, n;
       
        n = Array.getLength(data);       
        maximum = Double.NEGATIVE_INFINITY;       
        index = -1;

        for (int i = 0; i < n; i++) {
            if (data[i] > maximum) {
                index   = i;
                maximum = data[i];
            }
        }