20
\$\begingroup\$

You must produce a function which nests a string s inside an array, n times

>>> N("stackoverflow",2)
[['stackoverflow']]

Parameters:

  1. s - An ascii string
  2. n - An integer >= 0

Rules

  • Shortest code wins.
  • The output will be a nested array, list or tuple (or similar type based off an array)

Test Cases

>>> N("stackoverflow",0)
'stackoverflow'
>>> N("stackoverflow",1)
['stackoverflow']
>>> N("stackoverflow",5)
[[[[['stackoverflow']]]]]

Inspired by: Nesting a string inside a list n times ie list of a list of a list

\$\endgroup\$
10
  • 7
    \$\begingroup\$ Does the output have to be a list, or can it be a string representing that list? \$\endgroup\$
    – clismique
    Oct 17, 2016 at 10:53
  • 3
    \$\begingroup\$ Can we take the parameters in any order? \$\endgroup\$ Oct 17, 2016 at 10:56
  • \$\begingroup\$ @SocraticPhoenix I think unless explicitly forbidden, yes - you can take the input in any reasonable format (which would include taking the two as a list too I believe). Maybe someone more experienced can point to a relevant meta post. \$\endgroup\$ Oct 17, 2016 at 11:37
  • \$\begingroup\$ Will the string ever include an escaped "? E.g. N("stack\"overflow",5) \$\endgroup\$
    – Riley
    Oct 17, 2016 at 14:06
  • \$\begingroup\$ @Riley It could contain any ascii character \$\endgroup\$
    – jamylak
    Oct 17, 2016 at 23:48

61 Answers 61

17
\$\begingroup\$

Java and C#, 62 bytes

Object f(String s,int n){return n<1?s:new Object[]{f(s,n-1)};}

Should work without modification in both Java and C#.

\$\endgroup\$
1
  • \$\begingroup\$ Smart! +1 I was trying to get it to work in Java by nesting a String-array, which didn't really work out. Using an Object as return type and nest it in an Object[] is just the solution required for this challenge, since Object[] (or any array) is also an Object themselves. Nice one. \$\endgroup\$ Oct 17, 2016 at 13:19
12
\$\begingroup\$

05AB1E, 3 bytes

Code

`F)

Explanation

`   # Flatten the input array on the stack.
 F  # Element_2 times do:
  ) # Wrap the total stack into a single array.

This means that this also works for the 0-testcase, since the string is already on the stack.

Try it online!

\$\endgroup\$
0
11
\$\begingroup\$

Jelly, 2 bytes

Slightly confusing, since: (1) Jelly has no strings, only lists of characters; and (2); the output wont show the nesting. To see that this actually is doing what is asked look at a Python string representation of the result with:

W¡ŒṘ

An extra pair of [] will be present since the string itself will be a list of characters. For example

How?

W¡ - Main link: s, n
W  - wrap left, initially s, in a list
 ¡ - repeat previous link n times

The proof-of-concept code adds:

W¡ŒṘ - Main link: s, n
  ŒṘ - Python string representation
\$\endgroup\$
2
9
\$\begingroup\$

JavaScript (ES6), 20 bytes

d=>g=n=>n--?[g(n)]:d

Although people normally nag me to curry my functions for the 1-byte saving, this is a case where it actually contributes to the solution.

\$\endgroup\$
1
  • \$\begingroup\$ Great use of currying. I think you can make it slightly more readable: d=>g=n=>n?[g(n-1)]:d \$\endgroup\$ Oct 17, 2016 at 22:59
7
\$\begingroup\$

Mathematica, 13 bytes

List~Nest~##&
\$\endgroup\$
5
\$\begingroup\$

CJam, 7 6 bytes

{{a}*}

Online interpreter

This is an unnamed function that takes its arguments from the stack as S N, S being the string and N being the wraps. You can execute it with the ~ operator, meaning eval.

Explanation:

{{a}*}
{      Open block    [A B]
 {     Open block    [A]
  a    Wrap in array [[A]]
   }   Close block   [A B λwrap]
    *  Repeat        [A:wrap(*B)]
     } Close block   ["S" N λ(λwrap)repeat]
