Changeset 37005 in project


Ignore:
Timestamp:
12/16/18 19:21:19 (3 months ago)
Author:
kon
Message:

vector-shuffle!

File:
1 edited

Legend:

Unmodified
Added
Removed
  • release/5/amb/trunk/amb.scm

    r37004 r37005  
    3939;;; data-structures
    4040
    41 (cond-expand
    42   (chicken-5
    43     (import
    44       (only (chicken fixnum) fx<)
    45       (only (chicken random) pseudo-random-integer)
    46       (only (chicken sort) sort!)
    47       (only (srfi 1) map!))
    48     (define platform-random pseudo-random-integer) )
    49   (chicken-4
    50     (use
    51       (only chicken fx<)
    52       (only extras random)
    53       (only data-structures sort!)
    54       (only (srfi 1) map!))
    55     (define platform-random random) ) )
    56 
    57 (: fx<car ((pair fixnum *) (pair fixnum *) --> boolean))
    58 ;
    59 (define (fx<car a b) (fx< (car a) (car b)))
     41(import
     42  (chicken type)
     43  (only (chicken fixnum) fx= fx+ fx- fxmod)
     44  (only (chicken random) pseudo-random-integer) )
     45(define platform-random pseudo-random-integer)
     46
     47(: vector-shuffle! ((vector-of *) #!optional (procedure (fixnum) fixnum) -> void))
     48;
     49(define (vector-shuffle! vec #!optional (rnd platform-random))
     50  (let (
     51    (len (vector-length vec)) )
     52    (define (swap-adj! i)
     53      (let (
     54        (i+1 (fxmod (fx+ i 1) len))
     55        (tmp (vector-ref vec i)) )
     56        (vector-set! vec i (vector-ref vec i+1))
     57        (vector-set! vec i+1 tmp) ) )
     58    (do ((n len (fx- n 1)))
     59        ((fx= n 0))
     60      (swap-adj! (rnd len)) ) ) )
    6061
    6162(: shuffle ((list-of *) #!optional (procedure (fixnum) fixnum) -> (list-of *)))
    6263;
    63 (define (shuffle ls #!optional (rand platform-random))
    64   (let* (
    65     (len (length ls))
    66     (tagged-ls (map (lambda (x) (cons (rand len) x)) ls)) )
    67     (map! cdr (sort! tagged-ls fx<car) ) ) )
     64(define (shuffle ls #!optional (rnd platform-random))
     65  (let (
     66    (vec (list->vector ls)) )
     67    (vector-shuffle! vec rnd)
     68    (vector->list vec) ) )
    6869
    6970;;; miscmacros
Note: See TracChangeset for help on using the changeset viewer.