16
\$\begingroup\$

Given the input of n and value. The code is supposed to nest the single element list with value repeated n times. The final output should be a multilevel nested list with single repeated values in all sublists.

This is , so the shortest code in bytes wins!

Test cases:

n = 1, value = 'a': ['a']
n = 2, value = 'a': ['a', ['a']]
n = 3, value = 'a': ['a', ['a', ['a']]]
n = 4, value = 'a': ['a', ['a', ['a', ['a']]]]
n = 5, value = 'a': ['a', ['a', ['a', ['a', ['a']]]]]
n = 6, value = 'a': ['a', ['a', ['a', ['a', ['a', ['a']]]]]]
\$\endgroup\$
7
  • \$\begingroup\$ Is n always greater than zero? If so, can we take n 0-indexed? \$\endgroup\$
    – att
    Dec 20, 2021 at 4:44
  • \$\begingroup\$ Do we need to include the commas in the output? And can the value be input as a string? \$\endgroup\$
    – theorist
    Dec 20, 2021 at 5:14
  • \$\begingroup\$ @theorist Just a sequence is enough, in any way \$\endgroup\$ Dec 20, 2021 at 5:17
  • \$\begingroup\$ @att Yes. Always bigger than 0 \$\endgroup\$ Dec 20, 2021 at 5:17
  • 1
    \$\begingroup\$ @ZaMoC Sure.... \$\endgroup\$ Dec 20, 2021 at 9:41

31 Answers 31

19
\$\begingroup\$

Python 2, 33 30 bytes

-3 bytes thanks to @xnor

lambda n,v:eval('[v,'*n+']'*n)

Try it online!

\$\endgroup\$
4
  • \$\begingroup\$ Wow! Good thought!! \$\endgroup\$ Dec 20, 2021 at 7:10
  • 1
    \$\begingroup\$ It looks like you can just do lambda n,v:eval('[v,'*n+']'*n) \$\endgroup\$
    – xnor
    Dec 20, 2021 at 7:28
  • \$\begingroup\$ @xnor Haha! I honestly have no idea how I didn't see that... \$\endgroup\$ Dec 20, 2021 at 7:30
  • \$\begingroup\$ Even cooler now! \$\endgroup\$ Dec 20, 2021 at 9:28
10
\$\begingroup\$

05AB1E, 3 bytes

F‚Ù

Try it online.

Explanation:

F     # Loop the first input amount of times:
 ‚    #  Pair the (implicit) second input-value with the current list
  Ù   #  And uniquify it (which only does something in the first iteration,
      #  transforming the pair of values to a single wrapped value)
      # (after the loop, the result is output implicitly)
\$\endgroup\$
1
  • \$\begingroup\$ 3 bytes! So far I think you're the winner. \$\endgroup\$ Dec 27, 2021 at 10:29
8
\$\begingroup\$

Vyxal r, 4 bytes

(⁰"U

Try it Online!

The joys of golfing language :)

Explained

