Neural Sync Active
computationalthinking-week2
Registry Synced
computationalthinking-week2
522 words
3 min read
Reading compass
Now · Week map
Loop patterns combine walking data with filters (AND predicates) and aggregates (sum, max, count).
Week map
Loop over collection → neutral start value → accumulate → scan for max/min → filter with AND → empty input edge cases.
Accumulation notation
- Sum accumulator → start 0 →
total ← total + x. - Product accumulator → start 1 →
prod ← prod * x. - Count accumulator → start 0 → increment when condition holds.
- Max scan → start first item or sentinel → replace when
x > best.
AND filter
All conditions must pass:
“positive and even” →
x > 0 and x % 2 == 0.Contrast OR (week 3 procedures): “positive or even” passes more items.
Mini-list:
[3, -4, 6, 8, -2]. Positive and even → only 6, 8.Max and min scans
textbest ← first item for each x in data: if x > best: best ← x
Empty
data: no first item — algorithm must guard or define error.Mini-example:
[5, 2, 9, 9, 1]. Max scan ends 9. For positive max only: ignore nonpositive, start best at first positive or None.Pattern families
Easy — Sum or count list
- Sum all elements.
- Count how many equal a target.
- Product of list (start 1).
Medium — Max with AND filter
- Largest among entries meeting two tests.
- Count items where both predicates true.
- Sum only negatives in list.
Hard — Compound loop logic
- Multiple accumulators in one pass (sum and count together).
- Empty list: max undefined; count returns 0.
- Index loop vs for-each — same totals if bounds correct.
Worked mini-examples
Example 1 — Sum.
Data
[10, 20, 5]. total=0 → 10 → 30 → 35.Example 2 — AND count.
Data
[2, 3, 4, 5, 6]. Count even and >3:- 4 yes, 6 yes → count 2.
Example 3 — Filtered max.
Data
[-1, 8, 3, 12, 5]. Max among positive:Candidates 8,3,12,5 → max 12.
Example 4 — Empty.
Data
[]. Sum loop leaves total=0. Max scan without guard — undefined; safe design returns sentinel or “no data”.Example 5 — Dual accumulator.
Data
[1,2,3,4]. Track sum and count of evens in one pass:Evens 2,4 → sum 6, count 2.
Traps
- Product accumulator starting at 0 (always 0).
- OR filter when problem says “all conditions”.
- Max of empty without check.
- Off-by-one manual index:
0..len-1not0..len. - Updating max before checking filter — polluted by ineligible items.
Diagnostic (try yourself)
-
List
[7, -2, 4, 0, 11]. What is the sum of positive entries only? -
Same list: how many entries are both positive and less than 10?
-
List
[3, 9, 1, 9, 2]. What is the maximum value? If we only consider values ≥ 5, what is the max? -
Why does product accumulation start at 1, not 0?
-
One pass: for
[5, 10, 15, 20], findsumandcountof multiples of 5.