배열 내부에 문자열을 n 번 중첩


16

당신은 문자열을 둥지 함수 생성해야 s배열 내부를 n

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

매개 변수 :

  1. s -아스키 문자열
  2. n -정수 >= 0

규칙

  • 가장 짧은 코드가 승리합니다.
  • 출력이 중첩 된 것 array, list또는 tuple(어레이 기반으로하거나 유사한 타입)

테스트 사례

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

고무시키는 : 리스트 안에 문자열을 n 번 중첩, 즉리스트리스트의리스트


6
출력이 목록이어야합니까, 아니면 해당 목록을 나타내는 문자열 일 수 있습니까?
clismique

2
우리는 어떤 순서로 매개 변수를 취할 수 있습니까?
Socratic Phoenix

@SocraticPhoenix 나는 명시 적으로 금지되지 않는 한, 네-합리적인 형식으로 입력 할 수 있다고 생각합니다 (이 두 가지를 목록으로 사용하는 것도 포함됩니다). 더 경험이 많은 사람이 관련 메타 게시물을 가리킬 수 있습니다.
Jonathan Allan

문자열에 이스케이프가 포함 "됩니까? 예N("stack\"overflow",5)
Riley

@Riley 모든 ASCII 문자를 포함 할 수 있습니다.
jamylak

답변:


11

젤리 , 2 바이트

(1) 젤리에는 문자열이없고 문자 목록 만 있습니다. 및 (2); 출력에 중첩이 표시되지 않습니다. 이것이 실제로 요청 된 것을하고 있는지 확인하려면 결과로 파이썬 문자열 표현을 살펴보십시오.

W¡ŒṘ

[]문자열 자체는 문자 목록이므로 추가 쌍이 존재합니다. 예를 들어

어떻게?

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

개념 증명 코드는 다음을 추가합니다.

W¡ŒṘ - Main link: s, n
  ŒṘ - Python string representation


문자열이 사용되는 것처럼 보이는 "더 나은" ... 실제로 문자 목록이 사용되고 있음을 나타내지는 않습니다.
Jonathan Allan

15

Java 및 C #, 62 바이트

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

Java와 C # 모두에서 수정하지 않고 작동해야합니다.


똑똑한! +1 실제로 작동하지 않는 문자열 배열을 중첩하여 Java에서 작동 시키려고했습니다. Object를 반환 유형으로 사용하고 Object []에 중첩하면 Object [] (또는 모든 배열)도 Object 자체이므로이 문제에 필요한 솔루션 일뿐입니다. 좋은데
Kevin Cruijssen

12

05AB1E , 3 바이트

암호