\$\endgroup\$
4
  • \$\begingroup\$ Just use an unnamed block to avoid the awkward input format {{a}*} or {'a*~}. \$\endgroup\$ Oct 17, 2016 at 13:06
  • \$\begingroup\$ @MartinEnder I'm afraid it would take bytes, though, and I think that input format is 100% acceptable. It's just a list, and I think there is no restriction as to how those two parameters are entered. Also, I never named the block. \$\endgroup\$ Oct 17, 2016 at 13:13
  • \$\begingroup\$ I don't know what you mean about the bytes? Both of those solutions are only 6 bytes. \$\endgroup\$ Oct 17, 2016 at 13:14
  • \$\begingroup\$ @MartinEnder Oh, were these whole solutions? I thought you were talking about extending my program, but you just converted it to a function? Well, that changes the whole point. I'm a newbie at CJam/GolfScript/Pyth. I prefer the first one because it's more comprehensible (repeat {a} n times) instead of the second one (produce a string of n as and execute it). \$\endgroup\$ Oct 17, 2016 at 13:16
4
\$\begingroup\$

Javascript ES6, 23 bytes

Recursive function

f=(a,i)=>i?f([a],--i):a

console.log(f("stackoverflow",0))
console.log(f("stackoverflow",1))
console.log(f("stackoverflow",2))
console.log(f("stackoverflow",5))

Currying results in the same length

f=a=>i=>i?f([a])(--i):a
\$\endgroup\$
4
\$\begingroup\$

Brachylog, 10 bytes

tT,?h:T:gi

Try it online!

Explanation

tT,            T is the integer (second element of the Input)
   ?h:T:g      The list [String, T, built-in_group]
         i     Iterate: Apply built-in_group T times to String

This would be 3 bytes if it wasn't bugged. Here we need all this to get the list [String, T, built-in_group] even though [String, T] is already our input.

Unfortunately :g directly results in [[String, T], built-in_group], which is not recognized properly by i because the integer T is inside the first list.

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

MATL, 6 bytes

ji:"Xh

This produces a nested cell array as the output. With MATL's default display, however, you can't necessary see that's what it is since it won't show all of the curly braces. The demo below is a slightly modified version which shows the string representation of the output.

ji:"Xh]&D

Try it Online

Explanation

j       % Explicitly grab the first input as a string
i       % Explicitly grab the second input as an integer (n)
:"      % Create an array [1...n] and loop through it
    Xh  % Each time through the loop place the entire stack into a cell array
        % Implicit end of for loop and display
\$\endgroup\$
4
\$\begingroup\$

Pyke, 3 bytes

V]1

Try it here!

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

Python, 32 bytes

N=lambda s,n:n and[N(s,n-1)]or s
\$\endgroup\$
3
\$\begingroup\$

Pyth, 3 bytes

]Fw

Permalink

This will output something like ...[[[[['string']]]]].... It will not quote for zero depth: string.

Explanation:

]Fw
   Q Implicit: Eval first input line
]    Function: Wrap in array
  w  Input line
 F   Apply multiple times

If you want quoting on zero depth, use this 4-byte solution instead (explanation):

`]Fw
    Q Implicit: Eval first input line
 ]    Function: Wrap in array
   w  Input line
  F   Apply multiple times
`     Representation
\$\endgroup\$
3
\$\begingroup\$

PHP, 60 Bytes

for($r=$argv[1];$i++<$argv[2];)$r=[$r];echo json_encode($r);

48 Bytes if it looks only like the task

for($r=$argv[1];$i++<$argv[2];)$r="[$r]";echo$r;
\$\endgroup\$
4
  • \$\begingroup\$ I think a direct rewrite of the question owner's own Python answer is still the shortest in PHP too: function f($s,$n){return$n?[f($s,$n-1)]:$s;}. \$\endgroup\$
    – manatwork
    Oct 17, 2016 at 11:41
  • \$\begingroup\$ print_r() and, if you don't like that option, serialize() are both shorter than json_encode()ing it while differentiating the output. \$\endgroup\$
    – user59178
    Oct 17, 2016 at 11:56
  • \$\begingroup\$ BTW, that lonely ') at the end of code looks strange. \$\endgroup\$
    – manatwork
    Oct 17, 2016 at 12:46
  • \$\begingroup\$ @manatwork Copy and Paste error Thank You \$\endgroup\$ Oct 17, 2016 at 13:09
3
\$\begingroup\$

Ruby: 23 bytes

->n,s{n.times{s=[s]};s}

This is updated to make it a callable Proc rather than the original snippet. I'd be interested to know whether there's a way to have s implicitly returned rather than having to explicitly return it.

\$\endgroup\$
4
  • 2
    \$\begingroup\$ Generally your "a few more words" should be an explanation of how your code works. But it's a good answer nonetheless. \$\endgroup\$
    – wizzwizz4
    Oct 17, 2016 at 17:10
  • \$\begingroup\$ “You must produce a function” This is a code snippet. Unless explicitly specified otherwise, input and output has to be handled explicitly by the code or implicitly by the interpreter if it has such feature. You can not expect some global variables to be set and you can not just leave the result in some global variables. \$\endgroup\$
    – manatwork
    Oct 17, 2016 at 17:14
  • \$\begingroup\$ Welcome to PPCG! All answers should be callable functions or full programs, though. In your case, the shortest fix would be to use an unnamed function like ->s,n{...}. \$\endgroup\$ Oct 17, 2016 at 17:14
  • \$\begingroup\$ @wizzwizz4, and Martin, thank you for your encouragement and helpful input, I have learned something and will update. manatwork, I've got thick skin and have plenty of points on SO but you know that blunt statements like that scare newbies away from Stack sites and intimidate them. Seems a shame no? \$\endgroup\$ Oct 18, 2016 at 14:13
3
\$\begingroup\$

C, 44 bytes, 41 bytes

int*n(int*s,int a){return a?n(&s,a-1):s;}

You can test it by doing the following:

int main(void) {
    char* s = "stackoverflow";

    /* Test Case 0 */
    int* a = n(s,0);
    printf("'%s'\n", a);

    /* Test Case 1 */
    int* b = n(s,1);
    printf("['%s']\n", *b);

    /* Test Case 2 */
    int** c = n(s,2);
    printf("[['%s']]\n", **c);

    /* Test Case 3 */
    int*** d = n(s,3);
    printf("[[['%s']]]\n", ***d);

    /* Test Case 4 */
    int********** e = n(s,10);
    printf("[[[[[[[[[['%s']]]]]]]]]]\n", **********e);

    return 0;
}

The output:

'stackoverflow'
['stackoverflow']
[['stackoverflow']]
[[['stackoverflow']]]
[[[[[[[[[['stackoverflow']]]]]]]]]]

Of course, you'll get warnings. This works on gcc on bash on my Windows machine (gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.3), as well as on a true Linux machine (gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)).

\$\endgroup\$
11
  • 2
    \$\begingroup\$ Not sure about other compilers, but int*n(s,a)int*s;{return!a?s:n(&s,a-1);} works with gcc. \$\endgroup\$
    – Dennis
    Oct 17, 2016 at 22:38
  • \$\begingroup\$ It segfaults for cc -v -> Apple LLVM version 8.0.0 (clang-800.0.38). \$\endgroup\$
    – nimi
    Oct 17, 2016 at 22:51
  • 2
    \$\begingroup\$ Can you drop the ! from the ternary condition and switch the order of s and n(&s,a-1) to save a byte? \$\endgroup\$
    – Riley
    Oct 18, 2016 at 14:53
  • 2
    \$\begingroup\$ @VolAnd When you call n(s,6), you have to change *** to ****** in the variable declaration and use. This is needed exactly because the function does what it is expected to do: nest the string into an array several (here: 6) times. Of course you would still get three levels of [] because they are hardcoded. I think the program shouldn't output them at all. This challenge is not about brackets, it is about nesting. Some languages print arrays with brackets, C hasn't any builtin function to print them at all. So what? It is not needed here. \$\endgroup\$ Oct 19, 2016 at 2:58
  • 1
    \$\begingroup\$ Can you drop the spaces after the * in the function signature? \$\endgroup\$
    – anon
    Oct 19, 2016 at 4:04
