Problem of the Day
A new programming or logic puzzle every Mon-Fri

Filter Reduce

Today's problem is a two part problem. You'll be implementing a filter function and a reduce function.

Filter is a function that takes in a function and an array and runs each value of the array through the filter. The function passed in to the filter will return either a true or false value. For all values in the array that evaluate to true return that value. One example is an isOdd function with an array [1,2,3] which would return [1,3].

Reduce is a function that takes in a function and an array and runs each value of the array through the reducer. The goal is to run each item in the array through the list and then combine the output in to a single value. One example is an adder function with an array [1,2,3] which would return 6.

Permalink: http://problemotd.com/problem/filter-reduce/

Comments:

  • Mike N. - 9 years, 6 months ago

    Python:

    def isOdd(num):
        return (num%2==1)
    
    def adder(v1, v2):
        print(v1, "+", v2, "=", (v1+v2))
        return (v1+v2)
    
    def filter(array, function):
        newarray=[]
        for i in array:
            if (function(i)):
                newarray.append(i)
        return newarray
    
    def reduce(array, function):
        value=array[0]
        for i in array[1:]:
            value=function(value,i)
        return value
    
    array=[i for i in range(0,10)]
    print(array)
    array=filter(array, isOdd)
    print("Odds:", array)
    value=reduce(array, adder)
    print("Sum:", value)
    

    Output:

    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    Odds: [1, 3, 5, 7, 9]
    1 + 3 = 4
    4 + 5 = 9
    9 + 7 = 16
    16 + 9 = 25
    Sum: 25
    

    reply permalink

  • Driphter - 9 years, 6 months ago

    Clojure!

    (defn filter*
      [pred coll]
      (lazy-seq
        (when-let [s (seq coll)]
         (let [x (first s)]
           (if (pred x)
             (cons x (filter* pred (rest s)))
             (filter* pred (rest s)))))))
    
    (defn reduce*
      [f coll]
      (case (count coll)
        0 (f)
        1 (first coll)
        (loop [aggregate (first coll)
               coll      (next coll)]
          (if coll
            (recur (f aggregate (first coll)) (next coll))
            aggregate))))
    
    ; user=> (filter* odd? [1 2 3])
    ; (1 3)
    ; user=> (reduce* + [1 2 3])
    ; 6
    

    reply permalink

Content curated by @MaxBurstein