27
\$\begingroup\$

The natural numbers including 0 are formally defined as sets, in the following way:

  • Number 0 is defined as the empty set, {}
  • For n ≥ 0, number n+1 is defined as n ∪ {n}.

As a consequence, n = {0, 1, ..., n-1}.

The first numbers, defined by this procedure, are:

  • 0 = {}
  • 1 = {{}}
  • 2 = {{}, {{}}}
  • 3 = {{}, {{}}, {{}, {{}}}}

Challenge

Given n, output its representation as a set.

Rules

The output can consistently use any bracket character such as {}, [], () or <>. Arbitrary characters (such as 01) are not allowed.

Instead of a comma as above, the separator can be any punctuation sign; or it may be inexistent.

Spaces (not newlines) may be included arbitrarily and inconsistently.

For example, number 2 with square brackets and semicolon as separator is [[]; [[]]], or equivalently [ [ ]; [ [ ] ] ], or even [ [ ] ;[ []]]

The order in which elements of a set are specified doesn't matter. So you can use any order in the representation. For example, these are some valid outputs for 3:

{{},{{}},{{},{{}}}}
{{{}},{{},{{}}},{}}
{{{}},{{{}},{}},{}}

You can write a program or function. Output may be a string or, if using a function, you may return a nested list or array whose string representation conforms to the above.

Test cases

0  ->  {}
1  ->  {{}}
2  ->  {{},{{}}}
3  ->  {{},{{}},{{},{{}}}}
4  ->  {{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}}
5  ->  {{},{{}},{{},{{}}},{{},{{}},{{},{{}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}}}
6  ->  {{},{{}},{{},{{}}},{{},{{}},{{},{{}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}}}}
7  ->  {{},{{}},{{},{{}}},{{},{{}},{{},{{}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}}}}}
\$\endgroup\$

22 Answers 22

8
\$\begingroup\$

Jelly, 3 bytes

Ḷ߀

This is a monadic link. Try it online!

How it works

Each natural number is the set of all previous natural numbers, i.e., n = {0, …, n-1}. Since there are no natural numbers preceding 0, we have that 0 = {}.

Ḷ߀  Monadic link. Argument: n (natural number)

Ḷ    Unlength; yield [0, ..., n-1].
 ߀  Recursively map this link over the range.
\$\endgroup\$
  • 3
    \$\begingroup\$ "Unlength" I like Jelly's inverse functions. \$\endgroup\$ – ETHproductions Sep 30 '16 at 22:07
  • 1
    \$\begingroup\$ If I am understanding correctly, unlength is basically range [0,n)? \$\endgroup\$ – Downgoat Sep 30 '16 at 22:31
  • 5
    \$\begingroup\$ @Downgoat That's correct. I try to keep letters and letters with dot below as lateral inverses. Since ḶL is a no-op, the mnemonic is unlength. There's also unbinary, undecimal, unhalve, unsine, unarccosine, etc. \$\endgroup\$ – Dennis Sep 30 '16 at 23:08
  • 1
    \$\begingroup\$ Wait, unarccosine? Wouldn't that just be cosine? \$\endgroup\$ – ETHproductions Oct 4 '16 at 0:42
  • \$\begingroup\$ @ETHproductions Yup. There's no C with dot below though. \$\endgroup\$ – Dennis Oct 4 '16 at 1:20
18
\$\begingroup\$

Python 2, 26 bytes

f=lambda n:map(f,range(n))

Test it on Ideone.

\$\endgroup\$
10
\$\begingroup\$

JavaScript (ES6), 32 bytes

f=n=>[...Array(n).keys()].map(f)

Simple enough.

\$\endgroup\$
  • 1
    \$\begingroup\$ @Downgoat I think this may be the first time I've used .map() without an arrow function inside :-) \$\endgroup\$ – ETHproductions Sep 30 '16 at 22:29
  • \$\begingroup\$ well technically f is an arrow function :P \$\endgroup\$ – Downgoat Sep 30 '16 at 23:57
  • \$\begingroup\$ @ETHproductions Really? .map(Number) is quite a common case. \$\endgroup\$ – Sebastian Simon Oct 1 '16 at 0:36
  • \$\begingroup\$ @Xufox Good point, I think I've done that at least once. \$\endgroup\$ – ETHproductions Oct 1 '16 at 1:07
  • 4
    \$\begingroup\$ @Xufox Though .map(e=>+e) is shorter, by a byte. \$\endgroup\$ – Conor O'Brien Oct 1 '16 at 3:50
7
\$\begingroup\$

Perl 6, 16 bytes

{({@_}…*)[$_]}

Returns nested data structure.

Example:

say {({@_}…*)[$_]}( 4 );
# [[] [[]] [[] [[]]] [[] [[]] [[] [[]]]]]

Explanation:

{   # lambda with implicit parameter 「$_」

  (


    # produce a lazy infinite sequence of all results

    {       # lambda with implicit parameter 「@_」
      @_    # array containing all previously seen values in the sequence
    }

    …       # keep repeating that block until:

    *       # Whatever ( never stop )


  )[ $_ ]   # use the outer block's argument to index into the sequence

}
\$\endgroup\$
  • \$\begingroup\$ This is... impressive. \$\endgroup\$ – Conor O'Brien Oct 1 '16 at 3:51
6
\$\begingroup\$

Ruby, 27 21 bytes

I'm new to ruby golfing, but here goes nothing. Thanks to Jordan for saving 6 bytes!

f=->s{(0...s).map &f}

This is a recursive function f (a proc, to be specific) and takes an argument s. It maps the proc f over 0...s, which is the range [0, s).

\$\endgroup\$
  • \$\begingroup\$ You can replace map{|e|f[e]} with map &f. \$\endgroup\$ – Jordan Sep 30 '16 at 23:34
  • \$\begingroup\$ @Jordan Wow, nice! \$\endgroup\$ – Conor O'Brien Sep 30 '16 at 23:35
5
\$\begingroup\$

Haskell, 32 27 bytes

p n='{':(p=<<[0..n-1])++"}"

Try it on Ideone.

\$\endgroup\$
4
\$\begingroup\$

CJam, 14 bytes

"[]"{_)@\]}ri*

Try it online!

Explanation

"[]"            e# Push this string. It is the representation of 0, and also serves
                e# to initialize
    {     }ri*  e# Repeat this block as many times as the input number
     _          e# Duplicate
      )         e# Uncons: split into array without the last element, and last element
       @\       e# Rotate, swap
         ]      e# Pack stack contents into an array
                e# Implicitly display

In each iteration, the block builds the representation of a number from that of the preceding one. To illustrate, let's consider the second iteration, where the representation of number 2 is built from that of 1, which is the string "[[]]".

  1. The stack contains "[[]]"
  2. After statement _ (duplicate) it contains "[[]]", "[[]]"
  3. After statement ) (uncons) it contains "[[]]", "[[]", "]"
  4. After statement @ (rotate) it contains "[[]", "]", "[[]]"
  5. After statement \ (swap) it contains "[[]", "[[]]", "]"
  6. After statement ] (pack into array) it contains ["[[]" "[[]]" "]"], which would be displayed as the string "[[][[]]]".
\$\endgroup\$
4
\$\begingroup\$

Cheddar, 17 bytes

n f->(|>n).map(f)

Short recursion + Short range + Short iteration = A challenge where cheddar does very well

Non-competing, 11 bytes

n f->|>n=>f

The => operator was added after this challenge was released making this answer non-competing.

This may look confusing but let me simplify it:

n f -> |> n => f

basically n is the input and f is the function itself. |>n generates [0, n) and => maps that over f.

\$\endgroup\$
  • 1
    \$\begingroup\$ The non-competing one looks very nice :D \$\endgroup\$ – Conor O'Brien Oct 2 '16 at 17:51
4
\$\begingroup\$

05AB1E, 8 7 bytes

)IF)©`®

Explanation

)         # wrap stack in a list, as stack is empty this becomes the empty list []
 IF       # input number of times do:
   )      # wrap stack in list
    ©     # store a copy of the list in the register
     `    # flatten the list
      ®   # push the copy from the register
          # implicitly print top value of stack after the last loop iteration

Try it online!

Saved 1 byte thanks to Adnan.

\$\endgroup\$
  • \$\begingroup\$ Less than 2 minutes LOL \$\endgroup\$ – Luis Mendo Sep 30 '16 at 21:46
  • \$\begingroup\$ @LuisMendo I literally just logged on when the challenge was posted :) \$\endgroup\$ – Emigna Sep 30 '16 at 21:47
  • \$\begingroup\$ I believe you can remove the last bracket :p \$\endgroup\$ – Adnan Oct 2 '16 at 16:36
  • \$\begingroup\$ @Adnan: Oops. I don't know how I missed that :) \$\endgroup\$ – Emigna Oct 2 '16 at 18:05
3
\$\begingroup\$

Pyth, 4 bytes

LyMb

Test suite

L: Define the function y with input b

yMb: y mapped over the range 0, 1, ..., b-1

On the input 0, this map returns []. Otherwise, it returns y mapped over all numbers up to b.

\$\endgroup\$
3
\$\begingroup\$

MATL, 13 bytes

Xhi:"tY:Xh]&D

Try it online!

Explanation

Xh              % Concatenate the stack contents into cell array. Since the stack
                % is empty, this produces the empty cell array, {}
  i:"     ]     % Take input number. Repeat that many times
     t          % Duplicate the cell array that is at the top of the stack
      Y:        % Unbox it, i.e., push its contents onto the stack
        Xh      % Concatenate the stack contents into a cell array
           &D   % String representation. Implicitly display
