# Problem of the DayA 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.

• Mike N. - 9 years ago

Python:

``````def isOdd(num):
return (num%2==1)

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)
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
``````
• - 8 years, 12 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
``````

Content curated by @MaxBurstein
{"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0}