challenge 重複無し乱数

整数nを渡すと1 ~ n までの整数を重複しないようランダムに出力する関数「bingo」を作ってください。

このお題はraynstardさんの投稿を元にしています。ご投稿ありがとうございました。 投稿の内容には表示のしかたも含まれていたのですが、 このお題では「重複しない1~nまでの乱数をどうやって作るか」という点に集中することにして、 結果の整形は続編としてこの後のお題で出すことにします。 サンプル入出力は下のようになります。

>>> bingo(10)
[10, 7, 8, 4, 5, 2, 3, 1, 6, 9]
>>> bingo(3)
[2, 3, 1]
>>> bingo(3)
[2, 3, 1]
>>> bingo(3)
[3, 1, 2]
>>> bingo(10)
[7, 3, 8, 6, 4, 10, 9, 2, 1, 5]

Posted feedbacks - Emacs Lisp

;;  random-permutation
(random t)
(bingo 10)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
(defun iota (n &optional a step)
  (setq step (or step 1))
  (do ((n n (- n 1))
       (ret '() (cons a ret))
       (a (or a 0) (+ a step)))
      ((<= n 0) (nreverse ret))))
(defun bingo (a &optional b)
  (let* ((ret (vconcat (mapcar '1+ (iota a b))))
	 (num (length ret))
	 val rnd)
    (dotimes (x  num ret)
      (setq rnd (random num)
	    val (aref ret x))
      (aset ret x (aref ret rnd))
      (aset ret rnd val))))

Index

Feed

Other

Link

Pathtraq

loading...