Arc Forumnew | comments | leaders | submitlogin
1 point by rincewind 5983 days ago | link | parent

this only works for integer weightings

  (mac biased-choice choices
     (cons 'rand-choice (apply join (map [n-of car._ cadr._] pair.choices))))

  (def biased-choice choices
     (random-elt (apply join (map [n-of car._ cadr._] pair.choices))))
the second evaluates all of its arguments, which may or may not be what you want


1 point by rincewind 5983 days ago | link

this works for fractional weightings also

  (def reducecollect (sum list start)
    (if acons.list
        (let csum (sum start car.list)
            (cons csum (reducecollect sum cdr.list csum)))))

  (def zip args
   (when (all acons args) 
      (cons (map car args) (apply zip (map cdr args)))))

  (mac biased-choice choices
   (with (ranges (reducecollect + (map car pair.choices) 0)
          items (map cadr pair.choices)
          random (uniq))
          `(let ,random (* (rand) ,last.ranges)
               (if ,@(apply join (zip (map [list '< random _] ranges) items))))))

-----

3 points by rincewind 5977 days ago | link

zip (like that in python) can be written shorter with map

  (def zip args (apply map list args))

-----

1 point by skenney26 5977 days ago | link

And here's a better definition of unzip:

  (def unzip (xs (o n 2))
    (apply map list (tuples xs n)))

  arc> (unzip '(a b c d e f) 3)
  ((a d) (b e) (c f))

-----

1 point by tokipin 5982 days ago | link

you can multiply by 10^n to get n-digit decimal precision

-----