Question

I'm trying to find the most repeated element in a list. The problem is I have to use the count function, which finds how many time a specific value is repeated in a list (for example, (count 7 '(4 8 9 2 4 8 9)) => 0, (count 2 '(4 8 9 2 2 4 8 9 2)) => 3). I finished the count function and I think I'm close with the mode function. Any help will be appreciated.

(define (count item list)
  (cond
    [(null? list) '()]
    [(= item (car list)) (+ 1 (count item (cdr list)))]
    [#t (count item (cdr list))]))

(define (mode lst)
  (cond
    [(null? lst) '()]
    [(> (count (car lst) lst) (mode (cdr lst))) (car lst)]
    [else (mode (cdr lst))]))
Was it helpful?

Solution

It's mode night, as it seems - check a previous question, which uses a different approach: it assumes that the input list is sorted. But of course - the mode procedure can be implemented in terms of count with a non-sorted input list, although less efficiently - it's an O(n^2) solution:

(define (mode lnum)
  (let loop ((lst lnum)         ; list to traverse
             (max-counter 0)    ; number of times the mode appears
             (max-current #f))  ; the mode
    (if (null? lst)             ; if the list is empty
        max-current             ; return the mode
        (let ((n (count (car lst) lnum))) ; # of times current element appears
          (if (> n max-counter) ; if it appears more times
              (loop (cdr lst) n (car lst)) ; then we found a new maximum
              (loop (cdr lst) max-counter max-current)))))) ; else continue

The idea is simple, count how many times is each element in the list, and keep track of the element which appears the most.

And FYI, neither this nor the other linked solutions (which require that a sort is performed before) implement the most efficient algorithm for finding a mode in an unsorted list. See this answer, the most-common procedure implemented there also computes the mode of a list, but in O(n).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top