Weeks
Computational ThinkingWeek 4 · Binning and a Summary of Weeks 1 to 4
Week 4 Notes

Computational
Thinking 4

Reducing comparisons with binning, and a summary of the concepts from Weeks 1 to 4. Lectures 4.3 and 4.8.

3 chapters15 worked examples~19 min read
BinningComparisonsIteratorsWeeks 1 to 4

Chapters

  1. 01Reducing the Number of Comparisons with BinningLecture 4.3
  2. 02Summary of Concepts from Weeks 1 to 4Lecture 4.8
  3. 03Week 4 Summary SheetAll lectures
01
Lecture 4.3

Reducing the Number of Comparisons with Binning

How many comparisons comparing every pair needs, why that grows so fast, and how binning cuts it.

Some computations seem to need comparing each card with all the other cards in a pile. An example is choosing a study partner for each student. The number of comparisons can be very large. This lecture counts them exactly and shows how binning cuts the count.

1.1Comparing each element with all the others

Take 5 elements A, B, C, D, E. Compare A with every other element, then B with every element not yet compared with B, and so on.

Elements A to E, compared with those after themABCDE4comparisonsBCDE3comparisonsCDE2comparisonsDE1comparisons4 + 3 + 2 + 1 = 10B with A need not be repeated; C with A and C with B need not be repeated
Figure 1. The 10 comparisons for 5 elements, grouped by the element on the left
ElementCompared withComparisons
AB, C, D, E4
BC, D, E3
CD, E2
DE1
Total4 + 3 + 2 + 1 = 10

1.2A formula for the number of comparisons

The formula

For N objects the comparisons needed are (N − 1) + (N − 2) + ... + 1, which equals

N×(N−1)2=12×N×(N−1)=NC2\frac{N \times (N - 1)}{2} = \tfrac12 \times N \times (N - 1) = {}^{N}C_2

the same as the number of ways of choosing 2 objects from N objects.

The same formula from first principles:

All 25 ordered pairs of 5 elementsAAABACADAEBBBCBDBECCCDCEDDDEEE1 every card with every card5 × 5 = 252 remove self comparisons (A with A)25 − 5 = 20 = 5 × 43 A with B equals B with A: halve it½ × 5 × 4 = 10self paircounteddashed: repeat
Figure 2. Where ½ × N × (N − 1) comes from, shown for N = 5
  1. Start: N × N = 5 × 5 = 25 pairs: every card with every card.
  2. Remove the self comparisons (A with A): N × N − N = 20, which is N × (N − 1).
  3. A with B is the same as B with A. We double counted: halve it.
  4. ½ × N × (N − 1) = ½ × 5 × 4 = 10.
Remember. Two things are removed from the N × N pairs: comparing an item with itself, and comparing A with B and B with A (the same comparison counted twice).

1.3The number of comparisons grows really fast

NN × (N − 1) / 2
21
33
46
510
615
721
828
936
1045
1004,950
10004,99,500
Comparisons ½ × N × (N − 1) for N = 2 to 101233641051562172883694510N (number of items)N = 10 gives 45; doubling the items roughly quadruples the comparisons
Figure 3. The quadratic curve of N × (N − 1) / 2
Check on the lecture slide. The slide's table shows 49,500 for N = 100. The formula gives 100 × 99 / 2 = 4,950, so the table above uses 4,950. The value for N = 1000 on the slide, 4,99,500 (that is 499,500), is correct.
Why it matters

The count grows quadratically, i.e. quite fast. 10 items need 45 comparisons, but 1000 items need 4,99,500. Doubling the items roughly quadruples the comparisons. Comparing every pair is not practical for large piles.

1.4The key idea: binning

If we can organise the cards into bins based on some heuristic (a rule of thumb), then we only need to compare cards within one bin. This seems to reduce the number of comparisons a lot. To find the reduction formally: calculate the comparisons without binning, calculate them with binning, and use both to find the reduction factor.

Take 9 objects A to I. Comparing all pairs needs ½ × 9 × 8 = 36 comparisons. Now suppose the objects can be put into 3 bins of 3 each (ABC, DEF and GHI) and we compare only inside each bin:

