13
\$\begingroup\$

Challenge:

Given the input number n. It should give me nested sublists of n layers with the power of two numbers for each level. Each power of two value will be in separate sublists.

Notes:

  • n will always be greater than 0

  • I am using the example output with Python Lists. You can use any type of sequence in your own language.

  • Your output must be one-indexed, add one to n if your output is zero-indexed.

  • Your output sequence must be nested.

Test cases:

n = 1: [1]
n = 2: [1, [2]]
n = 3: [1, [2, [4]]]
n = 4: [1, [2, [4, [8]]]]
n = 5: [1, [2, [4, [8, [16]]]]]
n = 6: [1, [2, [4, [8, [16, [32]]]]]]
n = 7: [1, [2, [4, [8, [16, [32, [64]]]]]]]

This is , so the shortest code in bytes wins!

The power of twos are these values 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048..., each values is double of the previous value.

\$\endgroup\$
15
  • \$\begingroup\$ There are a number of issues with this challenge. It seems to be multiple challenges at once: Geometric sequence and the sublist formatting. See codegolf.meta.stackexchange.com/a/20905/91213 \$\endgroup\$
    – mousetail
    Commented Dec 21, 2022 at 6:47
  • \$\begingroup\$ @tsh It has to be [1, [2, [4, [8]]]] \$\endgroup\$ Commented Dec 21, 2022 at 6:50
  • 1
    \$\begingroup\$ Consider posting in the sandbox to get feedback on your challenges before posting them. \$\endgroup\$
    – mousetail
    Commented Dec 21, 2022 at 6:50
  • 1
    \$\begingroup\$ @tsh I changed it to "power of 2" \$\endgroup\$ Commented Dec 21, 2022 at 7:35
  • 2
    \$\begingroup\$ Can we output zero-indexed? (3 => [1, [2, [4, [8]]]]) \$\endgroup\$
    – hyper-neutrino
    Commented Dec 21, 2022 at 7:44

35 Answers 35

7
\$\begingroup\$

Factor + math.polynomials, 47 bytes

[ 2 powers reverse 1 cut [ swap 2array ] each ]

Try it online!

        ! 4
2       ! 4 2
powers  ! { 1 2 4 8 }
reverse ! { 8 4 2 1 }
1       ! { 8 4 2 1 } 1
cut     ! { 8 } { 4 2 1 }
        ! { 8 } 4              <<first iteration of each>>
swap    ! 4 { 8 }
2array  ! { 4 { 8 } }
        ! { 4 { 8 } } 2        <<second iteration>>
swap    ! 2 { 4 { 8 } }
2array  ! { 2 { 4 { 8 } } }
        ! { 2 { 4 { 8 } } } 1  <<third>>
swap    ! 1 { 2 { 4 { 8 } } }
2array  ! { 1 { 2 { 4 { 8 } } } }
\$\endgroup\$
5
\$\begingroup\$

><>, 47 bytes

1i:?v~~l?^;
/$-1/
/on$o"[,":
\2*$:}10./"]"o~60.

Try it!

enter image description here

Generates trailing commas at the end of lists, some languages allow that so that should be OK. Takes input as a char code.

Uses the length of the stack to keep track of how many ] to generate at the end.

\$\endgroup\$
3
  • \$\begingroup\$ It works! Upvoted! This language is cool :) Did you create it? \$\endgroup\$ Commented Dec 21, 2022 at 7:28
  • 1
    \$\begingroup\$ Yea Fish is amazingly fun to program in \$\endgroup\$
    – mousetail
    Commented Dec 21, 2022 at 7:28
  • 2
    \$\begingroup\$ No, I created the online interpreter myself but the language was made by Harypon \$\endgroup\$
    – mousetail
    Commented Dec 21, 2022 at 7:29
5
\$\begingroup\$

Python 3, 44 bytes

e=lambda n,i=1:[i,e(n-1, i*2)]if n>0 else[i]

Try it online!

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Nice answer, +1. You can save two bytes! Try it online! \$\endgroup\$ Commented Dec 21, 2022 at 11:40
  • 1
    \$\begingroup\$ 40 bytes: Try it online! \$\endgroup\$
    – The Thonnu
    Commented Dec 21, 2022 at 11:52
  • 2
    \$\begingroup\$ Since 0 is logically false in Python and other numbers are logically true, you don't need the comparison operator: 39 bytes \$\endgroup\$
    – DLosc
    Commented Dec 21, 2022 at 17:47
