Fork me on GitHub
#code-reviews
<
2021-05-17
>
eckardjf17:05:08

(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))))

noisesmith17:05:24

we don't really use pascalCase but other than having too many expressions on one line at the end that looks fine

noisesmith17:05:36

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

eckardjf17:05:58

Thanks, I agree but the hackerrank stubs supply the odd camelCase names 🙂

noisesmith17:05:01

oops right, that's camelCase not PascalCase

noisesmith17:05:13

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)

seancorfield17:05:34

Strictly headlessCamelCase. Otherwise it’s CamelCase.

noisesmith17:05:36

or if you can't have a custom ns decl, just (import (java.util BitSet)) at the top level before the function definition

noisesmith17:05:01

@seancorfield that's a new one to me, not mentioned in the wiki article https://en.wikipedia.org/wiki/Camel_case

seancorfield17:05:08

Interesting that it’s mentioned here https://simple.wikipedia.org/wiki/CamelCase but not on the main wiki.

winkywooster17:05:45

(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)))

winkywooster17:05:15

is there a better way to do this? cl-format maybe?

noisesmith19:05:41

user=> (format "%010d" (rand-int 10000))
"0000007057"

noisesmith19:05:56

regular format handles it fine

noisesmith19:05:18

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"

👍 3
noisesmith19:05:54

also be careful providing arbitrary args to rand-int, you can easily generate an arg that is too large for Integer and error

noisesmith19:05:15

user=> (rand-int (Math/pow 10 10))
Execution error (IllegalArgumentException) at user/eval186 (REPL:1).
Value out of range for int: 4440081733

noisesmith20:05:43

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

noisesmith20:05:25

of course that + at the end could be bit-or

winkywooster20:05:51

cool, thanks @U051SS2EU. 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..