Computational
Thinking 4
Reducing comparisons with binning, and a summary of the concepts from Weeks 1 to 4. Lectures 4.3 and 4.8.
Chapters
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.
| Element | Compared with | Comparisons |
|---|---|---|
| A | B, C, D, E | 4 |
| B | C, D, E | 3 |
| C | D, E | 2 |
| D | E | 1 |
| Total | 4 + 3 + 2 + 1 = 10 |
1.2A formula for the number of comparisons
For N objects the comparisons needed are (N − 1) + (N − 2) + ... + 1, which equals
the same as the number of ways of choosing 2 objects from N objects.
The same formula from first principles:
- Start:
N × N = 5 × 5 = 25pairs: every card with every card. - Remove the self comparisons (A with A):
N × N − N = 20, which isN × (N − 1). - A with B is the same as B with A. We double counted: halve it.
½ × N × (N − 1) = ½ × 5 × 4 = 10.
1.3The number of comparisons grows really fast
| N | N × (N − 1) / 2 |
|---|---|
| 2 | 1 |
| 3 | 3 |
| 4 | 6 |
| 5 | 10 |
| 6 | 15 |
| 7 | 21 |
| 8 | 28 |
| 9 | 36 |
| 10 | 45 |
| 100 | 4,950 |
| 1000 | 4,99,500 |
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.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:
- Comparisons per bin:
½ × 3 × (3 − 1) = ½ × 3 × 2 = 3. - Total for all 3 bins:
3 × 3 = 9. - 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:
| Quantity | Formula |
|---|---|
| Comparisons without binning | |
| Items in each bin | |
| Comparisons per bin | |
| Total comparisons with K bins | |
| Factor of reduction |
Check with N = 9 and K = 3: (9 − 1) / (3 − 1) = 8 / 2 = 4, as found above.
| K bins | Items per bin | Comparisons | Factor |
|---|---|---|---|
| none | 100 | 4,950 | 1 |
| 2 | 50 | 2,450 | 2.0× |
| 4 | 25 | 1,200 | 4.1× |
| 5 | 20 | 950 | 5.2× |
| 10 | 10 | 450 | 11.0× |
| 20 | 5 | 200 | 24.8× |
| 25 | 4 | 150 | 33.0× |
| 50 | 2 | 50 | 99.0× |
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
- 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).
- 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)
Numerical Answer Type (NAT).
How many comparisons are needed to compare every pair among 8 items?
Use ½ × N × (N − 1).
½ × 8 × 7 = 28(the lecture table has 28 for N = 8).- Answer: 28
Numerical Answer Type (NAT).
How many comparisons does a pile of 100 items need without binning?
Do not copy the slide table.
½ × 100 × 99 = 4,950, not 49,500.- Answer: 4950
Numerical Answer Type (NAT).
9 objects are put into 3 bins of 3. How many comparisons are needed in total?
Per bin ½ × 3 × 2.
- Each bin needs 3 comparisons, so
3 × 3 = 9(36 without bins). - Answer: 9
Numerical Answer Type (NAT).
20 students are put into 4 bins of 5. What is the factor of reduction in the number of comparisons?
Use (N − 1) / (N/K − 1).
(20 − 1) / (20/4 − 1) = 19 / 4 = 4.75, and190 / 40 = 4.75.- Answer: 4.75
Multiple Choice Question (MCQ): choose the one correct option.
With N items in K equal bins, the total number of comparisons is:
½ × N × (N − 1)½ × N × (N/K − 1)K × NN / KPer bin, then multiply by K.
- Per bin
½ × (N/K) × (N/K − 1); times K gives½ × N × (N/K − 1). - Answer: option 2.
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements.
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.
Numerical Answer Type (NAT).
10 items fall into bins of sizes 4, 3 and 3. How many comparisons are needed?
Add ½ × n × (n − 1) over the bins.
6 + 3 + 3 = 12.- Answer: 12
Study partner example
The count can be huge
½ × N × (N − 1)
Same as NC2
1000 items: 4,99,500
Slide's 49,500 for 100 is wrong
Compare only within a bin
9 items: 36 down to 9
Equal-size bins
N = 9, K = 3: 4
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.
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.
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.
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.
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.
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... | Meaning | Examples |
|---|---|---|
| a constant | the condition does not change after each iteration step | Count, Sum |
| a variable | the condition changes after an iteration step | max |
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.
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.
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.
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
- 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.
- 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)
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?
Count the F cards.
- The girls are cards 2, 4, 6 and 7:
Count = 4. - Answer: 4
Numerical Answer Type (NAT).
What is the sum of the boys' Maths marks on the same deck?
The boys are cards 1, 3, 5, 8.
95 + 96 + 42 + 70 = 303.- Answer: 303
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)?
Count the records.
- It changes at 95 (card 1) and at 96 (card 3); the final value is 96.
- Answer: 2
Numerical Answer Type (NAT).
What is the average of the eight Maths marks?
Sum divided by count.
577 / 8 = 72.125.- Answer: 72.125
Numerical Answer Type (NAT).
How many of the eight students have a Maths mark above the average?
Compare each mark with 72.125.
- The marks 95, 94, 96 and 80 (cards 1, 2, 3, 6) are above 72.125.
- Answer: 4
Multiple Choice Question (MCQ): choose the one correct option.
Which filter compares an item with a variable?
X.Gender == FX.Maths > MaxvalX.Gender == MWhich test changes when the loop updates something?
Maxvalchanges during the loop, so the testX.Maths > Maxvalchanges with it.- Answer: option 2.
Multiple Choice Question (MCQ): choose the one correct option.
For 6 people, how many comparisons does the nested iteration need without binning?
½ × N × (N − 1).
½ × 6 × 5 = 15.- Answer: option 2.
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements about above-average students.
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.
Variables hold values
Assignment statements
string and subtypes
List vs record
Constant: count, sum
Variable: max
Parameter variable
Call with a new value
Nested: two elements
Binning cuts comparisons
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
- 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.
- 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).
(N − 1) / (N/K − 1).- For N = 9 and K = 3 it is 8 / 2 = 4, so 36 comparisons become 9.
- Initialise, continue?, update.
- Add a decision inside the loop to filter, with a constant (count, sum) or a variable (max).
- Turn repeated code into a procedure with a parameter.
- Accumulate count, sum, average, or collect a list.
- One after another: accumulate, then filter with the accumulator.
- Nested: relate any two elements, which is costly, so use binning.
Formulas to remember
| Quantity | Formula | Example |
|---|---|---|
| Comparisons of all pairs of N items | N = 5 → 10, N = 9 → 36 | |
| Same count by adding | 4 + 3 + 2 + 1 = 10 | |
| Same count as choosing 2 from N | ||
| Items per bin (K equal bins) | 9 / 3 = 3 | |
| Comparisons with K bins | ||
| Factor of reduction | (9 − 1)/(3 − 1) = 4 |
½ × 100 × 99 = 4,950. Use 4,950.Concepts from Weeks 1 to 4
| Concept | What it gives you | Remember |
|---|---|---|
| Iterator | Repeat a task on every item | Initialise, continue?, update, with variables |
| Datatypes | Well defined values and operations | boolean, integer, character, string, subtypes |
| List and record | Bigger bundles of data | List: same type. Record: named fields, mixed types |
| Filtering | Process only some items | Constant condition: count, sum. Variable condition: max |
| Procedure | Reuse code with small changes | A parameter variable, called with new values |
| Accumulation | An aggregate from many values | Count, sum, average, or a collected list |
| Two iterations in sequence | Element versus the aggregate | Accumulators from the first, filtering in the second |
| Nested iterations | Element versus any other element | Costly, so bin where possible |
Which tool when?
| Situation | Tool |
|---|---|
| Repeat a task on every card | An iterator: initialise, continue?, update |
| Process only some of the cards | Filtering: a decision inside the loop |
| Count, sum or average | Accumulate into variables, filter with a constant |
| Maximum, or compare with a running value | Filter with a variable, e.g. X.Maths > Maxval |
| Same loop, small change | A procedure with a parameter variable |
| Compare each card with the aggregate | Two iterations: accumulate first, then filter |
| Compare any two cards | Nested iterations, costly: ½ × N × (N − 1) |
| Too many comparisons | Bin the items by a heuristic, compare inside bins |
Common mistakes
- A with B and B with A are the same comparison. Compute
N × (N − 1), then halve it.
- For N = 100 the count is 4,950. Always recompute with
½ × N × (N − 1).
(N − 1)/(N/K − 1)assumes K bins of equal size. Otherwise add up½ × n × (n − 1)for each bin.
- Binning only helps if a rule puts the items into bins so that items in different bins never need comparing.
- An above-average test needs the average first: accumulate in iteration 1, filter in iteration 2.
X.Gender == Fnever changes.X.Maths > Maxvalchanges each timeMaxvalis updated.