Count All Matches
March 10, 2015
This is simple if you think recursively:
(define (count-all-matches needle haystack)
(let loop ((needle (string->list needle))
(haystack (string->list haystack)))
(cond ((null? needle) 1)
((null? haystack) 0)
((char=? (car needle) (car haystack))
(+ (loop (cdr needle) (cdr haystack))
(loop needle (cdr haystack))))
(else (loop needle (cdr haystack))))))
The first two cond
clauses check for termination: if the needle is empty, a match has been found, but if the haystack is empty when the needle is not, matching failed. In the third cond
clause, where the first characters of needle and haystack match, count the number of times the remainder of the needle and the remainder of the haystack match, and the last two cond
clauses also count the number of times the needle is found in the remainder of the haystack. Fortunately, the code is simpler than this long-winded explanation. Here are some examples:
> (count-all-matches "cat" "catapult")
3
> (count-all-matches "cap" "catapult")
2
> (count-all-matches "cut" "catapult")
1
> (count-all-matches "cup" "catapult")
0
You can run the program at http://ideone.com/SlYKiF.
Haskell:
In Python.
(defun count-all-matches (substr text)
(labels ((cam (ss tt)
(let ((count 0))
(cond ((null ss) 1)
((null tt) 0)
(t (loop while (setq tt (member (car ss) tt)) do
(incf count (cam (subseq ss 1) (subseq tt 1)))
(setq tt (subseq tt 1)))
count)))))
(cam (coerce substr ‘list) (coerce text ‘list))))))
My initial C++ solution was like Scott’s, but there were some problems with eg. “count aaaa aaaaaaaa” (the perils of imperative programming). The following seems to works (and when applied to the above, the intermediate arrays of counts make a nice illustration of Pascal’s triangle). It’s sort of a compact memoized/dynamic programming version of the recursive solution (and a good deal more efficient than generating all possible substrings and comparing each one with the target):
My previous solution fails for duplicate letters in the sub string e.g ‘tat’ –> ‘tatapult’. This corrects that mistake
Python.
If t is very long, you might want to preprocess it to remove characters that are not in s.
I think this is equivalent to Francesco’s Haskell:
Another Haskell solution.