# teaching machines

## CS 145 Lecture 24 – Accumulation

### Agenda

• what ?s
• accumulation pattern

### Note

We continue our discussion of common patterns we see with loops. Today we visit the accumulation pattern, where a loop iterates through a collection and accumulates values in some variable of larger scope. Accumulations tend to look like this:

initialize soFar
for each item
integrate item into soFar
end
use soFar to some other end

We’ll look at an example of calculating a linear approximation of a dataset.

### Code

#### Regression.java

package lecture1030;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Regression {
public static void main(String[] args) throws FileNotFoundException {
File dataset = new File("/Users/johnch/numbers.csv");
Scanner in = new Scanner(dataset);

int productSumSoFar = 0;
int totalX = 0;
int totalY = 0;
int totalSquaredX = 0;
int n = 0;

while (in.hasNextInt()) {
int x = in.nextInt();
int y = in.nextInt();
System.out.printf("(%d,%d),", x, y);
totalX += x;
totalY += y;
totalSquaredX += x * x;
productSumSoFar += x * y;
++n;
}

double meanXY = productSumSoFar / (double) n;
double meanX = totalX / (double) n;
double meanY = totalY / (double) n;
double meanXX = totalSquaredX / (double) n;

double beta = (meanXY - meanX * meanY) / (meanXX - meanX * meanX);
double alpha = meanY - beta * meanX;

System.out.printf("y = %f * x + %f", beta, alpha);

//    System.out.println(productSumSoFar);

in.close();
}
}

### Haiku

To accumulate:
while the bag is not empty
  eat you some candy