3
\$\begingroup\$

k, 3 bytes

,:/

Taken as a dyadic function, / will iteratively apply the left-hand function ,: (enlist) n times to the second argument.

Example:

k),:/[3;"hello"]
,,,"hello"
\$\endgroup\$
3
\$\begingroup\$

Thunno, \$ 5 \log_{256}(96) \approx \$ 4.12 bytes

s{KZO

Attempt This Online!

If the inputs could be taken in any order, the leading s could be dropped.

Explanation

s{KZO  # Implicit input
s      # Swap so the number is on top
 {K    # Loop input number of times:
   ZO  # Wrap in a list
       # Implicit output
\$\endgroup\$
0
2
\$\begingroup\$

Ruby, 25 characters

Rewrite of jamylak's Python solution.

f=->s,n{n>0?[f[s,n-1]]:s}

Sample run:

irb(main):001:0> f=->s,n{n>0?[f[s,n-1]]:s}
=> #<Proc:0x00000002006e80@(irb):1 (lambda)>

irb(main):002:0> f["stackoverflow",0]
=> "stackoverflow"

irb(main):003:0> f["stackoverflow",1]
=> ["stackoverflow"]

irb(main):004:0> f["stackoverflow",5]
=> [[[[["stackoverflow"]]]]]
\$\endgroup\$
2
\$\begingroup\$

C# 6, 50 bytes

dynamic a(dynamic s,int n)=>n<2?s:a(new[]{s},n-1);
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Shouldn't it be n<1? Also -2 bytes if you use object instead of dynamic. \$\endgroup\$
    – milk
    Oct 17, 2016 at 20:26
2
\$\begingroup\$

Ruby, 24 bytes

f=->*s,n{s[n]||f[s,n-1]}

Called the same as in manatwork's answer, but a weirder implementation. *s wraps the input (a possibly-nested string) in an array. Then if n is zero, s[n] returns the first element of s, turning the function into a no-op. Otherwise, it returns nil since s will only ever have one element, so we pass through to the recursive call.

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

V, 6 bytes

Àñys$]

Try it online!

Explanation:

À      "Arg1 times
 ñ     "repeat:
  ys$  "surround this line
     ] "with square brackets
\$\endgroup\$
2
\$\begingroup\$

Perl 6, 23 bytes

{($^a,{[$_]}...*)[$^b]}

Expanded:

{ # bare block lambda with two placeholder parameters 「$a」 and 「$b」
  (

    # generate Sequence

    $^a,       # declare first input
    { [ $_ ] } # lambda that adds one array layer
    ...        # do that until
    *          # Whatever

  )[ $^b ]     # index into the sequence
}
\$\endgroup\$
1
  • \$\begingroup\$ Perl never ceases to amaze me with its syntax \$\endgroup\$
    – anon
    Oct 19, 2016 at 4:06
2
\$\begingroup\$

Agda, 173 bytes

Since the return type of the function depends on the number given as argument, this is clearly a case where a dependently typed language should be used. Unfortunately, golfing isn't easy in a language where you have to import naturals and lists to use them. On the plus side, they use suc where I would have expected the verbose succ. So here is my code:

module l where
open import Data.List
open import Data.Nat
L : ℕ -> Set -> Set
L 0 a = a
L(suc n)a = List(L n a)
f : ∀ n{a}-> a -> L n a
f 0 x = x
f(suc n)x = [ f n x ]

(I hope I found all places where spaces can be omitted.) L is a type function that given a natural n and a type a returns the type of n times nested lists of a, so L 3 Bool would be the type of lists of lists of lists of Bool (if we had imported Bool). This allows us to express the type of our function as (n : ℕ) -> {a : Set} -> a -> L n a, where the curly braces make that argument implicit. The code uses a shorter way to write this type. The function can now be defined in an obvious way by pattern matching on the first argument.

Loading this file with an .agda extension into emacs allows to use C-c C-n (evaluate term to normal form), input for example f 2 3 and get the correct answer in an awkward form: (3 ∷ []) ∷ []. Now of course if you want to do that with strings you have to import them...

\$\endgroup\$
2
  • \$\begingroup\$ Just remembered that I could write instead of ->, but of course that increases the size of an UTF-8 encoded file. \$\endgroup\$ Oct 18, 2016 at 12:11
  • \$\begingroup\$ My ugly translation of this into Haskell is somewhat shorter. I have to stick to manual unary to keep it short. \$\endgroup\$
    – dfeuer
    Jun 17, 2019 at 23:15
2
\$\begingroup\$

Japt, 8 bytes

@[X]}gNÅ

