【心得】
/
寫成 quot
,後者是 quotient 商數的意思,其實兩者效果幾乎是一樣。quot
一定要接收兩個參數,/
多了只接收一個參數 ex. (/ 2) => 1/2,只有一個的時候,給的參數會變成分母,分子則一定是 1【今日湯底】
Task
Given an array/list [] of integers , Construct a product array Of same size Such That prod[i] is equal to The Product of all the elements of Arr[] except Arr[i].
productArray ({1,5,2}) ==> return {10,2,5}
Explanation:
The first element 10 is the product of all array's elements except the first element 1
The second element 2 is the product of all array's elements except the second element 5
The Third element 5 is the product of all array's elements except the Third element 2.
(必須通過以下測試)
(ns kata.test
(:require [clojure.test :refer :all]
[kata :refer [product-array]]))
(deftest basic-tests
(is (= (product-array [12 20]) [20 12]))
(is (= (product-array [3 27 4 2]) [216 24 162 324]))
(is (= (product-array [13 10 5 2 9]) [900 1170 2340 5850 1300]))
(is (= (product-array [16 17 4 3 5 2]) [2040 1920 8160 10880 6528 16320])))
【我的答案】
(ns kata)
(defn product-array [numbers]
(map #(/ (reduce * numbers) %) numbers)
)
思路:
remove
function 無法做到我的需求,而是比較像反向的 filter【其他人的答案】
(ns kata)
(defn product-array [xs] (let [p (reduce * xs)] (map #(quot p %) xs)))