Correctness and Efficiency

The program below is correct. It prints how far each of today's eight hourly bird counts at a feeder lies from the average of yesterday's counts. This lesson counts its work, finds the part it repeats, and then searches a sorted copy of the counts.
const counts = [14, 9, 22, 17, 6, 11, 19, 13];
const yesterday = [10, 7, 16, 13, 4, 9, 14, 7];
function average(values) {
  let total = 0;
  for (const value of values) {
    total += value;
  }
  return total / values.length;
}
const distances = [];
for (const count of counts) {
  distances.push(Math.abs(count - average(yesterday)));
}
console.log(distances);
Output
Press Run to see what this program prints.

Note: This IDE is for experimenting with the code in this lesson. Your changes are not saved, and refreshing the page puts back the original lesson code.

Yesterday's counts average 10, and the program prints an array holding 4, 1, 12, 7, 4, 1, 9, and 3.
Run the program above to see that array.

Counting the work

The loop makes 8 passes, one per count. Each pass calls average(yesterday), and inside that call total += value runs once for each of yesterday's 8 counts. Thus it runs 8 × 8 = 64 times, and all eight calls return the same 10.
Runs of total += value inside average(yesterday). Columns: yesterday's values, read by the call: 10, 7, 16, 13, 4, 9, 14, 7. Rows: pass 1 (count 14), pass 2 (count 9), pass 3 (count 22), pass 4 (count 17), pass 5 (count 6), pass 6 (count 11), pass 7 (count 19), pass 8 (count 13), each with all eight cells filled. Call inside the loop: 8 passes × 8 runs = 64 runs. Once, before the loop: one row of eight cells. Call stored before the loop: 8 runs, same printed array.

One call before the loop

The loop never changes yesterday, so every call returns 10. We call average once, before the loop, and store its answer. Only the lines after the function change.
const avg = average(yesterday);
const distances = [];
for (const count of counts) {
distances.push(Math.abs(count - avg));
}
console.log(distances);
It prints the same array. Both programs are correct, and in this one that addition runs 8 times instead of 64.
The first program meets that condition. A loop that compares each count with the average of the counts so far doesn't.
const seen = [];
for (const count of counts) {
seen.push(count);
console.log(Math.abs(count - average(seen)));
}
Since seen grows on every pass, average(seen) returns 14 on the first pass, 11.5 on the second, and 13.875 on the last. Called once before the loop, it would average an empty array. JavaScript reports no error: 0 / 0 is NaN ("not a number"), so every line would print NaN.
The program below has that shape, on a runner's lap times in seconds. Each pass prints a lap next to the average of the laps so far. Run it, then change it and run it again:
• Add a fifth lap time to the list.
• Add const avg = average(seen); on the line just above for (const lap of laps) {, and change average(seen) in the console.log line to avg.
function average(values) {
  let total = 0;
  for (const value of values) {
    total += value;
  }
  return total / values.length;
}

const laps = [60, 64, 59, 65];
const seen = [];
for (const lap of laps) {
  seen.push(lap);
  console.log(lap, "seconds, average so far:", average(seen));
}
Output
Press Run to see what this program prints.

Note: This IDE is for experimenting with the code in this lesson. Your changes are not saved, and refreshing the page puts back the original lesson code.

Constant time

Square brackets take no negative index in JavaScript (counts[-1] is undefined), so the newest count is counts[counts.length - 1]. Its distance, Math.abs(counts[counts.length - 1] - avg), is 3. Computing it reads one count, whether the array holds 8 counts or 32.

Searching the sorted counts

Binary search needs sorted data, so we sort a copy of counts with const sorted = counts.slice().sort((a, b) => a - b);. With no argument, sort() compares numbers as text and would put 6 and 9 after 22. It also rearranges the array it's called on, so slice() copies counts first. The copy holds 6, 9, 11, 13, 14, 17, 19, and 22.
A binary search for 20 starts with all 8 as candidates. Each probe reads the middle candidate, rounding down, and keeps the side where 20 would have to be.
ProbeCandidatesMiddle count
1indices 0 to 713, at index 3
2indices 4 to 717, at index 5
3indices 6 to 719, at index 6
4index 722, at index 7
Binary search for 20 in the sorted counts 6, 9, 11, 13, 14, 17, 19, 22, at indices 0 to 7. Probe 1: middle of 0 to 7 is index 3, holding 13; 20 is greater than 13, keep indices 4 to 7. Probe 2: middle of 4 to 7 is index 5, holding 17; 20 is greater than 17, keep indices 6 to 7. Probe 3: middle of 6 to 7 is index 6, holding 19; 20 is greater than 19, keep index 7. Probe 4: only index 7 is left, holding 22; 20 is less than 22, no indices left: 20 is not in the array. Gray, crossed out: eliminated before this probe.
After the fourth probe no candidate is left, since 20 lies between 19 and 22, so 20 isn't there. The first three probes halved the candidates from 8 to 4, 2, and 1, and the fourth checked the last one. No search of these 8 counts takes more. A sorted array of 32 counts halves five times, to 16, 8, 4, 2, and 1. A binary search of it makes at most 6 probes, and a sequential search can read all 32.
Each probe discards a side on the assumption that the array is in order.
On counts, still in hour order, the check fails at the first pair, since 14 is larger than 9. On sorted it passes after comparing all 7 neighboring pairs, about the 8 reads a sequential search of the same counts can take. So checking the order before every search costs about as much as a sequential search, and throws away what binary search saves.

Reasonable and unreasonable time

Suppose both arrays held 32 counts. The first program would run the addition 32 × 32 = 1,024 times, the square of the length. The improved program runs it 32 times, and its loop makes 32 passes.
Both step counts are polynomials in the length, so both programs run in reasonable time. A program that tries every group of today's counts, looking for one that adds to exactly 50, is exponential. Each count is either in a group or out of it, so 8 counts form 2 ** 8 = 256 groups, and thirty-two counts form 2 ** 32, about 4.3 billion. Quadrupling the length multiplied the first program's count by 16 and this one's by about 16.8 million.