\$\endgroup\$
  • 2
    \$\begingroup\$ Very clever answer \$\endgroup\$ – Suever Sep 30 '16 at 22:33
  • \$\begingroup\$ @Suever Thanks! Way too long though... \$\endgroup\$ – Luis Mendo Sep 30 '16 at 22:35
3
\$\begingroup\$

Perl, 27 bytes

Includes +1 for -p

Many different methods all seem to end up as either 27 or 28 bytes. e.g.

#!/usr/bin/perl -p
$\=$_="{@F}"for@F[0..$_]}{

The best I could find is

#!/usr/bin/perl -p
s/./{$_/ for($\="{}")x$_}{

since on older perls you can drop the space before the for and get 26 bytes

\$\endgroup\$
3
\$\begingroup\$

Mathematica, 14 bytes

Array[#0,#,0]&
\$\endgroup\$
2
\$\begingroup\$

Mathematica, 31 bytes

Straightforwardly implements the definition as a nested list. Uses an unnamed function that recursively calls itself using #0.

If[#<1,{},Join[t=#0[#-1],{t}]]&
\$\endgroup\$
  • 4
    \$\begingroup\$ You can save a lot by using a named operator as well as Union instead of Join: ±0={};±n_:={t=±(n-1)}⋃t ... However, in this case it's even shorter to go for an iterative solution: Nest[{#}⋃#&,{},#]& \$\endgroup\$ – Martin Ender Oct 2 '16 at 16:53
2
\$\begingroup\$

Retina, 24 18 bytes

.+
$*1<>
+`1<
<<$'

Try it online! (The first line enables a linefeed-separated test suite.)

Explanation

.+
$*1<>

This converts the input to unary and appends <>, the representation of 0.

+`1<
<<$'

Here, the + indicates that this substitution should be run in a loop until the string stops changing. It's easier to explain this by going through the individual steps I took golfing it down. Let's with this version of the substitution:

1<(.*)>
<<$1>$1>

This matches the last 1 of the unary representation of the remaining input (to remove it and decrement the input), as well as the contents of the current set at the end. This is then replaced with a new set containing the previous one as well as its contents. However, we can notice that $1 is followed by > in both cases and hence we can include it in the capture itself and omit it from the substitution pattern. That leads to the form

1<(.*)
<<$1$1

However, now we can observe that (.*) just captures the suffix of the string after 1< and we even reinsert this suffix at the end with $1. Since the substitution syntax gives us a way to refer to the part of a string after a match with $' we can simply omit both of those parts and end up with the version used in the answer:

1<
<<$'
\$\endgroup\$
  • \$\begingroup\$ You sure this is Retina and not the ><> language? :-P \$\endgroup\$ – Luis Mendo Oct 2 '16 at 17:18
  • \$\begingroup\$ @LuisMendo I guess I could have used {}, but <> is the only pair that never needs escaping, so I thought I'd go with that. ;) \$\endgroup\$ – Martin Ender Oct 2 '16 at 17:22
2
\$\begingroup\$

Underload, 14 bytes

((:a*)~^()~^a)

Try it online!

Underload full programs can't take input via any of our defined methods, so this is a function that takes input from the stack as a Church numeral (the normal way to define integers in Underload), and produces output to the stack as a string.

The (…) grouping markers are required to make this a function (reusable) rather than a snippet (only usable once). The wrapper in the TIO link calls the function in question destructively using ^, but it could be reused via making a copy of it and only consuming one of the copies when calling it. It also provides input to the program (here, (:*:*), i.e. 4), and prints the output using S.

Explanation

Underload's surprisingly suited for this task as Turing tarpits go, having such useful primitives as "copy" and "surround with parentheses". (Somehow, Underload, normally a very verbose language, is beating Mathematica, normally a language which wins due to having a huge set of builtins, via having more appropriate builtins!) Here's how the program works:

((:a*)~^()~^a)
(            )   Make a snippet into a function
 (   )~^         Exponentiate the following function by the top of stack:
  :                Copy the top stack element
   a               Surround the copy in parentheses
    *              Append the copy to the original, popping the copy
          ~^     Run the resulting function, with the following argument on its stack:
        ()         Empty string
            a    Surround the result in parentheses

Function exponentiation effectively causes the steps of the function to repeat that many times, so, e.g., (:a*)³ would be (:a*:a*:a*). That's the idiomatic way to write a loop that repeats a given number of times in Underload. (You can note that the ~^ is described two different ways above; that's because integers in Underload are defined as function exponentiation specialised to that integer, so in order to do a function exponentiation, you simply try to execute an integer as though it were a function.)

\$\endgroup\$
2
\$\begingroup\$

Pari/GP, 23 bytes

f(n)=[f(i)|i<-[0..n-1]]

Try it online!

\$\endgroup\$
2
\$\begingroup\$

APL(NARS), 15 chars, 30 bytes

{⍵=0:⍬⋄∇¨¯1+⍳⍵}

test:

  f←{⍵=0:⍬⋄∇¨¯1+⍳⍵}
  o←⎕fmt
  o f 0
┌0─┐
│ 0│
└~─┘
  o f 1
┌1───┐
│┌0─┐│
││ 0││
│└~─┘2
└∊───┘
  o f 2
┌2──────────┐
│┌0─┐ ┌1───┐│
││ 0│ │┌0─┐││
│└~─┘ ││ 0│││
│     │└~─┘2│
│     └∊───┘3
└∊──────────┘
  o f 3
┌3────────────────────────┐
│┌0─┐ ┌1───┐ ┌2──────────┐│
││ 0│ │┌0─┐│ │┌0─┐ ┌1───┐││
│└~─┘ ││ 0││ ││ 0│ │┌0─┐│││
│     │└~─┘2 │└~─┘ ││ 0││││
│     └∊───┘ │     │└~─┘2││
│            │     └∊───┘3│
│            └∊──────────┘4
└∊────────────────────────┘
  o f 4
┌4────────────────────────────────────────────────────┐
│┌0─┐ ┌1───┐ ┌2──────────┐ ┌3────────────────────────┐│
││ 0│ │┌0─┐│ │┌0─┐ ┌1───┐│ │┌0─┐ ┌1───┐ ┌2──────────┐││
│└~─┘ ││ 0││ ││ 0│ │┌0─┐││ ││ 0│ │┌0─┐│ │┌0─┐ ┌1───┐│││
│     │└~─┘2 │└~─┘ ││ 0│││ │└~─┘ ││ 0││ ││ 0│ │┌0─┐││││
│     └∊───┘ │     │└~─┘2│ │     │└~─┘2 │└~─┘ ││ 0│││││
│            │     └∊───┘3 │     └∊───┘ │     │└~─┘2│││
│            └∊──────────┘ │            │     └∊───┘3││
│                          │            └∊──────────┘4│
│                          └∊────────────────────────┘5
└∊────────────────────────────────────────────────────┘

I don't know if this would be accepted... Zilde is ⍬ here it represent the void set {} if I want print the Zilde element or one element full of Zilde, and Zilde enclosed all what happen is print nothing... so for see Zilde one has to define one function I call it o (o←⎕fmt) I do not insert in the count because the element and its structure exist even if the sys not print it...It is possible if io is 0

{⍵=0:⍬⋄∇¨⍳⍵}

could be 12 characters solution too...

\$\endgroup\$
1
\$\begingroup\$

Brachylog, 14 bytes

yk:{,[]:?:gi}a

Try it online!

Explanation

yk                The range [0, ..., Input - 1]
  :{        }a    Apply on each element of the range
    ,[]:?:gi      Group the empty list [] in a list Input times
\$\endgroup\$
1
\$\begingroup\$

GAP, 22 bytes

f:=n->Set([0..n-1],f);

For example:

gap> f(3);                            
[ [  ], [ [  ] ], [ [  ], [ [  ] ] ] ]
\$\endgroup\$
1
\$\begingroup\$

Racket 119 bytes

(λ(n)(define ll(list'()))(for((i(range 1 n)))(set! ll(cons ll(for/list((j(length ll)))(list-ref ll j)))))(reverse ll))

Ungolfed:

(define f
  (λ (n)
    (define ll (list '()))
    (for ((i (range 1 n)))
      (set! ll
            (cons ll
                  (for/list ((j (length ll)))
                    (list-ref ll j)
                    ))))
    (reverse ll)))

Testing (In Racket {} is same as () and default output is ()):

(f 4)

'(() (()) ((()) ()) (((()) ()) (()) ()))

To clearly see each number (0 to 3):

(for((i (f 4)))  (println (reverse i)))

'()
'(())
'(() (()))
'(() (()) ((()) ()))
\$\endgroup\$
1
\$\begingroup\$

Batch, 74 bytes

@set s={}
@for /l %%i in (1,1,%1)do @call set s={%%s%%%%s:~1%%
@echo %s%

Uses the fact that each answer is equal to the previous answer inserted into itself after the leading {. The first few outputs are as follows:

{}

{{}}

{{{}}{}}

{{{{}}{}}{{}}{}}

{{{{{}}{}}{{}}{}}{{{}}{}}{{}}{}}

{{{{{{}}{}}{{}}{}}{{{}}{}}{{}}{}}{{{{}}{}}{{}}{}}{{{}}{}}{{}}{}}
\$\endgroup\$
  • \$\begingroup\$ Can you post an example showing input and output formats? \$\endgroup\$ – Luis Mendo Mar 7 '17 at 10:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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