I'm trying to learn elisp. I wanted to use (random n)
and then
take the result of (random n)
and use it to compute a new random
number until we reach 1.
Something like this:
(random 100)
99
(random 99)
51
(random 51)
24
(random 24)
11
(random 11)
3
(random 3)
2
(random 2)
1
How do I assign, the new value of n
to (random n)
?
(setq n (random n))
does not work. This gives a constant number, (random n)
is not calculated.
Can you give me a hint? I realize this is a total newbie question. Thanks.
EDİT
(defun rnd (n)
(setq counter 0)
(let ((ret ()))
(while (< 1 n)
(setq n (random n))
(setq counter (+ counter 1))
(push n ret))
(reverse ret))
)
(format "list: %s \n steps: %s" (rnd 100000) counter)
You cannot change the value of an external variable from within a function:
(defvar n 100)
(defun rnd (n)
(setq n (random n)))
(rnd n)
will not change the value of n
because rnd
create a new binding for n
.
This, however, should work:
(defvar n 100)
(defun rnd ()
(setq n (random n)))
Or you can just do a loop inside rnd
:
(defun rnd (n)
(let ((ret ()))
(while (< 1 n)
(setq n (random n))
(push n ret))
ret))
(rnd 100)
==> (1 3 8 16 20 27 53)