This page is not created by, affiliated with, or supported by Slack Technologies, Inc.
2021-05-20
Channels
- # adventofcode (7)
- # announcements (1)
- # aws (1)
- # babashka (127)
- # bangalore-clj (1)
- # beginners (54)
- # calva (8)
- # cider (12)
- # clj-http (2)
- # clj-kondo (8)
- # cljdoc (10)
- # cljs-dev (2)
- # clojure (48)
- # clojure-australia (14)
- # clojure-dev (6)
- # clojure-europe (105)
- # clojure-nl (6)
- # clojure-taiwan (1)
- # clojure-uk (62)
- # clojurebridge (1)
- # clojurescript (112)
- # code-reviews (4)
- # cursive (20)
- # data-science (1)
- # depstar (1)
- # events (8)
- # fulcro (6)
- # graalvm (11)
- # honeysql (2)
- # introduce-yourself (3)
- # jobs (1)
- # jobs-discuss (30)
- # malli (23)
- # nrepl (4)
- # off-topic (47)
- # pedestal (22)
- # polylith (10)
- # portal (3)
- # re-frame (16)
- # reitit (9)
- # releases (3)
- # rewrite-clj (1)
- # ring (1)
- # spacemacs (1)
- # tools-deps (12)
- # xtdb (7)
https://prit.substack.com/p/hackerrank-step-perms https://prit.substack.com/p/hackerrank-maximum-toys
Updated
case
and compare
might help you make the cond
faster and/or more readable. Also, clojure.core
already has memoize
. And finally, rem
is a simpler (slightly faster) form of mod
, when you don't care about negative numbers:
(defn step-perms [n]
(let [memoed
(memoize
(fn f [n]
(case (compare n 3)
-1 n
0 4
(+ (f (dec n))
(f (- n 2))
(f (- n 3))))))]
(rem (memoed n) 10000000007)))
That being said, if you want peak performance, you'd want to preallocate a buffer for the "memoized" state, and compute it bottom-up. Looks like this:
(defn step-perms [n]
(case (compare n 3)
-1 n
0 4
(let [buf (int-array (inc n))
_ (aset buf 1 1)
_ (aset buf 2 2)
_ (aset buf 3 4)]
(loop [i 4]
(if (> i n)
(aget buf n)
(do
(aset buf i
(rem
(+ (aget buf (dec i))
(aget buf (- i 2))
(aget buf (- i 3)))
10000000007))
(recur (inc i)))))))
PS: haven't run these on Hackerrank