gaucheノート  トランプ シャッフル(見切り発車)(編集中)

乱数を生成する

gosh> (use srfi-27)
#<undef>
gosh> (random-integer 5)
4
gosh> (random-integer 5)
0
gosh> (map random-integer '(5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5))
(4 4 0 4 4 1 3 1 0 2 1 0 2 4 4 4 4 4 0 3)

take*とdrop* (寛容♡)

gosh> (define (make-heart i) (string-append "h" (number->string i)))
make-heart
gosh> (define cards (map make-heart (iota 13 1 1)))
cards
gosh> cards
("h1" "h2" "h3" "h4" "h5" "h6" "h7" "h8" "h9" "h10" "h11" "h12" "h13")
gosh> (use util.list)
#<undef>
gosh> (take* cards 3)
("h1" "h2" "h3")
gosh> (drop* cards 3)
("h4" "h5" "h6" "h7" "h8" "h9" "h10" "h11" "h12" "h13")

リストxからn番目の要素を除いたリストを返す関数

gosh> (define (remains x n)   
(if (= (length x) 1) x
    (append (take* x n) (drop* x (+ n 1))))
)
remains
gosh> (remains cards 2)
("h1" "h2" "h4" "h5" "h6" "h7" "h8" "h9" "h10" "h11" "h12" "h13")
gosh> (remains cards 0)
("h2" "h3" "h4" "h5" "h6" "h7" "h8" "h9" "h10" "h11" "h12" "h13")
gosh> (remains cards 12)
("h1" "h2" "h3" "h4" "h5" "h6" "h7" "h8" "h9" "h10" "h11" "h12")

リストxをシャッフルしたリストを返す関数

gosh> (define (shuffle x)
(let ((n (random-integer (length x))))
  (if (= (length x) 1) x
      (append (list (ref x n)) (shuffle (remains x n)))))
)
shuffle
gosh> (shuffle cards)
("h3" "h8" "h13" "h12" "h11" "h10" "h9" "h1" "h6" "h7" "h5" "h4" "h2")
gosh> (shuffle cards)
("h2" "h7" "h11" "h12" "h4" "h3" "h1" "h8" "h5" "h13" "h9" "h10" "h6")