Created
October 3, 2019 14:49
-
-
Save ampersanda/1aeccdc2465ee5112d97ada9ac33ffae to your computer and use it in GitHub Desktop.
This file contains 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
; When a candle finishes burning it leaves a leftover. makeNew leftovers can be combined to make a new candle, which, when burning down, will in turn leave another leftover. | |
; You have candlesNumber candles in your possession. What's the total number of candles you can burn, assuming that you create new candles as soon as you have enough leftovers? | |
; Example | |
; For candlesNumber = 5 and makeNew = 2, the output should be | |
; candles(candlesNumber, makeNew) = 9. | |
; Here is what you can do to burn 9 candles: | |
; burn 5 candles, obtain 5 leftovers; | |
; create 2 more candles, using 4 leftovers (1 leftover remains); | |
; burn 2 candles, end up with 3 leftovers; | |
; create another candle using 2 leftovers (1 leftover remains); | |
; burn the created candle, which gives another leftover (2 leftovers in total); | |
; create a candle from the remaining leftovers; | |
; burn the last candle. | |
; Thus, you can burn 5 + 2 + 1 + 1 = 9 candles, which is the answer. | |
; Input/Output | |
; [execution time limit] 16 seconds (clj) | |
; [input] integer candlesNumber | |
; The number of candles you have in your possession. | |
; Guaranteed constraints: | |
; 1 ≤ candlesNumber ≤ 15. | |
; [input] integer makeNew | |
; The number of leftovers that you can use up to create a new candle. | |
; Guaranteed constraints: | |
; 2 ≤ makeNew ≤ 5. | |
; [output] integer | |
; [Clojure] Syntax Tips | |
; Prints help message to the console | |
; Returns a string | |
; (defn helloWorld [name] | |
; (println "This prints to the console when you Run Tests") | |
; (apply str (concat "Hello, " name))) | |
(defn candles [candlesNumber makeNew] | |
{:pre [(not (nil? candlesNumber)) | |
(>= candlesNumber 1) | |
(<= candlesNumber 15) | |
(not (nil? makeNew)) | |
(>= makeNew 2) | |
(<= makeNew 5)]} | |
(if (> makeNew candlesNumber) | |
candlesNumber | |
(loop [remaining candlesNumber | |
result [candlesNumber]] | |
(let [mod-result (mod remaining makeNew) | |
factor-count (int (double (/ remaining makeNew)))] | |
(if (<= remaining makeNew) | |
(reduce + (flatten [result factor-count])) | |
(recur | |
(+ mod-result factor-count) | |
(conj result factor-count))))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment