6 kyu

Fun with lists: countIf

744 of 1,581janitormeir

Description:

Implement the method countIf (count_if in PHP and Python), which accepts a linked list (head) and a predicate function, and returns the number of elements which apply to the given predicate.

For example: Given the list: 1 -> 2 -> 3, and the predicate x => x >= 2, countIf / count_if should return 2, since x >= 2 applies to both 2 and 3.

The linked list is defined as follows:

function Node(data, next = null) {
  this.data = data;
  this.next = next;
}
class Node<T> {
  public T data;
  public Node<T> next;
  
  Node(T data, Node next) {
    this.data = data;
    this.next = next;
  }
  
  Node(T data) {
    this(data, null);
  }
}
class Node {
  public $data, $next;
  public function __construct($data, $next = NULL) {
    $this->data = $data;
    $this->next = $next;
  }
}
struct Node {
    struct Node *next;
    int data;
};
class Node:
    def __init__(self, data, next=None): 
        self.data = data
        self.next = next

Note: the list may be null and can hold any type of value.

Good luck!

This kata is part of fun with lists series:

Lists
Functional Programming
Fundamentals

Stats:

CreatedNov 1, 2016
PublishedNov 1, 2016
Warriors Trained2822
Total Skips313
Total Code Submissions3799
Total Times Completed1581
JavaScript Completions744
Java Completions437
PHP Completions103
C Completions102
Python Completions294
Total Stars46
% of votes with a positive feedback rating95% of 359
Total "Very Satisfied" Votes327
Total "Somewhat Satisfied" Votes27
Total "Not Satisfied" Votes5
Total Rank Assessments10
Average Assessed Rank
6 kyu
Highest Assessed Rank
6 kyu
Lowest Assessed Rank
7 kyu
Ad
Contributors
  • janitormeir Avatar
  • donaldsebleung Avatar
  • trashy_incel Avatar
  • akar-0 Avatar
  • meni181818 Avatar
Ad