Search code examples
clojure

Why does my random function doesn't always work?


My function is supposed to give me 6 numbers, but to avoid zero and should not repeat any number, but sometimes it brings me 0 or repeated numbers

(defn function
  []
  (def lista (sort (take 6 (repeatedly #(rand-int 60)))))
  (loop []
    (when (or (= (contains? (set lista) 0) true) (< (count (set lista)) 6))
      (def lista (sort (take 6 (repeatedly #(rand-int 60)))))))
  (println lista))

Solution

  • to solve your problem you dont need that function. you can take a random 10 and call on set function to remove duplicates and filter ponly for positive numbers and take 6 from it. code goes something like this. 20 is just a random sample

    (take 6 (filter pos? (set (take 20 (repeatedly #(rand-int 60))))))
    

    or

    (->> #(rand-int 60) (repeatedly) (take 20) (set) (filter pos?) (take 6) )