Listing Pairs with Nested Loops

Nested loops generate pairs by combining outer and inner positions. The bounds determine whether pairs repeat.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Count every combination
  2. Check a three-item list
  3. Derive a pair count from modeled roles
  4. Check what identity means when values repeat

Count every combination

Matching two shirt colors with three sizes yields six combinations. A nested loop can hold one color fixed while visiting each size. When choosing two items from the same list, pairs of indices satisfying \(i<j\) exclude self-pairs and reversed duplicates. Write this in the pseudocode.

Check a three-item list

For indices 0, 1, 2 the desired pairs are \((0,1),(0,2),(1,2)\). If a loop also yields \((1,0)\), the inner loop's start is too early. Use range bounds derived from the outer position.[1]

Derive a pair count from modeled roles

To combine three rooms and four time slots, visit all four slots for each room. That gives twelve pairs because the roles are distinct. For choosing two teammates from one list, index pairs can require first index less than second to avoid choosing the same position twice or reversing the combination. With four people, the first index has three later partners, then two and one, giving six choices. Counting unordered combinations gives the corresponding formula.

Check what identity means when values repeat

A list of tool sizes 2, 2, and 5 can contain two independent tools of equal size. If the rule chooses two distinct positions, the pair made from the two twos is valid. If it chooses two distinct sizes, that pair is outside the rule. A testable pseudocode specification states exactly which pairs are emitted.

Try empty input, one item, and values with two equal entries. Compare the ordered output with a hand-derived list. When both source lengths can grow, keeping their sizes visible in the bound avoids assuming a square grid. See two input sizes.

References

  1. Python Software Foundation, Python Tutorial: Control Flow ↩