NO BINNINGABCDEFGHI½ × 9 × 8 = 36THREE BINS OF THREE: compare only inside each binABC½ × 3 × 2 = 3DEF½ × 3 × 2 = 3GHI½ × 3 × 2 = 33 bins × 3 = 9 (36 → 9, factor 4)
Figure 4. Nine objects: 36 comparisons without bins, 9 with three bins
  1. Comparisons per bin: ½ × 3 × (3 − 1) = ½ × 3 × 2 = 3.
  2. Total for all 3 bins: 3 × 3 = 9.
  3. The comparisons reduce from 36 to 9: a reduction by a factor of 4.

1.5The calculation for any N and K

For N items put into K bins of equal size:

QuantityFormula
Comparisons without binning12×N×(N−1)\tfrac12 \times N \times (N - 1)
Items in each binN/KN / K
Comparisons per bin12×NK×(NK−1)\tfrac12 \times \tfrac{N}{K} \times \left(\tfrac{N}{K} - 1\right)
Total comparisons with K binsK×12×NK(NK−1)=12×N×(NK−1)K \times \tfrac12 \times \tfrac{N}{K}\left(\tfrac{N}{K} - 1\right) = \tfrac12 \times N \times \left(\tfrac{N}{K} - 1\right)
Factor of reduction12N(N−1)12N(NK−1)=N−1NK−1\dfrac{\tfrac12 N (N - 1)}{\tfrac12 N \left(\tfrac{N}{K} - 1\right)} = \dfrac{N - 1}{\tfrac{N}{K} - 1}

Check with N = 9 and K = 3: (9 − 1) / (3 − 1) = 8 / 2 = 4, as found above.

N = 100: comparisons with K equal bins, and the factor of reductionno bins4,950K = 22,4502.0×K = 41,2004.1×K = 59505.2×K = 1045011.0×K = 2020024.8×K = 2515033.0×K = 505099.0×more bins means far fewer comparisons (illustration of the formula)
Figure 5. More bins means far fewer comparisons (the formula for N = 100)
K binsItems per binComparisonsFactor
none1004,9501
2502,4502.0×
4251,2004.1×
5209505.2×
101045011.0×
20520024.8×
25415033.0×
5025099.0×
Remember. The formula assumes K bins of equal size, so K must divide N. Binning only works when a heuristic exists that puts the items into bins so that only items in the same bin ever need to be compared.

1.6Going deeper

  • The factor is close to K (extra). For large N, (N − 1)/(N/K − 1) is a little more than K (10.09 for K = 10), so ten bins give about a ten-fold saving.
  • K = N breaks the formula (extra). If every bin has one item, N/K − 1 = 0: no comparisons at all, and the factor is undefined (division by zero).
  • The heuristic carries the risk (extra). If two items that should be compared land in different bins, the comparison is never made. Binning by month finds people with the same birth month, which is a necessary condition for the same birthday.
  • Square growth (extra). Going from 10 to 20 items multiplies the comparisons by 190 / 45 ≈ 4.2.

1.7Exam tips and common mistakes

Exam tips
  • First write N × (N − 1), then halve it. For bins, do the per-bin count first, then multiply by the number of bins.
  • Check with a small case (N = 5 gives 10, N = 9 gives 36).
Common mistakes
  • Counting each pair twice (N × (N − 1) without halving).
  • Copying the slide's 49,500 for N = 100; the correct value is 4,950.
  • Using the K-bin formula when the bins are unequal.

Practice questions (graded-assignment style)

Q1Pairs of 8

Numerical Answer Type (NAT).

How many comparisons are needed to compare every pair among 8 items?

Solution
Idea

Use ½ × N × (N − 1).

  • ½ × 8 × 7 = 28 (the lecture table has 28 for N = 8).
  • Answer: 28
Q2N = 100

Numerical Answer Type (NAT).

How many comparisons does a pile of 100 items need without binning?

Solution
Idea

Do not copy the slide table.

  • ½ × 100 × 99 = 4,950, not 49,500.
  • Answer: 4950
Q3Nine in three bins

Numerical Answer Type (NAT).

9 objects are put into 3 bins of 3. How many comparisons are needed in total?

Solution
Idea

