Page 1 of 1

Code snippet: seededRandomTable and seededShuffle

Posted: Tue Oct 15, 2013 4:36 pm
by pixelfck
The seeded versions of the build in (randomTable ...) and (shuffle ...):

Code: Select all

(setq seededRandomTable (lambda (seed probabilityList)
   (block (result pick propabilitySum i)
      (setq i 0)
      (setq propabilitySum -1)
      (loop (ls i (count probabilityList))
         (block Nil
            (setq propabilitySum (add propabilitySum (@ probabilityList i)))
            (setq i (add i 2))
            )
         )
      (setq pick (seededRandom seed 0 propabilitySum))
      
      (setq i 0)
      (setq propabilitySum 0)
      (loop (ls i (count probabilityList))
         (block Nil
            (setq propabilitySum (add propabilitySum (@ probabilityList i)))
            
            (if (ls pick propabilitySum)
               (block Nil
                  (setq result (@ probabilityList (add i 1)))
                  (setq i (count probabilityList))
                  )
               
               (setq i (add i 2))
               )
            )
         )
      result
      )
   ))
   
(setq seededShuffle (lambda (seed theList)
   (block (shuffledList cursor)
      (setq cursor (subtract (count theList) 1))
      ; create a copy (we do not what the input list modified by reference)
      
      (setq shuffledList Nil)
      (enum theList theItem
         (setq shuffledList (lnkAppend shuffledList theItem))
         )
      
      ; shuffle the shuffledList in place
      (loop (gr cursor 0)
         (block (result pick)
            (setq pick (seededRandom seed 0 cursor))
            (setq result (@ shuffledList pick))
            (set@ shuffledList pick (@ shuffledList cursor))
            (set@ shuffledList cursor result)
            
            (setq cursor (subtract cursor 1))
            )
         )
      shuffledList
      )
   ))
Enjoy, Pixelfck