Try it

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

Jellyfish, 8 bytes

p\Ai
 ;i

Try it online!

Unary ; wraps its argument in a list. Binary \ on a function and a value n iterates that function n times.

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

PHP, 44 bytes

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

nothing sophisticated, just a recursive function

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

Python 2, 32 bytes

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

Puts n open brackets before the string and n close brackets before it, then evals the result. If a string output is allowed, the eval can be removed.

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

Actually, 4 bytes

Input is string then n. Golfing suggestions welcome. Try it online!

`k`n

Ungolfing

          Implicit input string, then n.
`...`n    Run the function n times.
  k         Wrap the stack in a list.
          Implicit return.
\$\endgroup\$
1
\$\begingroup\$

R, 39 40 bytes

EDIT: Fixed the n=0 issue thanks to @rturnbull.

Function that takes two inputs s (string) and n (nestedness) and outputs the nested list. Note that R-class list natively prints output differently than most other languages, however, is functionally similar to a key/value map (with possibly unnamed keys) or a list in python.

f=function(s,n)if(n)list(f(s,n-1))else s

Example

> f=function(s,n)if(n)list(f(s,n-1))else s
> f("hello",3)
[[1]]
[[1]][[1]]
[[1]][[1]][[1]]
[1] "hello"


> # to access the string nested 5 times in the "list-object" named "list" we can do the following
> list = f("nested string",5)
> list[[1]][[1]][[1]][[1]][[1]]
[1] "nested string"
\$\endgroup\$
5
  • 1
    \$\begingroup\$ Very nice! It doesn't give the desired output for n=0, though. Before I saw your answer, I came up with a recursive solution which can deal with n=0, but it's 1 byte longer than your solution (40 bytes): f=function(s,n)if(n)list(f(s,n-1))else s \$\endgroup\$
    – rturnbull
    Oct 18, 2016 at 11:07
  • \$\begingroup\$ @rturnbull You're of course right. Your solution is much more elegant in my opinion and I totally forgot about the n=0 case. However, your solution is actually 38 bytes excluding the naming of the function and hence shorter. Great catch \$\endgroup\$
    – Billywob
    Oct 18, 2016 at 11:13
  • 1
    \$\begingroup\$ Since it's a recursive function it must be named, unfortunately! (Otherwise it can't interpret the f(s,n-1) call inside of it.) Recursive anonymous functions are not possible in R, as far as I know. \$\endgroup\$
    – rturnbull
    Oct 18, 2016 at 11:33
  • \$\begingroup\$ @rturnbull You're again right. Updating the answer. \$\endgroup\$
    – Billywob
    Oct 18, 2016 at 11:36
  • \$\begingroup\$ A year later, I've golfed off another byte: f=function(s,n)'if'(n,list(f(s,n-1)),s). \$\endgroup\$
    – rturnbull
    Nov 15, 2017 at 20:01
1
\$\begingroup\$

Racket 83 bytes

(for((c n))(set! s(apply string-append(if(= c 0)(list"[\'"s"\']")(list"["s"]")))))s

Ungolfed:

(define (f s n)
  (for ((c n))
    (set! s (apply string-append
                   (if (= c 0)
                       (list "[\'" s "\']")
                       (list "[" s "]"))
                   )))
  s)

Testing:

(f "test" 3)

Output:

"[[['test']]]"
\$\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.