Per bin ½ × 3 × 2.

  • Each bin needs 3 comparisons, so 3 × 3 = 9 (36 without bins).
  • Answer: 9
Q4Factor of reduction

Numerical Answer Type (NAT).

20 students are put into 4 bins of 5. What is the factor of reduction in the number of comparisons?

Solution
Idea

Use (N − 1) / (N/K − 1).

  • (20 − 1) / (20/4 − 1) = 19 / 4 = 4.75, and 190 / 40 = 4.75.
  • Answer: 4.75
Q5Which formula?

Multiple Choice Question (MCQ): choose the one correct option.

With N items in K equal bins, the total number of comparisons is:

1
½ × N × (N − 1)
2
½ × N × (N/K − 1)
3
K × N
4
N / K
Solution
Idea

Per bin, then multiply by K.

  • Per bin ½ × (N/K) × (N/K − 1); times K gives ½ × N × (N/K − 1).
  • Answer: option 2.
Q6Binning facts

Multiple Select Question (MSQ): select all that apply.

Choose the correct statements.

1
The equal-bin formula needs K to divide N
2
Binning needs a heuristic that puts items into bins
3
Doubling the items roughly doubles the comparisons
4
More equal bins always give fewer comparisons
Solution
Idea

Recall the growth and the formula.

  • Statements 1, 2 and 4 are true. Doubling the items roughly quadruples the comparisons (statement 3 is false).
  • Answer: options 1, 2 and 4.
Q7Unequal bins

Numerical Answer Type (NAT).

10 items fall into bins of sizes 4, 3 and 3. How many comparisons are needed?

Solution
Idea

Add ½ × n × (n − 1) over the bins.

  • 6 + 3 + 3 = 12.
  • Answer: 12
Revision overview
The problemEach card vs all others
Study partner example
The count can be huge
Counting pairs(N−1) + ... + 1
½ × N × (N − 1)
Same as NC2
Quadratic growth10 items: 45
1000 items: 4,99,500
Slide's 49,500 for 100 is wrong
BinningLecture 4.3
BinningA heuristic puts items in bins
Compare only within a bin
9 items: 36 down to 9
N items, K bins½ × N × (N/K − 1)
Equal-size bins
Factor(N−1) / (N/K−1)
N = 9, K = 3: 4
Revision: counting comparisons and how much binning saves
Next · Lecture 4.8Summary of Concepts from Weeks 1 to 4
02
Lecture 4.8

Summary of Concepts from Weeks 1 to 4

Iterators, datatypes, filtering, procedures, accumulation and nested iterations, each building on the last.

This lecture revisits the main ideas of Weeks 1 to 4. Each idea builds on the previous one, from a plain iterator up to nested iterations that relate two elements to each other.

2.1Iterators and variables

The iterator is the most commonly used pattern in computational thinking. It represents the procedure of doing some task repeatedly. It needs an initialisation step, the steps for the task that is repeated, and a way to determine when to stop.

StartInitialise variablesContinueiteration?No (False)EndYes (True)Update values ofvariables
Figure 6. An iterator as a flowchart: initialise, continue?, update
iterator.pseudo
Initialise variables
while (Continue with Iteration?) {
    Update values of variables
}
  • Variables keep track of intermediate values. They get starting values at the initialisation step and are updated at each repeated step.
  • Initialisation and updates are done through assignment statements.
  • The flowchart symbols are: terminal (Start, End), process, decision, and arrows that show progress from one step to another.
Remember

Every iterator has three parts: initialise, continue? (the stopping test) and update.

2.2Going through a set of items

To go systematically through a set of items, the loop picks a card from Pile 1, moves it to Pile 2, and continues while Pile 1 has more cards.

StartInitialise variablesMore cardsin Pile 1?No (False)EndYes (True)Pick a card X from Pile 1Move X to Pile 2Update values of variables
Figure 7. Iteration over a pile of cards
iteration-over-the-cards.pseudo
Initialise variables
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    Update values of variables
}

2.3Datatypes, lists and records

The items need well defined values. This leads to datatypes, which clearly identify the values and the allowed operations. The basic datatypes are boolean, integer and character; the string datatype is added to these. Subtypes put more constraints on the values and operations allowed.

