Count Items Matching a Rule
Problem
Each items[i] = [type, color, name]. A rule is two strings, ruleKey and ruleValue. The key picks a column: "type" → column 0, "color" → column 1, "name" → column 2. An item matches when that column equals ruleValue. Return how many items match.
items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver"1["computer","silver","lenovo"] has color "silver".def countMatches(items, ruleKey, ruleValue):
# map the rule key to the column it refers to
idx = {"type": 0, "color": 1, "name": 2}[ruleKey]
count = 0
for item in items:
if item[idx] == ruleValue: # compare just that column
count += 1
return count
function countMatches(items, ruleKey, ruleValue) {
// map the rule key to the column it refers to
const idx = { type: 0, color: 1, name: 2 }[ruleKey];
let count = 0;
for (const item of items) {
if (item[idx] === ruleValue) { // compare just that column
count++;
}
}
return count;
}
int countMatches(List<List<String>> items, String ruleKey, String ruleValue) {
// map the rule key to the column it refers to
int idx = ruleKey.equals("type") ? 0 : ruleKey.equals("color") ? 1 : 2;
int count = 0;
for (List<String> item : items) {
if (item.get(idx).equals(ruleValue)) { // compare just that column
count++;
}
}
return count;
}
int countMatches(vector<vector<string>>& items, string ruleKey, string ruleValue) {
// map the rule key to the column it refers to
int idx = ruleKey == "type" ? 0 : ruleKey == "color" ? 1 : 2;
int count = 0;
for (auto& item : items) {
if (item[idx] == ruleValue) { // compare just that column
count++;
}
}
return count;
}
Explanation
The rule names one of the three fields of every item. The first job is to turn that name into a column index: "type" is column 0, "color" is column 1, and "name" is column 2. A small lookup table (or a chain of comparisons) does this in one step.
Once we know which column to look at, the rest is a single pass. We walk through every item and compare just that one column against ruleValue. The other two columns are irrelevant, so an item like ["computer","silver","phone"] does not match the rule type == "phone" even though "phone" appears in its name.
Each time the chosen column equals ruleValue we add one to count. After scanning all items, count is the answer.
Example: with ruleKey = "color" the index is 1, so we read the middle field of each item. Only ["computer","silver","lenovo"] has "silver" there, giving a count of 1.
This works because the rule selects exactly one field and the match test is plain string equality. There is no need to sort, hash, or precompute anything beyond the index.