How to generate repeatable random sequences with rand-int

前端 未结 7 1596
你的背包
你的背包 2021-02-08 18:22

I want to be able to generate repeatable numbers using rand in Clojure. (Specifically, I want results of calls to rand-nth or Incanter\'s sample

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-08 18:40

    From what I understand, none of the above are functional approaches. If you want that, you can use a lazy-seq:

    (letfn [(f [randomizer]  (lazy-seq (cons (.nextInt randomizer) (f randomizer))))]
      (defn create-random 
        ([] (f (java.util.Random.)))
        ([seed] (f (java.util.Random. seed)))))
    

    To get the first random number you use:

    (first (create-random 0)) ;; using 0 as seed
    

    To get the rest of the sequence you use:

    (rest (create-random 0)) ;; again 0 as seed
    

    To get the first element and a reference to the rest you can use:

    (defn pop [x (create-random 0)]
         (n, rest) `(~(first x) ~(rest x)))
    

提交回复
热议问题