(⁰"U
(     # n times:
 ⁰    #   push the value
  "U  #   pair and uniquify - a port of the 05ab1e answer
\$\endgroup\$
2
  • \$\begingroup\$ Wow... 4 bytes!! \$\endgroup\$ Dec 20, 2021 at 3:08
  • \$\begingroup\$ That's so short... how- \$\endgroup\$ Dec 20, 2021 at 3:08
8
\$\begingroup\$

Python, 34 bytes

f=lambda x,n:n and[x,f(x,n-1)][:n]

Attempt This Online!

Thanks to loopy walt for this one.


Old answers:

Python, 36 bytes

f=lambda x,n:[x][n>1:]or[x,f(x,n-1)]

Attempt This Online!

Python, 36 35 bytes

f=lambda x,n:n*[1]and[[x]+f(x,n-1)]

Attempt This Online!

Outputs as a singleton list, but that feels like cheating here.

Python, 39 bytes

f=lambda x,n:[x]+(~-n*[1]and[f(x,n-1)])

Attempt This Online!

Python, 37 bytes

f=lambda x,n:x+(~-n*[1]and[f(x,n-1)])

Attempt This Online!

Inputs as a singleton list.

\$\endgroup\$
6
  • \$\begingroup\$ Wow! Very clever! \$\endgroup\$ Dec 20, 2021 at 3:07
  • \$\begingroup\$ You can go zero-based and save two bytes in the topmost lambda (dropping >1). \$\endgroup\$
    – loopy walt
    Dec 20, 2021 at 6:11
  • 1
    \$\begingroup\$ Well, they don't say no, do they? How about this f=lambda x,n:[x,n<2or f(x,n-1)][:n], then (35 bytes)? ato.pxeger.com/… \$\endgroup\$
    – loopy walt
    Dec 20, 2021 at 10:21
  • 1
    \$\begingroup\$ 34 if you are ok with requiring n>0. ato.pxeger.com/… And I'm not dingledooper :-) \$\endgroup\$
    – loopy walt
    Dec 20, 2021 at 23:05
  • 1
    \$\begingroup\$ @loopywalt sorry, your avatars are too similar ;) \$\endgroup\$
    – pxeger
    Dec 20, 2021 at 23:12
7
\$\begingroup\$

Proton, 25 bytes

n=>v=>((a=>[v,a])*n)([v])

Try it online!

n=>v=>((a=>[v,a])*n)([v])    This language is stupid
n=>                          Given n
  v=>                        and v
       (a=>[v,a])            pair v with the current accumulator
                 *n          n times
      (            )([v])    and call that on [v]
\$\endgroup\$
3
  • \$\begingroup\$ Thanks, very cool. "this language" is stupid lol \$\endgroup\$ Dec 20, 2021 at 4:15
  • \$\begingroup\$ @U12-F̉͋̅̾̇orward yep - I made this language, so I know better than anyone just how stupid it is :P \$\endgroup\$
    – hyper-neutrino
    Dec 20, 2021 at 6:09
  • \$\begingroup\$ Wow! Really! Very interesting. Cool. \$\endgroup\$ Dec 20, 2021 at 7:12
6
\$\begingroup\$

Wolfram Mathematica, 30 21 bytes

Print[""@@#~Nest~##]&

-9 bytes from @att!

Try it online!

Sample I/O:

Print[""@@#~Nest~##]&@@{a,3}

[a[a[a]]]

Print[""@@#~Nest~##]&@@{17,3}

[17[17[17]]]

Print[""@@#~Nest~##]&@@{Pi,6}

\$[\pi [\pi [\pi [\pi [\pi [\pi ]]]]]]\$

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Is a separator not needed? 21 bytes if so, or 27 bytes if it is. \$\endgroup\$
    – att
    Dec 20, 2021 at 5:06
  • \$\begingroup\$ (with separator only works if value is a string) \$\endgroup\$
    – att
    Dec 20, 2021 at 5:10
6
\$\begingroup\$

R, 46 bytes

function(n,v)Reduce(list,rep(v,n-1),list(v),T)

Try it online!

Non-recursive approach. Pretty-printing and test harness taken from Dominic van Essen who insisted I post this as my own.

\$\endgroup\$
1
  • \$\begingroup\$ Nice; and based on the OP's reply to ZaMoC's comment/question, you can probably leave-out the ,T to save 2 bytes. \$\endgroup\$ Dec 20, 2021 at 19:53
6
\$\begingroup\$

BQN, 9 bytes

∾⟜⋈´⥊⟜⋈⟜⋈

Pins and bowties FTW

Anonymous tacit function that takes two arguments and returns a nested list. This is why the list formatting looks weird. Run it online!

Explanation

The left argument is the count; the right argument is the value. The example uses a left argument of 2 and a right argument of 0.

∾⟜⋈´⥊⟜⋈⟜⋈
          ⟜⋈  Wrap the right argument in a list: ⟨ 0 ⟩, and then
       ⟜⋈     Wrap that list in a list: ⟨ ⟨ 0 ⟩ ⟩, and then
     ⥊        Reshape to a length equaling the left argument: ⟨ ⟨ 0 ⟩ ⟨ 0 ⟩ ⟩
    ´          Right-fold that list on this function:
 ⟜⋈             Wrap the right argument in a list: ⟨ ⟨ 0 ⟩ ⟩, and then
∾                Concatenate with the left argument: ⟨ 0 ⟩ ∾ ⟨ ⟨ 0 ⟩ ⟩ → ⟨ 0 ⟨ 0 ⟩ ⟩
\$\endgroup\$
0
6
\$\begingroup\$

Husk, 13 bytes

+J',R¹e'[²R']

Try it online!

Not an ideal challenge for a language that doesn't support ragged lists...

+              # join together:
    R¹         #  arg1 repeats of
      e        #   2-element list of
       '[      #    '[' and
         ²     #    arg2,
 J',           #  joined by commas,
               #  and
     R']       #  arg1 repeats of ']'
\$\endgroup\$
5
\$\begingroup\$

Jelly, 5 bytes

W{Ɱṭ/

Try it online!

Value on left, \$n\$ on right

W        The value wrapped in a singleton list
 {Ɱ      for each 1..n.
   ṭ/    Reduce by Funky Reverse Append™.
\$\endgroup\$
3
  • \$\begingroup\$ Just curious, how do you type those characters? :) \$\endgroup\$ Dec 20, 2021 at 4:15
  • 1
    \$\begingroup\$ @U12-F̉͋̅̾̇orward abrudz.github.io/lb/jelly \$\endgroup\$ Dec 20, 2021 at 4:36
  • \$\begingroup\$ Wow!.... Interesting \$\endgroup\$ Dec 20, 2021 at 5:18
5
\$\begingroup\$

Ruby, 29 23 bytes

->n,a{eval'[a,'*n+?]*n}

Try it online!

Stole the eval trick from dingledooper

\$\endgroup\$
5
\$\begingroup\$

R, 49 bytes

f=function(n,v)`if`(n-1,list(v,f(n-1,v)),list(v))

Try it online!

\$\endgroup\$
3
  • 1
    \$\begingroup\$ 46 bytes \$\endgroup\$
    – Giuseppe
    Dec 20, 2021 at 15:41
  • 1
    \$\begingroup\$ @Giuseppe - that's a different answer. Post it. \$\endgroup\$ Dec 20, 2021 at 16:23
  • \$\begingroup\$ If you insist! \$\endgroup\$
    – Giuseppe
    Dec 20, 2021 at 19:05
5
\$\begingroup\$

Racket, 49 bytes

(define(f x n)(if(= n 1)`(,x)`(,x,(f x(- n 1)))))

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Welcome to Code Golf! Nice first answer. \$\endgroup\$ Dec 20, 2021 at 23:15
4
\$\begingroup\$

Wolfram Language (Mathematica), 24 bytes

t&@Do[t={#,t},Set@t;#2]&

Try it online!

Input [n, value].

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

Wolfram Language (Mathematica), 24 bytes

0-indexed

Fold[List,{#},Table@##]&

Try it online!

\$\endgroup\$
4
  • \$\begingroup\$ The order is reversed. \$\endgroup\$
    – att
    Dec 20, 2021 at 7:06
  • \$\begingroup\$ @att I guess we will wait for OP to decide... \$\endgroup\$
    – ZaMoC
    Dec 20, 2021 at 8:20
  • 1
    \$\begingroup\$ The challenge specification clearly shows which order it should be in, which was OP's decision when they made the challenge in the first place. \$\endgroup\$
    – hyper-neutrino
    Dec 20, 2021 at 9:18
  • \$\begingroup\$ @hyper-neutrino OP says my answer is valid. Please check the main comments \$\endgroup\$
    – ZaMoC
    Dec 20, 2021 at 9:43
4
\$\begingroup\$

MathGolf, 5 bytes

a*Åαç

Outputs reversed (e.g. [[["a"],"a"],"a"] instead of ["a",["a",["a"]]]), which is allowed based on the comments under the challenge.

Try it online.

Explanation:

a      # Wrap the (implicit) input-string into a list
       #  e.g. "abc" → ["abc"]
 *     # Repeat it the (implicit) input-integer amount of times
       #  e.g. 5 → ["abc","abc","abc","abc","abc"]
  Å    # For-each over these strings,
       # using the following 2 characters as inner code-block:
   α   #  Wrap the top two values into a list
       #  (which will wrap with the implicit loop-index 0 in the first iteration)
       #   e.g. [0,"abc"] in the first iteration
       #        [["abc"],"abc"] in the second iteration
       #        [[["abc"],"abc"],"abc"] in the third, etc.
    ç  #  Remove all 0s from the list with a falsey filter
       #  (only relevant for the first iteration: [0,"abc"] → ["abc"])
       # (after the loop, the entire stack is output implicitly as result)
\$\endgroup\$
4
\$\begingroup\$

HBL, 11 bytes

1,(?(-.)(1('?(-.),)?)?

Try it!

Explanation

A recursive function:

1,(?(-.)(1('?(-.),)?)?
1                       Cons
 ,                      the second argument with:
  (?(-.)                 If the first argument decremented is truthy (> 1):
        (1          )     Cons
          ('?     )        Recursive call with
             (-.)           First argument decremented
                 ,          Second argument unchanged
                   ?      with nil (empty list)
                         Else (the first argument is 1):
                     ?    Nil (empty list)

I.e., if the first argument is 1, we get (cons arg2 nil), which simply creates a singleton list containing the second argument; and if the first argument is greater than 1, we get (cons arg2 (cons [recursive-call] nil)), which wraps the result of the recursive call in a singleton list and then prepends the second argument to it.

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

APL+WIN, 28 bytes

Prompts for n followed by value

(¯1↓∊n⍴⊂'[',⎕,','),(n←⎕)⍴']'

Try it online! Thanks to Dyalog Classic

\$\endgroup\$
4
  • \$\begingroup\$ From the image it looks as if the outermost list (=box?) doesn't contain an 'a' alement... \$\endgroup\$ Dec 20, 2021 at 20:03
  • \$\begingroup\$ @DominicvanEssen Thanks for picking that up. I could not find an easy fix so went with a new approach \$\endgroup\$
    – Graham
    Dec 20, 2021 at 21:23
  • \$\begingroup\$ Hmm... don't you now have an unwanted comma in the innermost list...? \$\endgroup\$ Dec 20, 2021 at 21:52
  • \$\begingroup\$ @DominicvanEssen Thanks again. Fixed. Old age seems to be getting the better of me ;( \$\endgroup\$
    – Graham
    Dec 20, 2021 at 22:14
4
\$\begingroup\$

PHP, 56 55 bytes

function($n,$a){for($r=[$a];--$n;)$r=[$a,$r];return$r;}

Try it online!

Like often, PHP makes the worst score, akin only to C, but dirtier and with lots of $

EDIT: -1 byte, these dollars allow us some trickery with the parser after all

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

PHP 50 bytes

function f($c,$n){return --$n?[$c,f($c,$n)]:[$c];}

Try it online!

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

PowerShell Core, 41 bytes

$n,$a=$args
1..$n|%{$r=$a,@($r)|?{$_}}
$r

Try it online!

Please note that this does not work for n = 1, for some reason PowerShell treats it as a string. Even when forcing to return an array.

Let me know if not OK and I'll withdraw this answer!

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Thanks for the answer, it's ok! doesn't matter much \$\endgroup\$ Dec 20, 2021 at 4:17
  • 1
    \$\begingroup\$ Or you could add an extra code for an if else for whether n is 1. Then just return the value in a singular list \$\endgroup\$ Dec 20, 2021 at 4:18
  • \$\begingroup\$ I tried but PowerShell doesn't want it: With an explicit .Net list for example \$\endgroup\$
    – Julian
    Dec 20, 2021 at 19:52
3
\$\begingroup\$

Pari/GP, 29 bytes

f(a,n)=if(n--,[a,f(a,n)],[a])

Try it online!

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

Charcoal, 15 bytes

FN≔⟦⁺⟦η⟧υ⟧υ⭆¹⊟υ

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

FN

Repeat n times...

≔⟦⁺⟦η⟧υ⟧υ

... prepend value to the initially predefined empty list, then wrap that in another list.

⭆¹⊟υ

Unwrap the very last wrapper list and pretty-print it.

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

Pip -p, 14 13 bytes

-1 byte by porting Neil's Charcoal answer

Lal:[lPEb]l@0

Try it online!

Explanation

Lal:[lPEb]l@0
               l is empty list; a,b are command-line args
La             Loop a times:
        b       b
      PE        Prepended to
     l          Current list
    [    ]      Wrap that result in a singleton list
  l:            Assign back to l
          l    After the loop, l is our desired result wrapped in a singleton list
           @0  So get the first element
               and autoprint it, formatted as a list (-p flag)
\$\endgroup\$
3
\$\begingroup\$

JavaScript (ES6), 24 bytes

-2 thanks to @tsh

n=>g=x=>--x?[n,g(x)]:[n]
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Why not --x instead. \$\endgroup\$
    – tsh
    Dec 20, 2021 at 8:25
3
\$\begingroup\$

JavaScript (ES6), 27 bytes

f=(c,n)=>--n?[c,f(c,n)]:[c]

Try it out online.

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

Lua, 50 bytes

n,v=...t={v}for i=2,n do t={v,t}n=n-1 end return t

Try it online!

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

Retina, 31 bytes

L$`¶
$`*$([$', )$`*]
, (]+)$
$1

Try it online! Takes n and value on separate lines. Explanation:

L$`¶

Match the newline between n and value. This puts n in $` and value in $'.

$`*$([$', )$`*]

Wrap value in n lists.

, (]+)$
$1

Remove the trailing comma in the innermost list.

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

C (clang), 56 bytes

i;f(*x,n){for(i=~n;++i<n;)printf(i<0?",[%s"-i/n:"]",x);}

Try it online!

Takes a string literal as value and n , prints to std out the result.

for(i=~n;++i<n;)      - iterate from -n to n

printf(i<0?  - select format string:
",[%s"-i/n..x)  * new nest, -i/n to skip comma at first stage
:"]"            * close nest
```
\$\endgroup\$
1
\$\begingroup\$

Python, 38 bytes:

f=lambda n,v:[v,f(n-1,v)]if n>1else[v]

Try It Online!

\$\endgroup\$
7
  • 2
    \$\begingroup\$ This doesn't work for n=1 \$\endgroup\$
    – pxeger
    Dec 20, 2021 at 3:18
  • \$\begingroup\$ @pxeger Edited mine! \$\endgroup\$ Dec 20, 2021 at 3:23
  • \$\begingroup\$ 36 bytes now... \$\endgroup\$ Dec 20, 2021 at 9:30
  • 3
    \$\begingroup\$ You can't remove the f= because this is a recursive function which requires itself to be assigned to f \$\endgroup\$
    – pxeger
    Dec 20, 2021 at 19:21
  • \$\begingroup\$ @pxeger dingledooper did \$\endgroup\$ Dec 21, 2021 at 1:23

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.