Permutations: Difference between revisions

→‎{{header|Tcl}}: adding scheme
(→‎{{header|Tcl}}: adding scheme)
Line 975:
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
</pre>
 
=={{header|Scheme}}
<lang scheme>; translation of ocaml : mostly iterative, with auxiliary recursive functions for some loops
(define (next-perm p)
(let* ((n (vector-length p))
(i (letrec ((aux (lambda (i)
(if (or (< i 0) (< (vector-ref p i) (vector-ref p (+ i 1))))
i (aux (- i 1)))))) (aux (- n 2)))))
(letrec ((aux (lambda (j k)
(if (< j k)
(let ((tmp (vector-ref p j)))
(vector-set! p j (vector-ref p k))
(vector-set! p k tmp)
(aux (+ j 1) (- k 1)))))))
(aux (+ i 1) (- n 1)))
(if (< i 0) #f
(let* ((j (letrec ((aux (lambda (j)
(if (> (vector-ref p j) (vector-ref p i))
j
(aux (+ j 1))))))
(aux (+ i 1))))
(tmp (vector-ref p i)))
(vector-set! p i (vector-ref p j))
(vector-set! p j tmp)
#t))))
 
(define (print-perm p)
(let ((n (vector-length p)))
(do ((i 0 (+ i 1))) ((= i n)) (display (vector-ref p i)) (display " "))
(newline)))
 
(define (print-all-perm n)
(let ((p (make-vector n)))
(do ((i 0 (+ i 1))) ((= i n)) (vector-set! p i i))
(print-perm p)
(do ( ) ((not (next-perm p))) (print-perm p))))
 
(print-all-perm 3)
; 0 1 2
; 0 2 1
; 1 0 2
; 1 2 0
; 2 0 1
; 2 1 0</lang>
 
=={{header|Tcl}}==
506

edits