Pairs that add up
Inputs
values is a list of 0 to 12 whole numbers, each from 0 to 15. target is a whole number from 0 to 30.
Your tasks
- Create a number
countthat starts at 0. - Use an outer loop over each position
i. Inside it, use an inner loop over each positionjafteri. - Add 1 to
countwhenevervalues[i] + values[j]equalstarget. - Complete
countPairsWithSumso it returnscount. Return it, do not print it.
Example
With values = [1, 5, 3, 3, 7] and target = 6, countPairsWithSum returns 2.
Rules
- Each pair of positions is counted once. Position pairs
(i, j)and(j, i)are the same pair.
Test data
TEST DATA 1: values is [1, 5, 3, 3, 7], target is 6
TEST DATA 2: values is [], target is 4
Practice focus
Nested loops compare every pair and build rows. The slow, simple answer to most problems is two loops. Knowing it is what lets you see how to beat it.