(defn flippingBits [n]
(let [bs (doto (java.util.BitSet/valueOf (long-array 1 n))
(.flip 0 32))]
(if (.isEmpty bs) 0 (aget (.toLongArray bs) 0))))
we don't really use pascalCase but other than having too many expressions on one line at the end that looks fine
I always put the condition of an if and each of the branches on their own line, so minimum three lines if the else arm is used
Thanks, I agree but the hackerrank stubs supply the odd camelCase names 🙂
oops right, that's camelCase not PascalCase
also, style wise I'd use (:import (java.util BitSet))
in the ns decl, instead of using the full class name in the code (both do work)
Strictly headlessCamelCase
. Otherwise it’s CamelCase
.
or if you can't have a custom ns decl, just (import (java.util BitSet))
at the top level before the function definition
@seancorfield that's a new one to me, not mentioned in the wiki article https://en.wikipedia.org/wiki/Camel_case
Interesting that it’s mentioned here https://simple.wikipedia.org/wiki/CamelCase but not on the main wiki.
(defn generate-pin [length]
"generate number string, with leading zeros, of specified length"
(let [r (rand-int (Math/pow 10 length))
z (- length (count (str r)))]
(str (clojure.string/join (repeat z "0")) r)))
is there a better way to do this? cl-format maybe?
user=> (format "%010d" (rand-int 10000))
"0000007057"
regular format handles it fine
more complete example
user=> (defn generate-pin
[length]
(let [r (rand-int (Math/pow 10 length))
fmt (str "%0" length "d")]
(format fmt r)))
#'user/generate-pin
user=> (generate-pin 8)
"00321275"
also be careful providing arbitrary args to rand-int, you can easily generate an arg that is too large for Integer and error
user=> (rand-int (Math/pow 10 10))
Execution error (IllegalArgumentException) at user/eval186 (REPL:1).
Value out of range for int: 4440081733
possible implementation for rand-long
(cmd)user=> (defn rand-long
[n]
(let [bytes-0-4 (rand-int (bit-and (long n) Integer/MAX_VALUE))
bytes-5-8 (if (< n Integer/MAX_VALUE)
0
(rand-int (bit-shift-right (long n) 32)))]
(+ bytes-0-4
(bit-shift-left bytes-5-8 32))))
#'user/rand-long
(cmd)user=> (rand-long 12)
3
(ins)user=> (rand-long (Math/pow 10 10))
277282388
of course that +
at the end could be bit-or
cool, thanks @noisesmith. yeah i don’t need pins longer than 7, and i was thinking bigint might be the way to go. but i like your approach to format..