`F)

설명

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

이것은 문자열이 이미 스택에 있기 때문에 0- testcase 에서도 작동한다는 것을 의미합니다 .

온라인으로 사용해보십시오!


8

자바 스크립트 (ES6), 20 바이트

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

사람들은 일반적으로 1 바이트 절약을 위해 내 기능을 카레하라고 잔소리하지만 실제로 솔루션에 기여하는 경우입니다.


카레의 큰 사용. 좀 더 읽기 쉽게 만들 수 있다고 생각합니다.d=>g=n=>n?[g(n-1)]:d
ETHproductions


5

CJam , 7 6 바이트

{{a}*}

온라인 통역사

이 같은 스택에서 인수를 취하는 함수 이름 S N, S문자열 인 및 N랩 인. ~eval을 의미 하는 연산자로 실행할 수 있습니다 .

설명:

{{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]

이름이없는 블록을 사용하여 어색한 입력 형식 {{a}*}또는 을 피하십시오 {'a*~}.
Martin Ender

@MartinEnder 바이트가 걸릴 것이 두려워서 입력 형식이 100 % 허용된다고 생각합니다. 그것은 단지 목록 일 뿐이며 두 매개 변수를 입력하는 방법에 대한 제한은 없다고 생각합니다. 또한 블록 이름을 지정하지 않았습니다.
Outgolfer Erik

바이트에 대해 무슨 의미인지 모르겠습니다. 이러한 솔루션은 모두 6 바이트입니다.
Martin Ender

@MartinEnder 아,이 전체 솔루션입니까? 내 프로그램 확장에 대해 이야기하고 있다고 생각했지만 방금 함수로 변환 했습니까? 글쎄, 그것은 요점을 바꾼다. CJam / GolfScript / Pyth의 초보자입니다. 첫 번째는 두 번째 것보다 더 이해하기 쉽고 ( {a}n 번 반복 ) (n 개의 문자열을 생성 a하고 실행) 때문에 선호합니다 .
Outgolfer Erik

4

자바 스크립트 ES6, 23 바이트

재귀 함수

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))

같은 길이의 카레

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

4

근접 , 10 바이트

tT,?h:T:gi

온라인으로 사용해보십시오!

설명

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

버그가 없으면 3 바이트가됩니다. 여기에리스트를 얻으려면이 모든 것이 필요합니다[String, T, built-in_group][String, T] 이미 입력 한 것이지만 .

불행히도 :g직접 결과는 [[String, T], built-in_group]이며, i정수 T가 첫 번째 목록 안에 있기 때문에 제대로 인식되지 않습니다 .


4

MATL, 6 바이트

ji:"Xh

이렇게하면 중첩 셀형 배열이 출력으로 생성됩니다. 그러나 MATL의 기본 디스플레이를 사용하면 모든 중괄호가 표시되지 않기 때문에 이것이 무엇인지 수 없습니다 . 아래의 데모는 출력의 문자열 표현을 보여주는 약간 수정 된 버전입니다.

ji:"Xh]&D

온라인으로 사용해보십시오

설명

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


3

Pyth , 3 바이트

]Fw

퍼머 링크

다음과 같은 결과가 출력됩니다 ...[[[[['string']]]]].... 깊이가 0 인 경우 인용하지 않습니다 string.

설명:

]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

3

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;

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;}.
manatwork

print_r() and, if you don't like that option, serialize() are both shorter than json_encode()ing it while differentiating the output.
user59178

BTW, that lonely ') at the end of code looks strange.
manatwork

@manatwork Copy and Paste error Thank You
Jörg Hülsermann

3

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.


2
Generally your "a few more words" should be an explanation of how your code works. But it's a good answer nonetheless.
wizzwizz4

“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.
manatwork

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{...}.
Martin Ender

@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?
Peter Nixey

3

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)).


2
Not sure about other compilers, but int*n(s,a)int*s;{return!a?s:n(&s,a-1);} works with gcc.
Dennis

It segfaults for cc -v -> Apple LLVM version 8.0.0 (clang-800.0.38).
nimi

2
Can you drop the ! from the ternary condition and switch the order of s and n(&s,a-1) to save a byte?
Riley

2
@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.
Christian Sievers

1
Can you drop the spaces after the * in the function signature?
Fund Monica's Lawsuit


2

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"]]]]]

2

C# 6, 50 bytes

dynamic a(dynamic s,int n)=>n<2?s:a(new[]{s},n-1);

1
Shouldn't it be n<1? Also -2 bytes if you use object instead of dynamic.
milk

2

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.



2

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
}

Perl never ceases to amaze me with its syntax
Fund Monica's Lawsuit

2

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...


Just remembered that I could write instead of ->, but of course that increases the size of an UTF-8 encoded file.
Christian Sievers

My ugly translation of this into Haskell is somewhat shorter. I have to stick to manual unary to keep it short.
dfeuer

2

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"

1

PHP, 44 bytes

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

nothing sophisticated, just a recursive function


1

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.


1

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.

1

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"

1
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
rturnbull

@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
Billywob

1
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.
rturnbull

@rturnbull You're again right. Updating the answer.
Billywob

A year later, I've golfed off another byte: f=function(s,n)'if'(n,list(f(s,n-1)),s).
rturnbull

1

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']]]"

1

Haskell, 40 38 bytes

data L=N[Char]|C L 
f 0=N
f n=C. f(n-1)

Haskell'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 calls n times the constructor C for nesting and N for the base case.

Usage example (with deriving (Show) added to the new data 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!


Of course Haskell's lists can be nested, but a function cannot return a string for one value and a list of lists of strings for another value of the same type. Golfing the additional deriving clause: the parens aren't needed. - Not sure if it's okay to only nest the C constructor which isn't list-like. My very similar attempt was based on a data type defined as data D x=J x|L[D x].
Christian Sievers

If you reverse the order of the arguments and don't use an infix operator, you don't need to mention the second argument: f 0=N;f n=C. f(n-1)
Christian Sievers

@ChristianSievers: yes, you're right, my explanation about nested lists was not accurate - I've changed it. Regarding list-likeness: I think my data structure is list-like. Compare a native Haskell list 1:(2:(3:([]))) with C (C (C (N "codegolf"))). C is cons (:), N is nil ([]).
nimi

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?
Christian Sievers

You spend 19 characters defining your data type. Wouldn't it be more sensible to use an existing type (e.g. Either) even if it meant the constructors were a little more verbose?
Periata Breatta

1

tinylisp (repl), 34 bytes

(d F(q((S N)(i N(F(c S())(s N 1))S

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):

(d nest
 (q
  ((item number)
   (i number
    (nest (c item ()) (s number 1))
    item))))

Example usage:

tl> (d F(q((S N)(i N(F(c S())(s N 1))S
F
tl> (F 2 3)
(((2)))
tl> (F () 1)
(())
tl> (F (q Hello!) 7)
(((((((Hello!)))))))
tl> (F c 3)
(((<builtin function tl_cons>)))

1

Clojure, 24 bytes

#(nth(iterate list %)%2)

Clojure is somewhat competitive here. iterate creates a sequence of x, (f x), (f (f x)) ..., nth returns needed element.

See it online: https://ideone.com/2rQ166

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.