RandomizeWords

There are various ways to randomize words.

Randomizing Words And Not Touching Punctuation

Randomly sorting words in a region can be done with:

  (defun randomize-region (beg end)
    "Randomize the order of words in region."
    (interactive "*r")
    (let ((all (mapcar
                (lambda (w) (if (string-match "\\w" w)
                                ;; Randomize words,
                                (cons (random) w)
                              ;; keep everything else in order.
                              (cons -1 w)))
                (split-string
                 (delete-and-extract-region beg end) "\\b")))
          words sorted)
      (mapc (lambda (x)
              ;; Words are numbers >= 0.
              (unless (> 0 (car x))
                (setq words (cons x words))))
            all)
      ;; Random sort!
      (setq sorted (sort words
                         (lambda (a b) (< (car a) (car b)))))
      (mapc
       'insert
       ;; Insert using original list, `all', 
       ;; but pull *words* from randomly-sorted list, `sorted'.
       (mapcar (lambda (x)
                 (if (> 0 (car x))
                     (cdr x)
                   (prog1 (cdar sorted)
                     (setq sorted (cdr sorted)))))
               all))))

Running ‘M-x randomize-region’ on:

  first, second, third - last.

produces:

  second, third, last - first.

though, it may sometimes produce:

  first, second, third - last.

You never know.

Use ‘C-x z’ to repeat until properly shuffled.

Working with Comma-Separated Lists

The following can be used to comma-separated lists. Thus, you can use it where multiple words are a token such as the names of people.

  (defun randomize-comma-separated-list (start end)
    "Randomize order of the comma separated list in the region."
    (interactive "r")
    (let ((str (mapconcat 'identity
			  (sort (split-string (replace-regexp-in-string
					       "\\s-+" " "
					       (buffer-substring start end))
					      " ?, ?" t)
				(lambda (a b) (= 1 (random 2))))
			  ", ")))
      (delete-region start end)
      (insert str)))

Here’s an example of how it works.

Input:

Nigel Terry, Helen Mirren, Nicholas Clay, Cherie Lunghi, Paul
Geoffrey, Nicol Williamson, Robert Addie, Gabriel Byrne

Output:

Gabriel Byrne, Nigel Terry, Nicol Williamson, Helen Mirren, Robert Addie, Paul Geoffrey, Nicholas Clay, Cherie Lunghi

Alternatives

See SortWords for sorting the order of words alphabetically.


CategoryEditing