help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: random predicate function


From: Pascal J. Bourguignon
Subject: Re: random predicate function
Date: Mon, 13 Dec 2010 16:26:03 +0100
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/23.2 (gnu/linux)

Tyler Smith <tyler.smith@eku.edu> writes:

> Hi,
>
> I'm trying to write a function that will randomly sort the paragraphs in
> a region. It seems to work ok, except that it doesn't seem very random.
> I think the function I'm using to randomly generate true and false
> values is sub-optimal. It often generates long strings of 't' or nil,
> such that either the paragraph order doesn't change at all for multiple calls
> to the function, or it simply reverses the order each time I call it.
>
> Any suggestions welcome! Thanks.
>
> Tyler
>
> Here is the function:

You shoud not use sort to randomize, because it's suboptimal
[ O(n*log(n)) at best instead of O(n) ].

And foremost, you should not use a predicate that is not a total order
because this usually gives invalid results.

Google for: shuffle algorithm.


You could instead put your paragraphs in a vector and use:

(defun shuffle (vector)
  "Re-orders randomly the vector."
  (loop
      for i from (1-  (length vector)) downto 1
      do (rotatef (aref vector i) (aref vector (random i)))))

to shuffle them and then re-insert them.


-- 
__Pascal Bourguignon__                     http://www.informatimago.com/
A bad day in () is better than a good day in {}.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]