Tell me more ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

The answer to this question is much too long

Your challenge is to write a partitioning function in the smallest number of characters.

Input example

['a', 'b', 'c']

Output example

[(('a'),('b'),('c')),
 (('a', 'b'), ('c')),
 (('a', 'c'), ('b')),
 (('b', 'c'), ('a')),
 (('a', 'b', 'c'))]

The input can be a list/array/set/string etc. whatever is easiest for your function to process

You can also choose the output format to suit yourself as long as the structure is clear.

Your function should work for at least 6 items in the input

share|improve this question

3 Answers

up vote 3 down vote accepted

GolfScript (43 chars)

{[[]]:E\{:v;{:^E+1/{^1$-\[~[v]+]+}/}%}/}:P;

or

{[[]]:E\{:v;{:^E+1/{^1$-\{[v]+}%+}/}%}/}:P;

Same input format, output format, and function name as Howard's solution. There's no brute forcing: this takes the simple iterative approach of adding one element from the input list to the partition each time round the outer loop.

share|improve this answer

GolfScript, 51 characters

{[[]]\{[.;]`{1$[1$]+@@`1$`{[2$]-@@[+]+}++/}+%}/}:P;

The script defines a variable P which takes an array from top of the stack and pushes back a list of all partitions, e.g.

[1 2] P            # => [[[1] [2]] [[1 2]]]
["a" "b" "c"] P    # => [[["a"] ["b"] ["c"]] [["b"] ["a" "c"]] [["a"] ["b" "c"]] [["a" "b"] ["c"]] [["a" "b" "c"]]]

It does also work on larger lists:

6, P ,p            # prints 203, i.e. Bell number B6
8, P ,p            # 4140

You may perform own tests online.

share|improve this answer

J, 51 characters

([:<a:-.~])"1~.((>:@i.#:i.@!)#l)<@;/."1[l=:;:1!:1[1

Takes input from the keyboard, items separated by spaces:

   ([:<a:-.~])"1~.((>:@i.#:i.@!)#l)<@;/."1[l=:;:1!:1[1
a b c
+-----+------+------+------+-------+
|+---+|+--+-+|+--+-+|+-+--+|+-+-+-+|
||abc|||ab|c|||ac|b|||a|bc|||a|b|c||
|+---+|+--+-+|+--+-+|+-+--+|+-+-+-+|
+-----+------+------+------+-------+
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.