fork(1) download
  1. ; one-swappable array
  2.  
  3. (define (swappable? xs)
  4. (define (x i) (vector-ref xs i))
  5. (define (swap! i j)
  6. (let ((t (vector-ref xs i)))
  7. (vector-set! xs i
  8. (vector-ref xs j))
  9. (vector-set! xs j t)))
  10. (define (sorted? i j)
  11. (cond ((= i j) #t)
  12. ((not (< (x i) (x (+ i 1)))) #f)
  13. (else (sorted? (+ i 1) j))))
  14. (let* ((len (vector-length xs))
  15. (left (let loop ((i 0))
  16. (if (= i (- len 1)) #f
  17. (if (< (x (+ i 1)) (x i)) i
  18. (loop (+ i 1))))))
  19. (right (let loop ((j (- len 1)))
  20. (if (= j 1) #f
  21. (if (< (x j) (x (- j 1))) j
  22. (loop (- j 1)))))))
  23. (if (not (and left right)) #f
  24. (begin
  25. (swap! left right)
  26. (if (sorted? (max (- left 1) 0)
  27. (min (+ right 1) (- len 1)))
  28. (list left right)
  29. #f)))))
  30.  
  31. (display (swappable? '#(1 2 6 4 5 3 7))) (newline)
  32. (display (swappable? '#(7 6 5 4 3 2 1))) (newline)
  33. (display (swappable? '#(1 2 3 4 5 6 7))) (newline)
  34. (display (swappable? '#(7 2 3 4 5 6 1))) (newline)
  35. (display (swappable? '#(1 2 4 3 5 6 7))) (newline)
  36. (display (swappable? '#(2 7 3 4 5 1 6))) (newline)
Success #stdin #stdout 0.01s 7268KB
stdin
Standard input is empty
stdout
(2 5)
#f
#f
(0 6)
(2 3)
#f