SECTION 06 / 17

Tutorial: same city AND same Maths mark

1 min read

Find pairs of different students with both the same CityTown and the same Mathematics mark. Checking only city counts too many pairs. Checking only Maths may match students from different cities.

Rahul and Deepika both come from Bengaluru and both have 97 in Mathematics. City bins reduce complete pair checks from 435 to 55.
Rahul and Deepika both come from Bengaluru and both have 97 in Mathematics. City bins reduce complete pair checks from 435 to 55.
REAL COURSE DATA · THINK BEFORE EACH STEP

Same city and same Maths

Trace the records, compare the methods and watch what changes. Back and Reset let you try again.

Ready

CURRENT RECORD X

Ready to begin

Choose Next step to follow the actual course records.

What we remember

Processed
0

Start with Next step. Predict what changes before reading the explanation.

Count = 0
while Table1 has rows:
    read first row X
    move X from Table1 to Table2
    while Table1 has rows:
        read first row Y
        if X.CityTown == Y.CityTown AND X.Mathematics == Y.Mathematics:
            Count = Count + 1
        move Y from Table1 to Table3
    move all rows from Table3 back to Table1
# Table2 contains the processed outer rows. Count is 1.

Moving X out before the inner scan prevents self-comparison. Keeping processed X rows in Table2 prevents reversed duplicate pairs. Table3 holds inner-scan rows temporarily. Return ALL of Table3 to Table1 after each inner scan, or later outer cards will have no partners left to inspect. Here a different order among remaining rows is harmless as long as all remain and each outer row is eventually removed once.

CityRowsPairs
Ambur10
Bengaluru510
Chennai828
Erode21
Madurai510
Nagercoil10
Salem10
Theni10
Trichy33
Vellore33
Total3055

After grouping by CityTown, the inner test can be just X.Mathematics == Y.Mathematics because city equality is guaranteed by bin membership. The final answer remains 1. The preparation changes the work, not the matching rule.

Try it yourself

Does binning by city mean that every pair within Chennai is a match?

Show explained answer

No. City equality is guaranteed, but Maths equality must still be tested.

Try it yourself

Why must Table3 be restored after EACH inner scan?

Show explained answer

Those rows are still candidates for later outer rows. Without restoring them, the outer loop would stop after inspecting only the first X.

Try it yourself

If three students in one city all have the same Maths mark, what does Count gain?

Show explained answer

Three pairs, not one city or three separate matches with themselves: A–B, A–C and B–C.

YOUR STUDY PROGRESS

Finished this section? Save your progress.

Back to top ↑