Shortest power set implementation

22

3

Problem definition

Print out the powerset of a given set. For example:

[1, 2, 3] => [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]

Each element is to be printed on a separate line, so the above example would be printed as:

[]
[1]
[2]
...
[1, 2, 3]

Example code (in D, python example here):

import std.stdio;

string[][] powerset(string[] set) {
    if (set.length == 1) {
        return [set, []];
    }

    string[][] ret;
    foreach (item; powerset(set[1 .. $])) {
        ret ~= set[0]~item;
        ret ~= item;
    }

    return ret;
}

void main(string[] argv) {
    foreach (set; powerset(argv[1 .. $]))
        writeln(set);
}

Input

Elements will be passed as arguments. For example, the example provided above would be passed to a program called powerset as:

powerset 1 2 3

Arguments will be alphanumeric.

Rules

  1. No libraries besides io
  2. Output does not have to be ordered
  3. Powerset does not have to be stored, only printed
  4. Elements in the set must be delimited (e.g. 1,2,3, [1,2,3] and ['1','2','3'] are acceptable, but 123 is not
    • Trailing delimiters are fine (e.g. 1,2,3, == 1,2,3)
  5. Best is determined based on number of bytes

The best solution will be decided no less than 10 days after the first submission.

beatgammit

Posted 2012-11-21T08:48:27.880

Reputation: 321

Related: http://codegolf.stackexchange.com/q/51468/21348

– edc65 – 2015-06-12T13:34:52.893

Closely related to http://codegolf.stackexchange.com/questions/6380

– Peter Taylor – 2012-11-21T22:55:35.590

2If only this challenge was updated to allow the defaults, like returning and functions. Python would be 54 bytes: lambda L:reduce(lambda r,x:r+[s+[x]for s in r],L,[[]]). – mbomb007 – 2016-12-21T02:10:13.420

I'm not agree in only print... Why not allow to have the data, the variable too.. Than why print in column and not in row? – RosLuP – 2017-11-15T19:54:19.793

Answers

15

Mathematica 16

Code

Subsets is native to Mathematica.

Column@Subsets@s

The code (without column) can be verified on WolframAlpha. (I had to use brackets instead of @; they mean the same thing.

Usage

s={1,2,3}
Column@Subsets@s

output


This method (55 chars) uses the approach suggested by @w0lf.

s #&/@Tuples[{0,1},Length@s]/.{0:>Sequence[]}//Column

Breakdown

Generate the tuples, composed of 0 and 1's of length Length[s]

Tuples[{0, 1}, Length@s]

{{0, 0, 0}, {0, 0, 1}, {0, 1, 0}, {0, 1, 1}, {1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}}

Multiply the original list (vector) by each tuple:

s # & /@ Tuples[{0, 1}, Length@s]

{{0, 0, 0}, {0, 0, 3}, {0, 2, 0}, {0, 2, 3}, {1, 0, 0}, {1, 0, 3}, {1, 2, 0}, {1, 2, 3}}

Delete the 0's. % is shorthand for "the preceding output".

%/. {0 :> Sequence[]}

{{}, {3}, {2}, {2, 3}, {1}, {1, 3}, {1, 2}, {1, 2, 3}}

Display in column:

Mathematica graphics

DavidC

Posted 2012-11-21T08:48:27.880

Reputation: 24 524

@tjameson I had serious doubts about whether I should post it, but I thought some people might find it interesting to know it is built-in. – DavidC – 2012-11-21T23:05:55.670

I find it interesting :) – Dr. belisarius – 2012-11-23T11:48:56.350

Can you leave off the s and put the input at the end of the line? – Solomon Ucko – 2019-01-05T14:21:02.260

15 bytes: Subsets/*Column makes an anonymous function that takes a list and returns the display in columns. – Roman – 2019-08-28T19:24:53.433

9

C, 118 115

Whilst can save approx 20 chars with simpler formatting, still not going to win in code golf terms either way.

x,i,f;
main(int a,char**s){
    for(;x<1<<a;x+=2,puts("[]"+f))
        for(i=f=0;++i<a;)x&1<<i?f=!!printf("%c%s","[,"[f],s[i]):0;
}

Testing:

/a.out 1 2 3
[]
[1]
[2]
[1,2]
[3]
[1,3]
[2,3]
[1,2,3]

baby-rabbit

Posted 2012-11-21T08:48:27.880

Reputation: 1 623

Nice. Some tips: K&R style (main(a,s)char**s;{...}), f|=x&1<<i&&printf is shorter than ?:. – ugoren – 2012-11-22T07:25:53.677

Just figured out what's behind x+=2 (and where did s[0] go). Really nice trick. – ugoren – 2012-11-22T07:29:42.247

Refusing to golf your answer because it's "still not going to win in code golf terms either way." makes the answer not a serious contender for the winning criteria of the challenge. – pppery – 2019-08-25T01:22:24.867

7

GolfScript, 22 18 characters

~[[]]{{+}+1$%+}@/`

Another attempt in GolfScript with a completely different algorithm. Input format is the same as with w0lf's answer. (online test)

Howard

Posted 2012-11-21T08:48:27.880

Reputation: 23 109

+1 Great solution! Mine is refactored for readability :-P – Cristian Lupascu – 2012-11-21T20:23:30.727

5

GolfScript (43 chars)

This may seem quite long, but it's the first solution to follow the spec: input is from command-line arguments, and output is newline-delimited.

"#{ARGV.join('
')}"n/[[]]\1/{`{1$+.p}+%}%p;

E.g.

$ golfscript.rb powset.gs 1 2 3
["1"]
["2"]
["2" "1"]
["3"]
["3" "2"]
["3" "1"]
["3" "2" "1"]
[]

Peter Taylor

Posted 2012-11-21T08:48:27.880

Reputation: 41 901

Quotes aren't necessary, if that makes a difference. – beatgammit – 2012-11-21T22:58:15.853

@tjameson, the quotes come from using the shortest possible way to print. The fact that those values are strings rather than integers comes from the inability of GolfScript to access command-line arguments directly: it has to rely on the interpreter doing an eval in Ruby and putting the result in a string. – Peter Taylor – 2012-11-21T23:04:27.440

4

awk (82)

{for(;i<2^NF;i++){for(j=0;j<NF;j++)if(and(i,(2^j)))printf "%s ",$(j+1);print ""}}

assume saved in file powerset.awk, usage

$ echo 1 2 3 | awk -f powerset.awk

1
2
1 2
3
1 3
2 3
1 2 3

ps if your awk doesn't have and() function, replace it with int(i/(2^j))%2 but adds two to the count.

karakfa

Posted 2012-11-21T08:48:27.880

Reputation: 161

(2^j) -> 2^j saves you 2 bytes; the .awk file also works without a trailing \n, so you could shave off another byte. – mklement0 – 2017-02-07T03:16:31.837

3

J, 19 chars

   (<@#~#:@i.@(2&^)@#)

   (<@#~#:@i.@(2&^)@#) 1 2 3
┌┬─┬─┬───┬─┬───┬───┬─────┐
││3│2│2 3│1│1 3│1 2│1 2 3│
└┴─┴─┴───┴─┴───┴───┴─────┘

The ascii boxing in the output is called boxing and provides heterogen collection (for different length of arrays here).

randomra

Posted 2012-11-21T08:48:27.880

Reputation: 19 909

3

JavaScript, 98

Sadly, a good chunk is spent on output formatting.

for(n in a=eval(prompt(i=p=[[]])))
    for(j=i+1;j;)
        p[++i]=p[--j].concat(a[n]);
alert('[]'+p.join('\n'))

Input

Takes a JavaScript array. (e.g. [1,2,3])

Output

[]
1
1,2
2
2,3
1,2,3
1,3
3

Paul Walls

Posted 2012-11-21T08:48:27.880

Reputation: 361

3

Python 70 67 bytes

def p(a,*v):
 i=0;print v
 for n in a:i+=1;p(a[i:],n,*v)
p(input())

Input is taken in the same manner as for ugoren's solution. Sample I/O:

$ echo [1,2,3] | powerset.py
()
(1,)
(2, 1)
(3, 2, 1)
(3, 1)
(2,)
(3, 2)
(3,)

primo

Posted 2012-11-21T08:48:27.880

Reputation: 30 891

1You can save some with def p(a,*v) and then p(a[i:],n,*v). Output becomes somewhat uglier, but still OK. – ugoren – 2012-11-26T14:52:39.443

Very clever, thanks for the tip. – primo – 2012-11-26T15:07:42.270

3

Python (74 70 chars)

def p(a,v):
 if a:i,*a=a;p(a,v);p(a,v+[i])
 else:print v
p(input(),[])

for input as 1,2,3 or [1,2,3], output is:

[]
[3]
[2]
[2, 3]
[1]
[1, 3]
[1, 2]
[1, 2, 3]

AMK

Posted 2012-11-21T08:48:27.880

Reputation: 506

[a[0]] = a[:1] – ugoren – 2012-11-25T17:51:06.503

with input 1,2,3 a[:1] not works. tuple+list not allowed. Exist better solution – AMK – 2012-11-26T13:21:31.877

+1 for i,*a=a – primo – 2012-11-26T14:43:41.273

Isn't i,*a=a Python 3? It doesn't work on my 2.7.1. – ugoren – 2012-11-26T15:02:24.347

Nor on 2.7.2. That might explain why I've never seen that trick before... most code golf servers run 2.7.x. – primo – 2012-11-26T15:24:25.793

2

brainfuck, 94 bytes

+[[<+>>+<-]++[>-<------]>-[>]<<[>>+>]>,]++++++++++[[[<]<]+[-[>[.>]]<[<]>+[>]>]<<
.[<<[<]>-]++>]

Formatted:

+
[
  [<+> >+<-]
  ++[>-<------]>-[>]
  <<[>>+>]
  >,
]
++++++++++
[
  [[<]<]
  +
  print
  [
    -[>[.>]]
    <[<]
    >+[>]
    >
  ]
  <<.
  increment
  [
    <<[<]
    >-
  ]
  ++>
]

Expects input of the form 9,10,11 without a trailing newline, and outputs subsets in the same format, sometimes with a trailing comma. The first line printed will always be empty, signifying the empty set.

Try it online.

The basic idea is to place a bit next to each element, then repeatedly increment the binary number while printing the corresponding subset before each increment. (A bit indicates whether an element is in the subset.) A sentinel bit to the left of the array is used to terminate the program. This version actually creates an exponential number of sentinels to save some bytes; a more efficient 99-byte solution that only uses one sentinel can be found in the revision history.

Each bit is encoded as one plus its value; i.e., it can be either 1 or 2. The tape is laid out with the bit before each element and a single zero cell between adjacent elements. The comma is included on the tape for non-final elements, so we can conveniently just print elements without doing any extra work to handle delimiters.

Mitch Schwartz

Posted 2012-11-21T08:48:27.880

Reputation: 4 899

2

Jelly, 6 bytes

ŒPŒṘ€Y

Try it online!

ŒṘ€Y are string formatting.

Erik the Outgolfer

Posted 2012-11-21T08:48:27.880

Reputation: 38 134

2

Mathematica 53

Column@Fold[#~Join~Table[x~Join~{#2},{x,#}]&,{{}},#]&

enter image description here

chyanog

Posted 2012-11-21T08:48:27.880

Reputation: 1 078

2

APL (Dyalog Classic), 13 bytes

⍪,⊃∘.,/⎕,¨⊂⊂⍬

Try it online!

Output:

 1 2 3 
 1 2   
 1 3   
 1     
 2 3   
 2     
 3     

There's a blank line at the end to represent the empty set.

Explanation:

evaluated input

⎕,¨⊂⊂⍬ append an empty numeric list after each element

∘., Cartesian product

/ reduction (foldr)

disclose (necessary after reduction in APL)

At this point the result is an n-dimensional 2-by-...-by-2 array, where n is the length of the input.

, flatten into a vector

turn the vector into an upright 2n-by-1 matrix, so each subset is on a separate line

ngn

Posted 2012-11-21T08:48:27.880

Reputation: 11 449

2

C# 164

Man this is hard in C#!

void P<T>(T[]c){foreach(var d in c.Aggregate<T,IEnumerable<IEnumerable<T>>>(new[]{new T[0]},(a,b)=>a.Concat(a.Select(x=>x.Concat(new[]{b})))))Console.WriteLine(d);}

Ben Reich

Posted 2012-11-21T08:48:27.880

Reputation: 1 577

2

Scala, 81

def p[A](x:Seq[A]){x.foldLeft(Seq(Seq[A]()))((a,b)=>a++a.map(b+:_)).map(println)}

Dan G

Posted 2012-11-21T08:48:27.880

Reputation: 191

2

APL (26)

Reads input from keyboard because there's no argv equivalent.

↑⍕¨(/∘T)¨↓⍉(M/2)⊤⍳2*M←⍴T←⎕

Usage:

      ↑⍕¨(/∘T)¨↓⍉(M/2)⊤⍳2*M←⍴T←⎕
⎕:
      1 2 3
3    
2    
2 3  
1    
1 3  
1 2  
1 2 3

Explanation:

  • T←⎕: read input, store in T
  • M←⍴T: store length of T in M
  • (M/2)⊤⍳2*M: generate the bit patterns for 1 upto 2^M using M bits.
  • ↓⍉: split the matrix so that each bit pattern is separate
  • (/∘T)¨: for each bit pattern, select those sub-items from T.
  • ↑⍕¨: for output, get the string representation of each element (so that it will fill using blanks and not zeroes), and format as a matrix (so that each element is on its own line).

marinus

Posted 2012-11-21T08:48:27.880

Reputation: 30 224

2

Haskell, 80 78 bytes

import System.Environment
main=getArgs>>=mapM(print.concat).mapM(\a->[[a],[]])

Try it online!

Angs

Posted 2012-11-21T08:48:27.880

Reputation: 4 825

The I/O requirements are horrible, however people are interpreting them quite loosely. If you change to taking input via stdin you could save 15 bytes, see this.

– ბიმო – 2018-04-23T12:59:11.357

2

JavaScript (ES6) 76

Partially copied from this one: https://codegolf.stackexchange.com/a/51502/21348

Using a bitmap, so it's limited to no more than 32 elements.

Run the snippet in Firefox to test.

f=l=>{ 
  for(i=0;i<1<<l.length;i++)
    console.log(l.filter(v=>[i&m,m+=m][0],m=1))
}  

// TEST

// Redefine console to have output inside the page
console = { log: (...p) => O.innerHTML += p.join(' ') + '\n' }

test=()=>{
  var set = I.value.match(/[^ ,]+/g)
  O.innerHTML='';
  f(set);
}

test()
#I,#O { border: 1px solid #aaa; width: 400px; padding:2px}
Insert values, space or comma separated:<br>
<input id=I value='1 2 3'> <button onclick="test()">-></button>
<pre id=O></pre>

edc65

Posted 2012-11-21T08:48:27.880

Reputation: 31 086

2

Python 2, 64 bytes

Using comma-separated input:

P=[[]]
for i in input():P+=[s+[i]for s in P]
for s in P:print s

Pyth, 4 bytes (using builtin) or 14 bytes (without)

As noted by @Jakube in the comments, Pyth is too recent for this question. Still here's a solution using Pyth's builtin powerset operator:

jbyQ

And here's one without it:

jbu+Gm+d]HGQ]Y

You can try both solutions here and here. Here's an explanation of the second solution:

jb       # "\n".join(
 u       #  reduce(
  +G     #   lambda G,H: G+
   m     #    map(
    +d]H #     lambda d: d+[H],
    G    #     G),
  Q      #   input()
  ]Y     #   [[]]))

Uri Granta

Posted 2012-11-21T08:48:27.880

Reputation: 2 675

2

Golfscript 48

~:x,:§2\?,{[2base.,§\-[0]*\+x\]zip{~{}{;}if}%p}%

This program uses the binary representations of numbers from 0 to length(input) to generate powerset items.

Input

The input format is the Golfscript array format (example: [1 2 3])

Output

The output is a collection of arrays separated by newlines, representing the power set. Example:

[]
[3]
[2]
[2 3]
[1]
[1 3]
[1 2]
[1 2 3]

Online Test

The program can be tested online here.

Cristian Lupascu

Posted 2012-11-21T08:48:27.880

Reputation: 8 369

Awesome, but could you delimit with newlines? – beatgammit – 2012-11-21T09:43:00.073

@tjameson I managed to output delimited by newlines while keeping the same character count. Please see the update to my answer. – Cristian Lupascu – 2012-11-21T09:51:56.977

2

Haskell (96)

import Control.Monad
import System.Environment
main=getArgs>>=mapM print.filterM(\_->[False ..])

If importing Control.Monad isn't allowed, this becomes 100 characters:

import System.Environment
main=getArgs>>=mapM print.p
p z=case z of{[]->[[]];x:y->p y++map(x:)(p y)}

Lambda Fairy

Posted 2012-11-21T08:48:27.880

Reputation: 311

1

Ruby, 39

$*.map{p *$*.combination($.)
$.+=1}
p$*

Lowjacker

Posted 2012-11-21T08:48:27.880

Reputation: 4 466

1

Haskell 89 chars

import System.Environment
main=getArgs>>=mapM print.p
p[]=[[]]
p(x:y)=(map(x:)$p y)++p y

Getting parameters is long :/

kyticka

Posted 2012-11-21T08:48:27.880

Reputation: 111

one more char can be shaved off with map(x:)(p y)++p y and yet two more chars above that with [(x:),id]<*>p y. Apparently <*> is in the Prelude now. (filterM isn't).

– Will Ness – 2016-09-17T22:33:48.443

1

JavaScript (ES6), 68 bytes

a=>alert(a.reduce((a,x)=>[...a,...a.map(y=>[...y,x])],[[]]).join`
`)

Demo

let f =

a=>alert(a.reduce((a,x)=>[...a,...a.map(y=>[...y,x])],[[]]).join`
`)

f([1,2,3])

Arnauld

Posted 2012-11-21T08:48:27.880

Reputation: 111 334

Why the alert? – Shaggy – 2018-02-02T14:16:39.493

@Shaggy The challenge explicitly asks to print each element on a separate line -- which would probably frowned upon with our current standards. Most answers seem to stick to this rule. – Arnauld – 2018-02-02T14:21:37.757

Ah, fair enough; I interpreted "print" as "output". – Shaggy – 2018-02-02T14:22:29.993

1

R, 63

y=lapply(seq(v),function(x)cat(paste(combn(v,x,s=F)),sep="\n"))

Here, v represents a vector.

Usage:

v <- c(1, 2, 3)
y=lapply(seq(v),function(x)cat(paste(combn(v,x,s=F)),sep="\n"))
1
2
3
c(1, 2)
c(1, 3)
c(2, 3)
c(1, 2, 3)

Sven Hohenstein

Posted 2012-11-21T08:48:27.880

Reputation: 2 464

1

Brachylog, 4 bytes

⊇ᵘẉᵐ

Try it online!

  ẉ     Write on its own line
 ᵘ ᵐ    every unique
⊇       subset of the input.

Unrelated String

Posted 2012-11-21T08:48:27.880

Reputation: 5 300

1

Mathematica, 51

More cheating:

Column@ReplaceList[Plus@@HoldForm/@#,x___+___->{x}]&

Use with @{1,2,3}.

LogicBreaker

Posted 2012-11-21T08:48:27.880

Reputation: 11

Your code should take the set as input, not just hardcode it. Also, since this is code golf, you should include the byte count of the code (and probably remove the unnecessary spaces). – Martin Ender – 2015-06-12T12:43:32.853

Since this contest is long over, the post was more for the idea, but I've edited it. – LogicBreaker – 2015-06-12T15:13:13.767

1

K, 14 bytes

{x@&:'!(#x)#2}

Generate all 0/1 vectors as long as the input, gather the indices of 1s and use those to select elements from the input vector. In practice:

  {x@&:'!(#x)#2} 1 2 3
(!0
 ,3
 ,2
 2 3
 ,1
 1 3
 1 2
 1 2 3)

This is a bit liberal with the output requirements, but I think it's legal. The most questionable part is that the empty set will be represented in a type dependent form; !0 is how K denotes an empty numeric vector:

  0#1 2 3      / integers
!0
  0#`a `b `c   / symbols
0#`
  0#"foobar"   / characters
""

Explanation

The (#x)#2 builds a vector of 2 as long as the input:

  {(#x)#2}1 2 3
2 2 2
  {(#x)#2}`k `d `b `"+"
2 2 2 2

When monadic ! is applied to a vector, it is "odometer":

  !2 2 2
(0 0 0
 0 0 1
 0 1 0
 0 1 1
 1 0 0
 1 0 1
 1 1 0
 1 1 1)

Then we use "where" (&) on each (') vector to gather its indices. The colon is necessary to disambiguate between the monadic and dyadic form of &:

  &0 0 1 0 1 1
2 4 5

  {&:'!(#x)#2} 1 2 3
(!0
 ,2
 ,1
 1 2
 ,0
 0 2
 0 1
 0 1 2)

If we just wanted combination vectors, we'd be done, but we need to use these as indices into the original set. Fortunately, K's indexing operator @ can accept a complex structure of indices and will produce a result with the same shape:

  {x@&:'!(#x)#2} `a `c `e
(0#`
 ,`e
 ,`c
 `c `e
 ,`a
 `a `e
 `a `c
 `a `c `e)

Elegant, no?

JohnE

Posted 2012-11-21T08:48:27.880

Reputation: 4 632

1This is no longer valid, as "odometer" in oK now generates a flipped matrix. It can be corrected at the cost of a single byte: {x@&:'+!(#x)#2}. Unrelated: a shorter equivalent of (#x)#2 is 2|~x. – ngn – 2018-02-02T18:10:34.880

1

Python, 93 87 chars

Python makes formatting simple, because the required input/output matches its native format.
Only supports items which are Python literals (e.g. 1,2,'hello', not 1,2,hello).
Reads standard input, not parameters.

f=lambda x:x and f(x[1:])+[x[:1]+a for a in f(x[1:])]or[()]
for l in f(input()):print l

ugoren

Posted 2012-11-21T08:48:27.880

Reputation: 16 527

print f(input()) shorter – AMK – 2012-11-24T14:02:21.123

@AMK, the requirement is for each element to be printed in one line. But list can indeed be removed (if also replacinf [[]] with [()]. – ugoren – 2012-11-24T18:04:54.667

print'\n'.join(f(input())) saves two characters – beary605 – 2012-11-24T22:45:26.337

@beary605, doesn't work, f() contains tuples, not strings. – ugoren – 2012-11-25T05:24:37.330

0

Python 2, 74 bytes

def f(x):
    for i in reduce(lambda s,e:s+[i+[e] for i in s],x,[[]]):print i

chyanog

Posted 2012-11-21T08:48:27.880

Reputation: 1 078

0

Japt -R, 5 bytes

Sadly, Japt's built-in for getting the powerset of an array doesn't include the empty array or this would be 1 byte.

à pNÅ

Try it

Shaggy

Posted 2012-11-21T08:48:27.880

Reputation: 24 623

0

Perl 6, 22 bytes

say words.combinations

The built in combinations method will give all N-combinations of a list, ie. the powerset. Arguments provided via STDIN

% echo 1 2 3 | ./powerset.p6
(() (1) (2) (3) (1 2) (1 3) (2 3) (1 2 3))

Joshua

Posted 2012-11-21T08:48:27.880

Reputation: 261

0

Japt -R, 5 bytes

à i[]

Try it online!

Oliver

Posted 2012-11-21T08:48:27.880

Reputation: 7 160

Beat you to it! :p Also, note the (unnecessary) requirement of each element being on its own line. – Shaggy – 2019-01-04T16:17:40.320

0

Common Lisp, 117 bytes

(labels((p(l &aux(x(car l)))(if x`(,@#1=(p(cdr l)),@(mapcar(lambda(m)(cons x m))#1#))'(()))))(mapcar'print(p(read))))

Input is a list of element, in output the sets are printed as lists (empty list is equal to NIL)

Try it online!

If the answer can be a function that returns the result, then:

Common Lisp, 90 bytes

(defun p(l &aux(x(car l)))(if x`(,@#1=(p(cdr l)),@(mapcar(lambda(m)(cons x m))#1#))'(())))

Try it online!

Renzo

Posted 2012-11-21T08:48:27.880

Reputation: 2 260

0

Coconut, 90 bytes

def p(l)=(fmap((+)$(l[:1]),p(l[1:])))+p(l[1:])if l else[[]]
fmap(print,p(input().split()))

I think I had something one byte shorter but I lost it after experimenting more.

Try it online!

Solomon Ucko

Posted 2012-11-21T08:48:27.880

Reputation: 439

0

PHP, 78 bytes

for(;$i<1<<$argc;$i+=2)for(print$c=_;$argc>$c+=1;)$i&1<<$c&&print"$argv[$c],";

prints a comma after each element and an underscore before each subset. Run with -nr or try it online.

Titus

Posted 2012-11-21T08:48:27.880

Reputation: 13 814

0

05AB1E, 2 bytes

æ»

Try it online.

Output is space-delimited (i.e. 1 2 3). If you want it as actual lists (i.e. [1, 2, 3]), add €¸ before the »:

怸»

Try it online.

Explanation:

æ     # Take the powerset of the (implicit) input-list
   »  # Join the lists by newlines (and each inner list by spaces)
      # (and output the result implicitly)

 €¸   # Wrap each inner list into a list
      # (i.e. [[1],[1,2]] → [[[1]],[[1,2]]])

Kevin Cruijssen

Posted 2012-11-21T08:48:27.880

Reputation: 67 575

0

Zsh, 66 bytes

for ((;2**$#>i++;)){j=;for s
((i&1<<j++))&&echo ${(P)j}' \c'
echo}

Pretty standard nested for loop comparison, similar the C and js answers. Try it online!


Zsh, 71 bytes

for s;a=($^@'
'$^a)
for s ($a);b+=(${(j: :)${(uof)s}})
<<<${(F)${(u)b}}

Progressively builds up the cartesian product S^N, then eliminates repeated coordinates in a single element: (0 0 1 0 -> 0 1), then eliminates repeated elements: (0 1, 0 1 -> 0 1).

Here's an expanded version, with some examples:

for s in $@; do                    # 'for s in {a,b,c}' ensures we iterate 3 times
    cprod=( ${^@}$'\n'${^cprod} )  # ex: {a,b,c}{aa,ab,ac,ba,bb,bc,ca,cb,cc}
done                               # (actually, $'a\na\na' $'a\na\nb' ...)
for xyz in $cprod; do              # ex: xyz=$'a\nb\na'
    unique_elems=${(uof)xyz}       # $'a\nb\na' -(f)-> a b a -(o)-> a a b -(u)> a b
    sets+=( ${(j: :)unique_elems}  # a b -(j: :)> 'a b'
done
unique_sets=(${(u)sets})           # a 'a b' 'a b' b -(u)> a 'a b' b
<<< ${(F)unique_sets}              # a 'a b' b -(F)> $'a\na b\nb'

Try it online!

GammaFunction

Posted 2012-11-21T08:48:27.880

Reputation: 2 838

0

Python 2, 58 bytes

S=lambda A:A and[u+[A[0]]for u in S(A[1:])]+S(A[1:])or[[]]

Try it online!

Chas Brown

Posted 2012-11-21T08:48:27.880

Reputation: 8 959

0

Pyth, 1 byte

y

Since Pyth has implicit Q (input variable) at the end of programs, this is basically just power set of the input. I don't think this violates any rules (although 'No libraries besides io' is a bit vague)

Try it online!

EdgyNerd

Posted 2012-11-21T08:48:27.880

Reputation: 1 106

0

Matlab (46)

v=input(''),for i=1:numel(v),nchoosek(v,i),end

  • the input must be of the form [% % % ..] where % is a number

Abr001am

Posted 2012-11-21T08:48:27.880

Reputation: 862

0

Ruby Array method combination (from 1.9 ) [50 chars]

0.upto(ARGV.size){|a|ARGV.combination(a){|v| p v}}

beginnerProg

Posted 2012-11-21T08:48:27.880

Reputation: 51