5
\$\begingroup\$

Vyxal, 9 6 bytes

(d1$"ꜝ

Try it Online!

Uses the fact that stack languages can have their input placed on the stack before execution

Proof the meta proposal was +6 at the time of posting

Explained

A port of Jelly

(d1$"ꜝ
(      # repeat input times
 d     # double
  1$"  # [1, that]
     ꜝ #  keep only truthy items
\$\endgroup\$
1
  • \$\begingroup\$ Exactly what I want! Upvoted. \$\endgroup\$ Commented Dec 21, 2022 at 7:01
4
\$\begingroup\$

R, 44 bytes

f=\(n,k=1,`+`=list)`if`(n-1,k+f(n-1,k*2),+k)

Attempt This Online!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ A shame this doesn't work. \$\endgroup\$
    – Giuseppe
    Commented Dec 21, 2022 at 19:10
  • \$\begingroup\$ @Giuseppe yep. I also hoped for relist, but simple recursion seems to be the shortest... \$\endgroup\$
    – pajonk
    Commented Dec 21, 2022 at 19:40
4
\$\begingroup\$

Jelly, 7 bytes

Ḥ1,¹ƇƲ¡

Try it online!

-2 bytes thanks to caird coinheringaahing (use STDIN to avoid needing the leading 0, and a shorter way of filtering the 0)

Ḥ1,¹ƇƲ¡    Main Link (input in STDIN, so argument starts at 0)
      ¡    repeat N times
Ḥ          double the current list
 1,        pair with 1
   ¹Ƈ      filter by identity; remove falsy elements (filter out the 0 in the first step)
\$\endgroup\$
3
  • \$\begingroup\$ Nice answer! Equal to lyxal's 9 bytes. \$\endgroup\$ Commented Dec 21, 2022 at 7:51
  • \$\begingroup\$ 7 bytes \$\endgroup\$ Commented Dec 21, 2022 at 15:20
  • \$\begingroup\$ @cairdcoinheringaahing can't believe I didn't think of that - thanks \$\endgroup\$
    – hyper-neutrino
    Commented Dec 21, 2022 at 22:24
4
\$\begingroup\$

Ruby, 36 34 bytes

->n{*r=k=2**n;n.times{r=k/=2,r};r}

Try it online!

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

05AB1E, 7 bytes

F·Xs‚ZK

Try it online!

Port of lyxal's Vyxal answer.

  • -1 thanks to Kevin Cruijssen

Explanations:

F·Xs‚ZK   # Implicit input (n)
F         # for i in range(a):
 ·        #  Double
  Xs‚     #  Get [1, that] (X defaults to 1)
     ZK   #  Push the list without the maximum

Previous 8 byte answer:

L<o`¸¹G‚   # Implicit input (n)
L<         # range(0, n)
  o        # 2 to the power of each
   `¸      # Dump onto stack, putting the last one in a list
     ¹G    # n-1 times:
       ‚   #  Pair

Previous 13 byte answer:

<Do¸sE¹<N-o‚R   # Implicit input (n)
<               # Reduce n by 1
 Do¸            # Duplicate and push [2**(n-1)] to the stack
    sE          # Swap and loop through range(0, n-1):
      ¹<N-      #  Subtract from n-1
          o     #  Raise 2 to the power of this number
           ‚R   #  Pair and reverse
\$\endgroup\$
4
  • 1
    \$\begingroup\$ Haha, wow! Impressive. \$\endgroup\$ Commented Dec 21, 2022 at 12:31
  • \$\begingroup\$ 7 bytes (still a port of Lyxal's Vyxal answer). \$\endgroup\$ Commented Dec 28, 2022 at 8:01
  • \$\begingroup\$ @KevinCruijssen thanks \$\endgroup\$
    – The Thonnu
    Commented Dec 28, 2022 at 8:27
  • 2
    \$\begingroup\$ The rare double port, porting and then being outgolfed by porting :p \$\endgroup\$
    – lyxal
    Commented Dec 29, 2022 at 1:01
3
\$\begingroup\$

JavaScript (Node.js), 31 bytes

f=(x,i=1)=>--x?[i,f(x,i*2)]:[i]

Try it online!

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

MATL, 12 bytes

:qWP"@XhP]&D

Try it at MATL online!

:       % Implicit input, n. Range [1 2 ... n]
q       % Subtract 1, element-wise
W       % Powers of 2, element-wise
P       % Flip. Gives [2^(n-1) 2^(n-2) ··· 1]
"       % For each number in that vector
@       % Push current number
  Xh    %   Concatenate all stack contents into a cell array
  P     %   Flip
]       % End
&D      % String representation. Implicit display
\$\endgroup\$
3
\$\begingroup\$

Pyth, 20 bytes

L+[^2b)?qtQbY[yhb)y0

Try it online!

L                      # Function y with input as b
 +                     # Append
  [^2b)                # List with 2^b as only element
       ?               # Ternary operator
        qtQb           # If b is equal to input - 1
            Y          #  empty list (when condition is true)
             [yhb)     # Call function y with input b+1 and put inside a list (when condition is false)
                  y0   # Call function y with input 0
\$\endgroup\$
2
  • \$\begingroup\$ -4 bytes Two bytes since you can use ]... instead of [...) for single element lists, another saved by counting down instead of up allowing the implicit Q at the end, and another saved by getting rid of the first ] (+ on a non list and a list will automatically append) \$\endgroup\$ Commented Dec 22, 2022 at 20:12
  • \$\begingroup\$ Yet more trickery can bring it down to 15 bytes \$\endgroup\$ Commented Dec 22, 2022 at 21:11
3
\$\begingroup\$

Pip, 28 bytes

FiR,a{YlAEyPE EiUi=a?Y Hy0}y

Try It Online!

FiR,a{YlAEyPE EiUi=a?Y Hy0}y
FiR,a{                    }    Loop through [a, 0]
      YlAEyPE Ei               Set y (initially "") to y + 2**i wrapped in a list
                Ui=a?Y Hy0     Remove the empty string if it is the first iteration

```
\$\endgroup\$
4
  • \$\begingroup\$ You have a stray nil in the innermost list that probably shouldn't be there... \$\endgroup\$
    – DLosc
    Commented Dec 21, 2022 at 17:28
  • \$\begingroup\$ @DLosc shouldn't nil print nothing? \$\endgroup\$
    – math scat
    Commented Dec 22, 2022 at 10:10
  • \$\begingroup\$ The str of nil is nothing, but the repr of nil is (). Since it's in a list and you're using the -p flag, you get the repr. \$\endgroup\$
    – DLosc
    Commented Dec 22, 2022 at 16:21
  • \$\begingroup\$ Hint: since the empty string is falsey and all the other values involved are truthy, you can remove the empty string using FI. \$\endgroup\$
    – DLosc
    Commented Dec 22, 2022 at 16:23
3
\$\begingroup\$

Knight (v2), 35 bytes

;=l,=c/^2=pP2;W=p-EpT=l+,=c/c 2,lDl

Try it online!

Looks golfable.

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

K (ngn/k), 17 bytes

{(x-1)(1,,2*)/,1}

Try it online!

Explanation:
{(x-1)(1,,2*)/,1}
              ,1  start with list one
 (x-1)       /    do n-1 times
      (1,,2*)     1 joined with double the current value enlisted
\$\endgroup\$
3
\$\begingroup\$

Python 3, 68 bytes

def f(n):
	for i in range(n):l=i and[l[0]//2,l]or[2**n//2]
	return l

Try it online!

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

Charcoal, 14 bytes

FN≔Φ⟦¹⊗υ⟧κυ⭆¹υ

Try it online! Link is to verbose version of code. Explanation:

FN

Repeat n times...

≔Φ⟦¹⊗υ⟧κυ

... double the predefined empty list and prepend a 1 (but on the first pass filter out the list as it is empty).

⭆¹υ

Pretty-print the final list.

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

Python 3, 48 42 40 bytes

f=lambda n,c=1:n>1and[c,f(n-1,c+c)]or[c]

Try it online!

-6 bytes thanks to l4m2

-2 bytes thanks to The Thonnu

\$\endgroup\$
9
  • \$\begingroup\$ Store 2**c rather than c saves some \$\endgroup\$
    – l4m2
    Commented Dec 21, 2022 at 8:19
  • 1
    \$\begingroup\$ Try it online! \$\endgroup\$
    – l4m2
    Commented Dec 21, 2022 at 8:33
  • 1
    \$\begingroup\$ "x if y else z" can (sometime) by simplify into "y and x or z" (if x is always truthy for example) \$\endgroup\$
    – tsh
    Commented Dec 21, 2022 at 9:47
  • 1
    \$\begingroup\$ 40 bytes: Try it online! \$\endgroup\$
    – The Thonnu
    Commented Dec 21, 2022 at 10:12
  • 1
    \$\begingroup\$ @TheThonnu What a great idea! \$\endgroup\$ Commented Dec 21, 2022 at 10:14
2
\$\begingroup\$

Retina, 36 bytes

"$&"{`\d+
$.(*2*
.+
[1, $&]
, \d+]
]