booleanTrue / Falseintegerwhole numberscharactera single symbolstringtextSubtypes put more constraints on the values and operations allowedList95949640RecordId1GenderMMaths95all items typically the same datatypenamed fields, each can differ in type
Figure 8. Datatypes, subtypes, lists and records
ListA bigger bundle of data in which all items typically have the same datatype.
RecordA bundle with multiple named fields, each of a possibly different datatype (a card: Id, Gender, Maths).

2.4Iteration with filtering

Filtering makes a decision at each repeated step whether to process an item or not. This adds a decision step inside the loop.

filtering.pseudo
Initialise variables
while (Continue with Iteration?) {
    ...
    if (condition is satisfied?) {
        Update some variables
    }
    ...
}
Prepare final results from variable values
The filtering condition compares an item with...MeaningExamples
a constantthe condition does not change after each iteration stepCount, Sum
a variablethe condition changes after an iteration stepmax
StartCount = 0More cardsin Pile 1?No (False)EndYes (True)Pick a card X from Pile 1Move X to Pile 2X.Gender == F?Yes (True)Count = Count + 1No (False)
Figure 9. Filter with a constant: the test X.Gender == F never changes
StartMaxval = 0More cardsin Pile 1?No (False)EndYes (True)Pick a card X from Pile 1Move X to Pile 2X.Maths > Maxval?Yes (True)Maxval = X.MathsNo (False)
Figure 10. Filter with a variable: X.Maths > Maxval changes whenever Maxval is updated

2.5Procedures and parameters

We sometimes write the same piece of code again and again with small differences. A piece of pseudocode can become a procedure by separating it from the rest of the code. Some variables or constants in it are replaced by a parameter variable. Instead of rewriting the code, we call the procedure with a different parameter value, for example finding the max for each subject.

Procedure Maxmarks(fld)the same loop for any fieldfld is the parameter variableMaxmarks(Maths)fld = MathsMaxmarks(Physics)fld = PhysicsMaxmarks(Chemistry)fld = Chemistrywrite the code once, call it with a different parameter value
Figure 11. One procedure Maxmarks(fld), called for different fields

2.6Accumulation through iteration

The most common use of an iterator is to create an aggregate value (accumulation) from the available values. Simple examples are count, sum and average. We can filter while accumulating, for example the sum of the boys' marks. We can also collect a list of elements, for example the students with the maximum marks in a subject.

2.7Two iterations, one after another

The first iteration does some accumulation. The variables that hold the results are called accumulators. The second iteration does filtering using the accumulator variables, for example finding the above-average students, where the average comes from the first iteration. This establishes a relationship between any element and the aggregate of all elements, for example the more frequently occurring word, or higher-spending customers.

ITERATION 1 · accumulateover all cardsSum = Sum + X.MathsCount = Count + 1Sum = 577, Count = 8ITERATION 2 · filterwith the accumulatorif (X.Maths > Average)keep the card577 / 8 = 72.125Above average: cards 1, 2, 3, 6 (needs the average first, so two loops)
Figure 12. Above-average Maths marks on the eight-card deck

2.8Two iterations, one nested within the other

To go beyond an element and the aggregate, and express a relationship between any two elements, one iteration must run inside another. Example: find out if two students have the same birth day and month. Nested iterations are costly in the number of computations, so wherever possible we reduce the comparisons using binning (Lecture 4.3). How to store such relationships is discussed in the next four weeks.

Outer iteration X, inner iteration Y: the 15 pairs checked (green: same birthday)AA✓BB✓CCDDEEFF15 pairsA: 12 MarB: 05 JulC: 12 MarD: 20 JanE: 05 JulF: 30 NovWITH BINS BY MONTH: compare only inside a binMar: A, C Jul: B, E Jan: D Nov: F1 + 1 + 0 + 0 = 2 comparisons
Figure 13. Nested iteration over pairs, with and without binning by month
No pseudocode for nested iterations. The lecture gives no pseudocode for nested iterations, so they are shown here only as a diagram of which pairs get compared.

