Last active
August 29, 2015 14:03
-
-
Save shicholas/a2f91d5690c88b203806 to your computer and use it in GitHub Desktop.
Investment Problem
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
(ns sample.investment) | |
;; c = cost-per-investment | |
;; a = additional-return-per-investment | |
;; g = goal | |
;; n = number-of-investments | |
;; i = current-income | |
;; t = time, with 0 being when we started | |
(defn- time-without-investing [g i t] (+ (/ g i) t)) | |
(defn- added-time-from-investing [c i t] (+ t (/ c i))) | |
(defn- income-after-investing-once [a i] (+ a i)) | |
(defn- time-with-investing-once [c a g i t] | |
(+ (/ g (income-after-investing-once a i)) (added-time-from-investing c i t))) | |
(defn- faster-to-not-invest? [c a g i t] | |
(< (time-without-investing g i t) (time-with-investing-once c a g i t))) | |
(defn time-until-goal | |
;; This function calculates the minimum amount of time necessary for | |
;; an investor to reach his/her goal. It checks the value of reaching | |
;; the goal without investing vs. reaching the goal with investing once. | |
;; If the latter is smaller than the former, the function recurses until | |
;; the opposite is true. | |
([c a g] | |
;; default values for n, i, and t | |
(let [n 0 | |
i 2 | |
t 0] | |
(if (faster-to-not-invest? c a g i t) | |
(time-without-investing g i t) | |
;; somewhat interesting I could not call recur here | |
(time-until-goal c a g (+ n 1) (income-after-investing-once a i) (added-time-from-investing c i t)) | |
))) | |
([c a g n i t] | |
(if (faster-to-not-invest? c a g i t) | |
(time-without-investing g i t) | |
(recur c a g (+ n 1) (income-after-investing-once a i) (added-time-from-investing c i t)) | |
)) | |
) | |
;; Solutions - I just used Cmd+Shift+Enter in Light Table to see the answers | |
(time-until-goal 30.5 3.14159 1999.1999) | |
(time-until-goal 30 2 100) | |
(time-until-goal 30 1 2) | |
(time-until-goal 500 4 2000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Question to the reader: How do you handle default values in Clojure functions? Here I used multi-arity, but maybe there's a better way?