Vous devez produire une fonction qui imbrique une chaîne s
dans un tableau, n
fois
>>> N("stackoverflow",2)
[['stackoverflow']]
Paramètres:
s
- Une chaîne asciin
- Un nombre entier>= 0
Règles
- Le code le plus court gagne.
- La sortie sera un imbriqué
array
,list
outuple
(ou un type similaire basé sur un tableau)
Cas de test
>>> N("stackoverflow",0)
'stackoverflow'
>>> N("stackoverflow",1)
['stackoverflow']
>>> N("stackoverflow",5)
[[[[['stackoverflow']]]]]
Inspiré par: imbriquer une chaîne dans une liste n fois, c'est-à-dire la liste d'une liste d'une liste
"
? Par exempleN("stack\"overflow",5)
Réponses:
Gelée , 2 octets
Légèrement déroutant, car: (1) Jelly n'a pas de chaînes, seulement des listes de personnages; et (2); la sortie ne montrera pas l'imbrication. Pour voir que cela fait réellement ce qui est demandé, regardez une représentation en chaîne Python du résultat avec:
Une paire supplémentaire de
[]
sera présente car la chaîne elle-même sera une liste de caractères.Par exempleComment?
Le code de preuve de concept ajoute:
la source
Java et C #, 62 octets
Devrait fonctionner sans modification à la fois en Java et en C #.
la source
05AB1E , 3 octets
Code
Explication
Cela signifie que cela fonctionne également pour le test 0 , car la chaîne est déjà sur la pile.
Essayez-le en ligne!
la source
JavaScript (ES6), 20 octets
Bien que les gens me harcèlent normalement pour utiliser mes fonctions pour la sauvegarde d'un octet, c'est un cas où cela contribue réellement à la solution.
la source
d=>g=n=>n?[g(n-1)]:d
Mathematica, 13 octets
la source
CJam ,
76 octetsInterprète en ligne
Ceci est une fonction anonyme qui prend ses arguments à partir de la pile comme
S N
,S
étant la chaîne etN
étant les enveloppes. Vous pouvez l'exécuter avec l'~
opérateur, ce qui signifie eval.Explication:
la source
{{a}*}
ou{'a*~}
.{a}
n fois) au lieu du second (produire une chaîne de na
s et l'exécuter).Javascript ES6, 23 octets
Fonction récursive
Les résultats de curry dans la même longueur
la source
Brachylog , 10 octets
Essayez-le en ligne!
Explication
Ce serait 3 octets s'il n'était pas buggé. Ici, nous avons besoin de tout cela pour obtenir la liste
[String, T, built-in_group]
même si[String, T]
c'est déjà notre entrée.Malheureusement, il
:g
en résulte directement[[String, T], built-in_group]
, qui n'est pas reconnu correctement pari
car l'entierT
est dans la première liste.la source
MATL, 6 octets
Cela produit un tableau de cellules imbriqué en sortie. Avec l'affichage par défaut de MATL, cependant, vous ne pouvez pas nécessairement voir ce que c'est car il n'affichera pas tous les accolades. La démo ci-dessous est une version légèrement modifiée qui montre la représentation sous forme de chaîne de la sortie.
Essayez-le en ligne
Explication
la source
Pyke, 3 octets
Essayez-le ici!
la source
Pyth, 3 bytes
Permalink
This will output something like
...[[[[['string']]]]]...
. It will not quote for zero depth:string
.Explanation:
If you want quoting on zero depth, use this 4-byte solution instead (explanation):
la source
PHP, 60 Bytes
48 Bytes if it looks only like the task
la source
function f($s,$n){return$n?[f($s,$n-1)]:$s;}
.print_r()
and, if you don't like that option,serialize()
are both shorter thanjson_encode()
ing it while differentiating the output.')
at the end of code looks strange.Ruby: 23 bytes
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.la source
->s,n{...}
.C,
44 bytes, 41 bytesYou can test it by doing the following:
The output:
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)
).la source
int*n(s,a)int*s;{return!a?s:n(&s,a-1);}
works with gcc.cc -v
->Apple LLVM version 8.0.0 (clang-800.0.38)
.!
from the ternary condition and switch the order ofs
andn(&s,a-1)
to save a byte?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.*
in the function signature?Python, 32 bytes
la source
Ruby, 25 characters
Rewrite of jamylak's Python solution.
Sample run:
la source
C# 6, 50 bytes
la source
n<1
? Also -2 bytes if you useobject
instead ofdynamic
.Ruby, 24 bytes
Called the same as in manatwork's answer, but a weirder implementation.
*s
wraps the input (a possibly-nested string) in an array. Then ifn
is zero,s[n]
returns the first element ofs
, turning the function into a no-op. Otherwise, it returnsnil
sinces
will only ever have one element, so we pass through to the recursive call.la source
V, 6 bytes
Try it online!
Explanation:
la source
Perl 6, 23 bytes
Expanded:
la source
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 verbosesucc
. So here is my code:(I hope I found all places where spaces can be omitted.)
L
is a type function that given a naturaln
and a typea
returns the type ofn
times nested lists ofa
, soL 3 Bool
would be the type of lists of lists of lists ofBool
(if we had importedBool
). 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 useC-c C-n
(evaluate term to normal form), input for examplef 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...la source
→
instead of->
, but of course that increases the size of an UTF-8 encoded file.k, 3 bytes
Taken as a dyadic function,
/
will iteratively apply the left-hand function,:
(enlist
) n times to the second argument.Example:
la source
PHP, 44 bytes
nothing sophisticated, just a recursive function
la source
Python 2, 32 bytes
Puts
n
open brackets before the string andn
close brackets before it, then evals the result. If a string output is allowed, theeval
can be removed.la source
Actually, 4 bytes
Input is
string
thenn
. Golfing suggestions welcome. Try it online!Ungolfing
la source
R,
3940 bytesEDIT: Fixed the
n=0
issue thanks to @rturnbull.Function that takes two inputs
s
(string) andn
(nestedness) and outputs the nested list. Note that R-classlist
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.Example
la source
n=0
, though. Before I saw your answer, I came up with a recursive solution which can deal withn=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
n=0
case. However, your solution is actually38
bytes excluding the naming of the function and hence shorter. Great catchf(s,n-1)
call inside of it.) Recursive anonymous functions are not possible in R, as far as I know.f=function(s,n)'if'(n,list(f(s,n-1)),s)
.Racket 83 bytes
Ungolfed:
Testing:
Output:
la source
Haskell,
4038 bytesHaskell's strict type system prevents returning different types (Strings vs. List of Strings vs. List of List of Strings,...), so I have to define my own type that accommodates all those cases. The main function
f
recursively callsn
times the constructorC
for nesting andN
for the base case.Usage example (with
deriving (Show)
added to the newdata
type to be able to print it):f 4 "codegolf"
->C (C (C (C (N "codegolf"))))
.Edit: @Christian Sievers saved 2 bytes by rewriting the function in a point-free style for the string argument. Thanks!
la source
deriving
clause: the parens aren't needed. - Not sure if it's okay to only nest theC
constructor which isn't list-like. My very similar attempt was based on a data type defined asdata D x=J x|L[D x]
.f 0=N;f n=C. f(n-1)
1:(2:(3:([])))
with C (C (C (N "codegolf"))).C
is cons (:
),N
is nil ([]
).C
doesn't cons, it only embeds, your data type can't express[["a","b"],["c"]]
. But maybe that is fine as this problem only needs singletons. -f n=...
isn't point-free. Point-reduced?Either
) even if it meant the constructors were a little more verbose?tinylisp (repl), 34 bytes
Defines a function
F
. Technically, tinylisp doesn't have strings, but this code will work for any data type it's given.Ungolfed (key to builtins:
d
= define,q
= quote,i
= if,c
= cons,s
= subtract):Example usage:
la source
Clojure, 24 bytes
Clojure is somewhat competitive here.
iterate
creates a sequence ofx, (f x), (f (f x)) ...
,nth
returns needed element.See it online: https://ideone.com/2rQ166
la source