2.9Going deeper

  • Iterator, filter, accumulate, nest. Each idea adds one thing to the last: a repeated step, then a decision inside it, then variables that collect results, then a second loop, then a loop inside a loop.
  • Constant versus variable. A constant condition (X.Gender == F) can be tested on any card in any order; a variable condition (X.Maths > Maxval) depends on what was seen so far.
  • Why two loops (extra). The average needs all the marks, so no card can be judged until the whole pile has been summed.
  • Cost of nesting (extra). The outer loop runs N times and the inner about N times, so the work is about N²; binning is the way to shrink it.

2.10Exam tips and common mistakes

Exam tips
  • Ask "does the test use something that changes while the loop runs?" to tell a constant filter from a variable filter.
  • If a question compares each item with an aggregate (average, maximum), expect two iterations: accumulate first, then filter.
Common mistakes
  • Merging the two iterations: the above-average test needs the average first.
  • Mixing up constant and variable filters.
  • Forgetting the heuristic: binning helps only if items in different bins never need comparing.

Practice questions (graded-assignment style)

Q1Counting girls

Numerical Answer Type (NAT).

On the eight-card deck (genders M F M F M F F M), what is Count at the end of the count-girls loop?

Solution
Idea

Count the F cards.

  • The girls are cards 2, 4, 6 and 7: Count = 4.
  • Answer: 4
Q2Boys' Maths sum

Numerical Answer Type (NAT).

What is the sum of the boys' Maths marks on the same deck?

Solution
Idea

The boys are cards 1, 3, 5, 8.

  • 95 + 96 + 42 + 70 = 303.
  • Answer: 303
Q3How many updates

Numerical Answer Type (NAT).

For the Maths marks 95, 94, 96, 40, 42, 80, 60, 70 how many times does Maxval change during the loop (starting at 0)?

Solution
Idea

Count the records.

  • It changes at 95 (card 1) and at 96 (card 3); the final value is 96.
  • Answer: 2
Q4The average

Numerical Answer Type (NAT).

What is the average of the eight Maths marks?

Solution
Idea

Sum divided by count.

  • 577 / 8 = 72.125.
  • Answer: 72.125
Q5Above average

Numerical Answer Type (NAT).

How many of the eight students have a Maths mark above the average?

Solution
Idea

Compare each mark with 72.125.

  • The marks 95, 94, 96 and 80 (cards 1, 2, 3, 6) are above 72.125.
  • Answer: 4
Q6Constant or variable?

Multiple Choice Question (MCQ): choose the one correct option.

Which filter compares an item with a variable?

1
X.Gender == F
2
X.Maths > Maxval
3
X.Gender == M
4
None of these
Solution
Idea

Which test changes when the loop updates something?

  • Maxval changes during the loop, so the test X.Maths > Maxval changes with it.
  • Answer: option 2.
Q7Birthday comparisons

Multiple Choice Question (MCQ): choose the one correct option.

For 6 people, how many comparisons does the nested iteration need without binning?

1
6
2
15
3
30
4
36
Solution
Idea

½ × N × (N − 1).

  • ½ × 6 × 5 = 15.
  • Answer: option 2.
Q8Two iterations

Multiple Select Question (MSQ): select all that apply.

Choose the correct statements about above-average students.

1
The average must be computed before filtering
2
The two loops can be merged into one
3
The first iteration produces accumulators
4
Binning by month is used for it
Solution
Idea

The average needs all the marks.

  • Statements 1 and 3 are true. The loops cannot be merged, and binning belongs to the nested birthday example.
  • Answer: options 1 and 3.
Revision overview
IteratorInitialise, continue?, update
Variables hold values
Assignment statements
Datatypesboolean, integer, character
string and subtypes
List vs record
FilteringDecision inside the loop
Constant: count, sum
Variable: max
Weeks 1 to 4Lecture 4.8
ProceduresSame code, small change
Parameter variable
Call with a new value
More loopsAccumulators, then filter
Nested: two elements
CostlyNested iterations: ½ × N × (N−1)
Binning cuts comparisons
Revision: the main ideas of Weeks 1 to 4 in one view
Next · All lecturesWeek 4 Summary Sheet
03
All lectures

Week 4 Summary Sheet

