[ create a new paste ] login | about

Project: programmingpraxis
Link: http://programmingpraxis.codepad.org/QKrX5JfK    [ raw code | output | fork ]

programmingpraxis - Scheme, pasted on Oct 11:
; rotate an array

(define (swap! v i j)
  (let ((t (vector-ref v i)))
    (vector-set! v i
      (vector-ref v j))
    (vector-set! v j t)))

(define (reverse! v lo hi)
  (when (< lo hi)
    (swap! v lo hi)
    (reverse! v (+ lo 1) (- hi 1))))

(define (rotate! n v)
  (let* ((len (vector-length v))
         (n (modulo n len)))
    (reverse! v 0 (- n 1))
    (reverse! v n (- len 1))
    (reverse! v 0 (- len 1))))

(define v (vector 1 2 3 4 5 6))
(display v) (newline)
(rotate! 2 v)
(display v) (newline)
(rotate! -2 v)
(display v) (newline)
(rotate! 8 v)
(display v) (newline)


Output:
1
2
3
4
#(1 2 3 4 5 6)
#(3 4 5 6 1 2)
#(1 2 3 4 5 6)
#(3 4 5 6 1 2)


Create a new paste based on this one


Comments: