Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shuffle list in lisp?

It's very simple program which just return the input as a list shuffled. I wrote this program in python. Now I want to convert this program to lisp code. but I couldn't. How do I write down this program in lisp?

def my_shuffle(a, b, c, d):
    return [b, c, d, a]

I tried the following code but an error occur.

(defun my_shuffle (a b c d) (list b c d a))
like image 429
Kei Minagawa Avatar asked Mar 26 '18 11:03

Kei Minagawa


1 Answers

Thee are several things here that I think that need to be pointing out. First the code that you presented is correct but do shuffle a list, present a new list of four algorithms that you pass, allways with the same order. First of all shuffle a sequence is:

generating a random permutation of a finite sequence

From wikipedia you can find several algorithms for that:

https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

Also in the rosseta code there is an implementation of the knuth shuffle:

(defun nshuffle (sequence)
  (loop for i from (length sequence) downto 2
        do (rotatef (elt sequence (random i))
                    (elt sequence (1- i))))
  sequence)

Then if you apply this in the repl:

CL-USER> (nshuffle (list 1 2 3 4))
(3 1 4 2)
CL-USER> (nshuffle (list 1 2 3 4))
(3 1 2 4)

Note Two different results on the same list!!! (also the same can happen, because is a random order)

In python there are build algorithms for that:

https://docs.python.org/3/library/random.html#random.shuffle

also in the Common lisp library Alexandria:

CL-USER> (ql:quickload :alexandria)
To load "alexandria":
  Load 1 ASDF system:
    alexandria
; Loading "alexandria"

(:ALEXANDRIA)
CL-USER> (alexandria:shuffle (list 1 2 3 4))
(3 2 4 1)
like image 62
anquegi Avatar answered Nov 15 '22 15:11

anquegi