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

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

Re: Random number generation in LISP or using it


From: TomSW
Subject: Re: Random number generation in LISP or using it
Date: Thu, 11 Jun 2009 00:34:12 -0700 (PDT)
User-agent: G2/1.0

On Jun 10, 5:21 pm, bolega <gnuist...@gmail.com> wrote:
> I am a newbie with the following problem.
>
> A the outset let me state that the limitation is that I have to use
> this inside emacs to scramble a set of chosen lines like you do
> "reverse-region" or "sort-lines". It is possible that I can call some
> scheme or clisp functions.

Grab the lines into an array, shuffle the array, re-insert the
lines :)

hth
Tom SW

------

(require 'cl) ; provides useful things like loop and setf

(defun shuffle-vector (vector)
  "Destructively shuffle the contents of VECTOR and return it."
  (loop
     for pos from (1- (length vector)) downto 1
     for swap = (random (1+ pos))
     unless (= pos swap)
     do (rotatef (aref vector pos)
                 (aref vector swap)))
  vector)

(defun randomize-region (start end)
  "Randomly re-order the lines in the region."
  (interactive "r")
  (save-excursion
    (save-restriction
      ;; narrow to the region
      (narrow-to-region start end)
      (goto-char (point-min))
      (let* ((nlines (line-number-at-pos end))
             (lines (make-vector nlines nil)))
        ;;
        (while (not (eobp))
          (setf (aref lines (decf nlines)) ; if it's random backwards
is fine
                (delete-and-extract-region (point)
                                           (progn (forward-visible-
line 1)
                                                  (point)))))
        ;;
        (let ((rlines (shuffle-vector lines)))
          (dotimes (linenum (length rlines))
            (insert (aref rlines linenum))))))))


reply via email to

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