Changeset 37006 in project


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

vector-shuffle!

File:
1 edited

Legend:

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

    r37003 r37006  
    158158;;;
    159159
    160 (cond-expand
    161   (chicken-5
    162     (import
    163       (only (chicken fixnum) fx<)
    164       (only (chicken random) pseudo-random-integer)
    165       (only (chicken sort) sort!)
    166       (only (srfi 1) map!))
    167     (define platform-random pseudo-random-integer) )
    168   (chicken-4
    169     (use
    170       (only chicken fx<)
    171       (only extras random)
    172       (only data-structures sort!)
    173       (only (srfi 1) map!))
    174     (define platform-random random) ) )
     160(use
     161  (only chicken fx= fx+ fx- fxmod)
     162  (only extras random))
     163(define platform-random random)
    175164
    176 (: fx<car ((pair fixnum *) (pair fixnum *) --> boolean))
     165(: vector-shuffle! ((vector-of *) #!optional (procedure (fixnum) fixnum) -> void))
    177166;
    178 (define (fx<car a b) (fx< (car a) (car b)))
     167(define (vector-shuffle! vec #!optional (rnd platform-random))
     168  (let (
     169    (len (vector-length vec)) )
     170    (define (swap-adj! i)
     171      (let (
     172        (i+1 (fxmod (fx+ i 1) len))
     173        (tmp (vector-ref vec i)) )
     174        (vector-set! vec i (vector-ref vec i+1))
     175        (vector-set! vec i+1 tmp) ) )
     176    (do ((n len (fx- n 1)))
     177        ((fx= n 0))
     178      (swap-adj! (rnd len)) ) ) )
    179179
    180180(: shuffle ((list-of *) #!optional (procedure (fixnum) fixnum) -> (list-of *)))
    181181;
    182 (define (shuffle ls #!optional (rand platform-random))
    183   (let* (
    184     (len (length ls))
    185     (tagged-ls (map (lambda (x) (cons (rand len) x)) ls)) )
    186     (map! cdr (sort! tagged-ls fx<car) ) ) )
     182(define (shuffle ls #!optional (rnd platform-random))
     183  (let (
     184    (vec (list->vector ls)) )
     185    (vector-shuffle! vec rnd)
     186    (vector->list vec) ) )
    187187
    188188) ;module amb
Note: See TracChangeset for help on using the changeset viewer.