Last active
August 29, 2015 14:08
-
-
Save erasmas/a17e627826882a7a9839 to your computer and use it in GitHub Desktop.
Weekly coding interview problem (https://www.interviewcake.com/free-weekly-coding-interview-problem-newsletter)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
You have an array of integers, and for each index you want to find the product of every integer except the integer at that index. | |
Write a function get_products_of_all_ints_except_at_index() that takes an array of integers and returns an array of the products. | |
For example, given: | |
[1, 7, 3, 4] | |
your function would return: | |
[84, 12, 28, 21] | |
by calculating: | |
[7*3*4, 1*3*4, 1*7*4, 1*7*3] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; First solution that came to my mind ... | |
(defn get-products-of-all-ints-except-at-index | |
[ints] | |
(loop [ints ints | |
processed [] | |
products []] | |
(if (empty? ints) | |
products | |
(let [xs (rest ints) | |
product (apply * (concat processed xs))] | |
(recur xs | |
(conj processed (first ints)) | |
(conj products product)))))) | |
;; A cleaner solution by @mishadoff | |
(defn get-products-of-all-ints-except-at-index [ints] | |
(map-indexed (fn [i _] | |
(->> ints | |
(keep-indexed (fn [j e] (when (not= i j) e))) | |
(reduce *))) | |
ints)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment