Ordered partitions: Difference between revisions
Content added Content deleted
(Added Elixir) |
(Added EchoLisp) |
||
Line 635: | Line 635: | ||
[2 4 ][][1 3 ] |
[2 4 ][][1 3 ] |
||
[3 4 ][][1 2 ]</pre> |
[3 4 ][][1 2 ]</pre> |
||
=={{header|EchoLisp}}== |
|||
<lang scheme> |
|||
(lib 'list) ;; (combinations L k) |
|||
;; add a combination to each partition in ps |
|||
(define (pproduct c ps) (for/list ((x ps)) (cons c x))) |
|||
;; apply to any type of set S |
|||
;; ns is list of cardinals for each partition |
|||
;; for all combinations Ci of n objects from S |
|||
;; set S <- LS minus Ci , set n <- next n , and recurse |
|||
(define (_partitions S ns ) |
|||
(cond |
|||
([empty? (rest ns)] (list (combinations S (first ns)))) |
|||
(else |
|||
(for/fold (parts null) |
|||
([c (combinations S (first ns))]) |
|||
(append |
|||
parts |
|||
(pproduct c (_partitions (set-substract S c) (rest ns)))))))) |
|||
;; task : S = ( 0 , 1 ... n-1) args = ns |
|||
(define (partitions . args) |
|||
(for-each |
|||
writeln |
|||
(_partitions (range 1 (1+ (apply + args))) args ))) |
|||
</lang> |
|||
{{out}} |
|||
<pre> |
|||
(partitions 1 1 1) |
|||
({ 1 } { 2 } { 3 }) |
|||
({ 1 } { 3 } { 2 }) |
|||
({ 2 } { 1 } { 3 }) |
|||
({ 2 } { 3 } { 1 }) |
|||
({ 3 } { 1 } { 2 }) |
|||
({ 3 } { 2 } { 1 }) |
|||
(partitions 2 0 2) |
|||
({ 1 2 } () { 3 4 }) |
|||
({ 1 3 } () { 2 4 }) |
|||
({ 1 4 } () { 2 3 }) |
|||
({ 2 3 } () { 1 4 }) |
|||
({ 2 4 } () { 1 3 }) |
|||
({ 3 4 } () { 1 2 }) |
|||
(for-each writeln (_partitions (make-set '(b a d c )) '(1 2 1))) |
|||
({ a } { b c } { d }) |
|||
({ a } { b d } { c }) |
|||
({ a } { c d } { b }) |
|||
({ b } { a c } { d }) |
|||
({ b } { a d } { c }) |
|||
({ b } { c d } { a }) |
|||
({ c } { a b } { d }) |
|||
({ c } { a d } { b }) |
|||
({ c } { b d } { a }) |
|||
({ d } { a b } { c }) |
|||
({ d } { a c } { b }) |
|||
({ d } { b c } { a }) |
|||
</pre> |
|||
=={{header|Elixir}}== |
=={{header|Elixir}}== |