One page to revise all of Week 4: how many comparisons a pile needs, how binning cuts them, and the ideas that lead up to it.

The big picture

Lecture 4.3 · Counting comparisons
  • Comparing every pair of N items needs ½ × N × (N − 1), the same as NC2.
  • It grows quadratically: 10 items need 45, 1000 items need 4,99,500.
Lecture 4.3 · Binning
  • A heuristic puts items into bins and only items in the same bin are compared.
  • With K equal bins the count becomes ½ × N × (N/K − 1).
Lecture 4.3 · Factor of reduction
  • (N − 1) / (N/K − 1).
  • For N = 9 and K = 3 it is 8 / 2 = 4, so 36 comparisons become 9.
Lecture 4.8 · Iterators and filtering
  • Initialise, continue?, update.
  • Add a decision inside the loop to filter, with a constant (count, sum) or a variable (max).
Lecture 4.8 · Procedures and accumulation
  • Turn repeated code into a procedure with a parameter.
  • Accumulate count, sum, average, or collect a list.
Lecture 4.8 · Two iterations
  • One after another: accumulate, then filter with the accumulator.
  • Nested: relate any two elements, which is costly, so use binning.

Formulas to remember

QuantityFormulaExample
Comparisons of all pairs of N items12×N×(N−1)\tfrac12 \times N \times (N - 1)N = 5 → 10, N = 9 → 36
Same count by adding(N−1)+(N−2)+⋯+1(N - 1) + (N - 2) + \cdots + 14 + 3 + 2 + 1 = 10
Same count as choosing 2 from NNC2=N(N−1)/2{}^{N}C_2 = N(N - 1)/26C2=15{}^{6}C_2 = 15
Items per bin (K equal bins)N/KN / K9 / 3 = 3
Comparisons with K bins12×N×(N/K−1)\tfrac12 \times N \times (N/K - 1)12×9×2=9\tfrac12 \times 9 \times 2 = 9
Factor of reduction(N−1)/(N/K−1)(N - 1)/(N/K - 1)(9 − 1)/(3 − 1) = 4
Check on the lecture slide. The slide's growth table shows 49,500 for N = 100, but ½ × 100 × 99 = 4,950. Use 4,950.

Concepts from Weeks 1 to 4

ConceptWhat it gives youRemember
IteratorRepeat a task on every itemInitialise, continue?, update, with variables
DatatypesWell defined values and operationsboolean, integer, character, string, subtypes
List and recordBigger bundles of dataList: same type. Record: named fields, mixed types
FilteringProcess only some itemsConstant condition: count, sum. Variable condition: max
ProcedureReuse code with small changesA parameter variable, called with new values
AccumulationAn aggregate from many valuesCount, sum, average, or a collected list
Two iterations in sequenceElement versus the aggregateAccumulators from the first, filtering in the second
Nested iterationsElement versus any other elementCostly, so bin where possible

Which tool when?

SituationTool
Repeat a task on every cardAn iterator: initialise, continue?, update
Process only some of the cardsFiltering: a decision inside the loop
Count, sum or averageAccumulate into variables, filter with a constant
Maximum, or compare with a running valueFilter with a variable, e.g. X.Maths > Maxval
Same loop, small changeA procedure with a parameter variable
Compare each card with the aggregateTwo iterations: accumulate first, then filter
Compare any two cardsNested iterations, costly: ½ × N × (N − 1)
Too many comparisonsBin the items by a heuristic, compare inside bins

Common mistakes

Counting each pair twice
  • A with B and B with A are the same comparison. Compute N × (N − 1), then halve it.
Copying the slide's 49,500
  • For N = 100 the count is 4,950. Always recompute with ½ × N × (N − 1).
K-bin formula with unequal bins
  • (N − 1)/(N/K − 1) assumes K bins of equal size. Otherwise add up ½ × n × (n − 1) for each bin.
Forgetting the heuristic
  • Binning only helps if a rule puts the items into bins so that items in different bins never need comparing.
Merging the two iterations
  • An above-average test needs the average first: accumulate in iteration 1, filter in iteration 2.
Constant versus variable filters
  • X.Gender == F never changes. X.Maths > Maxval changes each time Maxval is updated.
Back to top