Try it online! Link includes test cases (because fortunately I was able to use $& instead of $+). Explanation:

"$&"{`

Repeat the program n times (because n is the input).

\d+
$.(*2*

Double all of the integers.

.+
[1, $&]

Wrap the list with 1 in a sublist.

, \d+]
]

Remove the original input.

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

sclin, 19 bytes

[1]"2*1rev ,";1- *#

Try it here! Takes the argument from the next line. If outputting as an infinite sequence were allowed, then something like 1,,"2*1rev ,"itr would be 16 bytes.

For testing purposes:

; n>o
1,,"2*1rev ,";1- *#
7

Explanation

Prettified code:

[1] ( 2* 1rev , ) ;1- *#
  • [1] starting with 1-length array of 1
  • (...) ;1- *# repeat (next line) - 1 times...
    • 2* 1rev , vectorized-multiply by 2 and prepend 1
\$\endgroup\$
2
\$\begingroup\$

Raku, 23 bytes

[1],{[1,2 «*«$_]}...*

Try it online!

This is an expression for the infinite sequence of arrays. The magic is in the «*« operator, which multiplies each element of an arbitrarily-deeply nested structure by a number.

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

Pip -p, 12 bytes

LaYFI[1y*2]y

Try It Online!

Explanation

Same idea as hyper-neutrino's Jelly answer:

LaYFI[1y*2]y
              a is command-line argument; y is "" (implicit)
La            Loop a times:
       y*2      Multiply y by 2 (-> 0 if it's "", element-wise if it's a list)
     [1   ]     Put 1 and that value in a list
   FI           Filter, removing falsey values (in this case, 0)
  Y             Yank, assigning the result back to y
           y  After the loop, autoprint the final value of y
\$\endgroup\$
2
\$\begingroup\$

Pip -p, 18 14 bytes

FI[EiUi<a&REa]

Try It Online!

-4 bytes thanks to @DLosc

Recursively builds the nested lists. FI is used to filter out the 0 in the last list, otherwise [1;[2;[4;0]]] would be output.

\$\endgroup\$
2
  • \$\begingroup\$ Nice solution! Here's 14 bytes. \$\endgroup\$
    – DLosc
    Commented Dec 22, 2022 at 16:55
  • \$\begingroup\$ @DLosc that's really interesting that you don't need a seperator in the list, might come in handy in the future \$\endgroup\$
    – jezza_99
    Commented Dec 22, 2022 at 18:29
2
\$\begingroup\$

MathGolf, 6 bytes

Æ∞1\αç

Port of @lyxal's Vyxal answer.

Try it online.

Explanation:

Æ       # Loop the (implicit) input amount of times,
        # using the following five characters as inner code-block:
 ∞      #  Double all current values (the stack contains a 0 by default)
  1\α   #  Pair it with a leading 1
     ç  #  Falsey filter to remove the 0
        # (after the loop, the entire stack is output implicitly as result)
\$\endgroup\$
1
\$\begingroup\$

Julia 1.0, 21 bytes

!n=[n<2||[1,2*!~-n];]

Try it online!

using instead of ! would save a character, since a√b is parsed as a*√b (which doesn't work for !). But of course the byte count would be higher.

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

FunStack alpha, 40 bytes

Pair 1 Double over iterate Wrap 1 At Dec

Try it at Replit: pass the input number as a command-line argument and enter the program on stdin.

Explanation

First, we generate the infinite sequence of such nested lists:

Pair 1

Given x, turn it into [1, x].

Double

Multiply by 2 (applies itemwise over lists).

over

Given two arity-1 functions, this modifier works the same as compose but is 3 bytes shorter. The composed function is "Multiply the argument by 2 and pair 1 with the result."

iterate

Repeatedly apply this function and return the infinite list of results...

Wrap 1

... starting at [1].

The resulting infinite list is a value at the left side of the program, so it gets pushed onto the argument list. Then:

At

Get the nth element, where n is...

Dec

... the first program argument, decremented (since indexing is 0-based).

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

CJam, 14 bytes

{,W%{2\#]W%}%}

Anonymous code block that pops a number from the stack and pushes the nested array.

The header reads the input. The footer executes the block and prints the string representation of the array.

Port of my MATL answer.

Try it online!

Code explanation

{,W%{2\#]W%}%}

{            }   e# define code block
 ,               e#   range (0-based)
  W%             e#   reverse array
    {      }%    e#   map this code block over the array
     2\#         e#     exponential with case 2 
        ]        e#     pack all stack contents into an array
         W%      e#     reverse array
\$\endgroup\$
1
\$\begingroup\$

Mathematica 39 bytes

With n=5

s=Nothing;Do[s={2^--i,s},{i,n,1,-1}];s

{1, {2, {4, {8, {16}}}}}

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

awk solution - different solutions for mawk-1/2 and gawk/nawk :

jot 16 | 
mawk 'function __(_){return $_=--_?_+=_=__(_):!_}__(NF=$_)' OFS=,
nawk
gawk 'func __(_){return $++_=--_?__(_)/_*(_+_):!_}__(NF=$-_)' OFS=,

 * "function" is normally preferred, but this is Pebble Beach…
1
1,2
1,2,4
1,2,4,8
1,2,4,8,16
1,2,4,8,16,32
1,2,4,8,16,32,64
1,2,4,8,16,32,64,128
1,2,4,8,16,32,64,128,256
1,2,4,8,16,32,64,128,256,512
1,2,4,8,16,32,64,128,256,512,1024
1,2,4,8,16,32,64,128,256,512,1024,2048
1,2,4,8,16,32,64,128,256,512,1024,2048,4096
1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192
1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384
1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768
1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536

Different solutions needed stemming from their different order of precedence of something not clearly specified in POSIX -

  • mawks go strictly left-to-right, even for assignments,

    — so $_ = ... is equivalent to $(func-input-val) = ...,

  • while gawk/nawk handles all of RHS first, with LHS taking on final value of _

To make nesting sublists out of that :

 for __ in $(jot 7); do 
  
    echo " $__ :: $( echo "$__"  | 
      
       mawk 'function __(_){ORS="]"ORS;return $_=\
             --_?_+=_=__(_):!_}$!__(NF=$(OFS=",["))="["$_' 

    )"
 done

 1 :: [1]
 2 :: [1,[2]]
 3 :: [1,[2,[4]]]
 4 :: [1,[2,[4,[8]]]]
 5 :: [1,[2,[4,[8,[16]]]]]
 6 :: [1,[2,[4,[8,[16,[32]]]]]]
 7 :: [1,[2,[4,[8,[16,[32,[64]]]]]]]
\$\endgroup\$
1
\$\begingroup\$

Scala, 70 bytes

Try it online!

def e(n:Int,i:Int=1):List[Any]={if(n>0)List(i,e(n-1,i*2))else List(i)}
\$\endgroup\$
1
\$\begingroup\$

Lua, 59 bytes

load"a={1}b=a for i=2,...do b[2]={2^i/2}b=b[2]end return a"

Try it online!

Ungolfed version:

function f(n)
    a={1}b=a
    for i=2,n do
        b[2]={2^i/2}
        b=b[2]
    end
    return a
end
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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