DEV Community

Cover image for 1773. Count Items Matching a Rule.
Tahzib Mahmud Rifat
Tahzib Mahmud Rifat

Posted on

1773. Count Items Matching a Rule.

Introduction

Image description

Here our problem says, there are one 2D list of items and one ruleKey and ruleValue. We have to traverse all the element and first match with the ruleKey value. If ruleKey is "type" then we will check the ruleValue with the first elements of the list.

Examples

Image description

Hint

Image description

Steps

  1. Take counter variable
  2. Run a for each loop
  3. Check if ruleKey value == type, and ruleValue == item(0)
  4. Or ruleKey == color, and ruleValue == item(1)
  5. or ruleKey == name, and ruleValue == item(2)
  6. Now if any of these are true then increase the count.
  7. return the count.

JavaCode

import java.util.List;

class Solution {
    public int countMatches(List<List<String>> items, String ruleKey, String ruleValue) {
        int count = 0;
            for(List<String> item : items) {
        if  (("type".equals(ruleKey) && ruleValue.equals(item.get(0)))
        ||  ("color".equals(ruleKey) && ruleValue.equals(item.get(1)))
        ||  ("name".equals(ruleKey) && ruleValue.equals(item.get(2)))){
                    count++;
                }
            }
        return count;
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Image description

Top comments (0)