76
\$\begingroup\$

To "function nest" a string, you must:

  • Treat the first character as a function, and the following characters as the arguments to that function. For example, if the input string was Hello, then the first step would be:

    H(ello)
    
  • Then, repeat this same step for every substring. So we get:

    H(ello)
    H(e(llo))
    H(e(l(lo)))
    H(e(l(l(o))))
    

Your task is to write a program or function that "function nests" a string. For example, if the input string was Hello world!, then you should output:

H(e(l(l(o( (w(o(r(l(d(!)))))))))))

The input will only ever contain printable ASCII, and you may take the input and the output in any reasonable format. For example, STDIN/STDOUT, function arguments and return value, reading and writing to a file, etc.

For simplicity's sake, you may also assume the input will not contain parentheses, and will not be empty.

Input:
Nest a string
Output:
N(e(s(t( (a( (s(t(r(i(n(g))))))))))))

Input:
foobar
Output:
f(o(o(b(a(r)))))

Input:
1234567890
Output:
1(2(3(4(5(6(7(8(9(0)))))))))

Input:
code-golf
Output:
c(o(d(e(-(g(o(l(f))))))))

Input:
a
Output:
a

Input:
42
Output:
4(2)

As usual, all of our default rules and loopholes apply, and the shortest answer scored in bytes wins!

\$\endgroup\$
  • 21
    \$\begingroup\$ Ahem: Is this message anything to do with the challenge? :-) \$\endgroup\$ – wizzwizz4 Oct 18 '16 at 18:46
  • 11
    \$\begingroup\$ T​I​L 4​2​ ​= 8 \$\endgroup\$ – ETHproductions Oct 18 '16 at 21:48
  • \$\begingroup\$ What is maximum length for the input string? Incase of recursive methods \$\endgroup\$ – Ferrybig Oct 23 '16 at 20:30
  • \$\begingroup\$ Is the output the execution of said function, or merely the string itself? \$\endgroup\$ – nl-x Oct 24 '16 at 12:24
  • 1
    \$\begingroup\$ @kamoroso94 You may take the input and the output in any reasonable format. A list of characters seems perfectly reasonable to me. \$\endgroup\$ – DJMcMayhem Sep 1 '17 at 15:29

91 Answers 91

63
\$\begingroup\$

Python, 41 39 34 bytes

lambda e:"(".join(e)+")"*~-len(e)

Ideone it

Pretty self explanatory.

It puts a parenthesis between every other character then adds one less than the length parentheses to the end.

\$\endgroup\$
  • 13
    \$\begingroup\$ That ~- trick is cool, I will need to remember that. \$\endgroup\$ – Skyler Oct 18 '16 at 19:25
  • \$\begingroup\$ how does the ~-trick work ? \$\endgroup\$ – ShadowFlame Oct 19 '16 at 14:08
  • 1
    \$\begingroup\$ @ShadowFlame - makes the number negative and ~ bit flips it. You can read a bit more about it on the tips page. \$\endgroup\$ – Sriotchilism O'Zaic Oct 19 '16 at 14:11
  • 1
    \$\begingroup\$ @ShadowFlame. The mechanics of it is as WheatWidard said. It works on systems that use twos-complement mode to store negative numbers (which is most systems nowadays). \$\endgroup\$ – Mad Physicist Oct 21 '16 at 17:40
  • 1
    \$\begingroup\$ @MadPhysicist With Python, it works always, because ~ is defined as -x-1 \$\endgroup\$ – Mega Man May 28 '18 at 12:51
45
\$\begingroup\$

MS-DOS .com file, 30 bytes

0000   fc be 82 00 b4 02 ac 88 c2 cd 21 ac 3c 0d 74 0d
0010   b2 28 50 cd 21 5a e8 f0 ff b2 29 cd 21 c3

The string is passed to the executable using the command line. (One space character between the .COM file name and the string).

The result is written to standard output.

The disassembly is here:

  fc          cld              ; Make sure DF is not set (lodsb!)
  be 82 00    mov    si,0x82   ; First character of command line args
  b4 02       mov    ah,0x2    ; AH=2 means output for INT 21h
  ac          lodsb            ; Load first character
  88 c2       mov    dl,al     ; Move AL to DL (DL is written to output)
recursiveFunction:
  cd 21       int    0x21      ; Output
  ac          lodsb            ; Get the next character
  3c 0d       cmp    al,0xd    ; If it is "CR" (end of command line) ...
  74 0d       je     doReturn  ; ... return from the recursive function
  b2 28       mov    dl,0x28   ; Output "(" next...
  50          push   ax        ; ... but save character read first
  cd 21       int    0x21      ; (Actual output)
  5a          pop    dx        ; Restore character (but in DL, not in AL)
  e8 f0 ff    call   recursiveFunction  ; Recursively enter the function
doReturn:
  b2 29       mov    dl,0x29   ; Output ")"
  cd 21       int    0x21
  c3          ret              ; Actually return

Note: You can exit a DOS .COM file (unlike files with EXE headers) using a "RET" instruction.

\$\endgroup\$
  • \$\begingroup\$ Since I can't find any actual documentation or satisfactory info: why call 0xfoff? The program is loaded into memory at address 0 as far as I can tell (or 0x100 on CP/M-DOS but these appear to be x86 instructions), why is recursiveFunction suddenly located at 0xffof? It appears to begin 9 bytes after the beginning of the program, and there is no virtualisation or metadata in the executable. \$\endgroup\$ – cat Oct 20 '16 at 23:19
  • 6
    \$\begingroup\$ DOS loads .COM files to address 0x100 however this program would even run on ANY address: e8 f0 ff is a relative call instruction: It jumps to the address of the instruction following the call instruction minus 0x10. \$\endgroup\$ – Martin Rosenau Oct 21 '16 at 5:59
32
\$\begingroup\$

JavaScript (ES6), 40 34 33 bytes

Saved 6 bytes, thanks to ETHproductions

A recursive function.

f=([c,...s])=>s+s?c+`(${f(s)})`:c

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ Nice trick with 1/s. \$\endgroup\$ – ETHproductions Oct 18 '16 at 19:38
  • \$\begingroup\$ Super nice trick with ([c,...s]) you should write a tip \$\endgroup\$ – edc65 Oct 18 '16 at 21:27
  • \$\begingroup\$ @edc65 Just for sake of clarity, this one was suggested by ETHproductions. \$\endgroup\$ – Arnauld Oct 18 '16 at 21:40
  • \$\begingroup\$ o well, someone has to write a tip anyway \$\endgroup\$ – edc65 Oct 18 '16 at 21:42
  • 1
    \$\begingroup\$ @jmingov thank you, I know. The point here is using DA to to slice a string in a very short way (very shorter than .slice) \$\endgroup\$ – edc65 Oct 19 '16 at 7:16
26
\$\begingroup\$

Brainfuck, 42 40 bytes

>+[-->+[<]>-]>+>>,.,[<+<.>>.,]<<+>[-<.>]

Try it online!

Ungolfed:

>+[-->+[<]>-]>+     # count to 40 (ASCII for open paren)
>>                  # move to the input holder
,.                  # input the first byte and output it
,                   # input the next byte
[                   # while it's not zero
  <+                # move to the input counter and increment it
  <.                # move to the open paren and output it
  >>.               # move to the input holder and output it
  ,                 # input the next byte
]
<<+                 # move to the open paren and increment it to a close
>                   # move to the input counter
[                   # while it's not zero
  -                 # decrement it
  <.                # move to the close paren and output it
  >                 # move to the input counter
]
\$\endgroup\$
  • 1
    \$\begingroup\$ There is usually a shorter way to get a constant than the obvious 2-factor multiplication. \$\endgroup\$ – Martin Ender Oct 18 '16 at 20:16
  • \$\begingroup\$ Ah nice, thanks. This was my first BF submission (my first BF program at all, really) so I'm sure there are lots of other possible improvements too. \$\endgroup\$ – Alex Howansky Oct 18 '16 at 20:58
  • \$\begingroup\$ you got one pair of brackets to much!? \$\endgroup\$ – Vloxxity Oct 21 '16 at 14:04
  • \$\begingroup\$ This puts an empty pair of parentheses after the last character of the string. I don't know if there's a way to avoid that without adding ",." before the loop and switching the output order inside the loop, which makes the program two bytes longer. \$\endgroup\$ – user59468 Oct 21 '16 at 22:34
  • \$\begingroup\$ Ah bugger, you're right. I didn't read carefully enough and made the last letter a function call like the others. \$\endgroup\$ – Alex Howansky Oct 23 '16 at 17:54
22
\$\begingroup\$

05AB1E, 11 bytes

S'(ý¹g<')×J

Try it online!

Explanation:

S'(ý         join input by "("
    ¹g<      push length of input - 1, call it n
       ')×   push a string with char ")" n times
          J  concatenate
\$\endgroup\$
16
\$\begingroup\$

Brainfuck, 44 bytes

>+++++[-<++++++++>],.,[<.>.>+<,]<+>>[-<<.>>]

Reads a byte at a time, puts an open-paren before each one except the first, puts the same number of close-parens at the end.

\$\endgroup\$
16
\$\begingroup\$

Haskell, 30 bytes

f[x]=[x]
f(a:b)=a:'(':f b++")"

Usage example: f "Nest a string" -> "N(e(s(t( (a( (s(t(r(i(n(g))))))))))))".

Take the next char, followed by a (, followed by a recursive call with all but the first char, followed by a ).

\$\endgroup\$
  • 1
    \$\begingroup\$ If we interpret the answers as Haskell, we can solve it with just f=Data.List.intersperse '$'! That gives us f "Nest a string" -> "N$e$s$t$ $a$ $s$t$r$i$n$g". \$\endgroup\$ – porglezomp Oct 19 '16 at 1:02
  • \$\begingroup\$ Just wanted to let you know that @fornit (he hasn't enough rep to comment) suggested to use f[]=[] as a base case instaed of your f[x]=[x]. I'm not familiar with Haskell so I don't know whether it's legit or not, I'll let you judge. \$\endgroup\$ – Dada Oct 24 '16 at 13:13
  • \$\begingroup\$ @Dada: that won't work, because it would put an additional () behind the last letter, e.g. f "abc" -> "a(b(c()))". \$\endgroup\$ – nimi Oct 24 '16 at 15:52
  • \$\begingroup\$ This also doesn’t handle empty input. The shortest correct version I could come up with is 44, with a different technique: f=(++).intersperse '('<*>drop 1.map(\_->')'). \$\endgroup\$ – Jon Purdy Oct 27 '16 at 3:48
  • \$\begingroup\$ @JonPurdy: we don't have to handle empty input. intersperse requires import Data.List for another 17 bytes. \$\endgroup\$ – nimi Oct 27 '16 at 9:15
15
\$\begingroup\$

Jelly, 9 8 bytes

-1 byte thanks to @Dennis (use mould, , in place of length, L, and repeat, x)

j”(³”)ṁṖ

TryItOnline

How?

j”(³”)ṁṖ - Main link: s     e.g. "code-golf"           printed output:
j        - join s with
 ”(      - literal '('           "c(o(d(e(-(g(o(l(f"
    ”)   - literal ')'
      ṁ  - mould like
   ³     - first input, s        ")))))))))"
         - causes print with no newline of z:          c(o(d(e(-(g(o(l(f
       Ṗ - pop (z[:-1])          "))))))))"            c(o(d(e(-(g(o(l(f
         - implicit print                              c(o(d(e(-(g(o(l(f))))))))
\$\endgroup\$
  • 3
    \$\begingroup\$ Btw, ³ actually causes Jelly to print the current return value, so you never have two lists of chars. \$\endgroup\$ – Dennis Oct 18 '16 at 21:09
13
\$\begingroup\$

Retina, 22 17 bytes

\1>`.
($&
T`(p`)_

Try it online!

Alternatively:

S_`
\`¶
(
T`(p`)_

Explanation

I always forget that it's possible to print stuff along the way instead of transforming everything into the final result and outputting it in one go...

\1>`.
($&

Here \ tells Retina to print the result of this stage without a trailing linefeed. The 1> is a limit which means that the first match of the regex should be ignored. As for the stage itself, it simply replaces each character (.) except the first with ( followed by that character. In other words, it inserts ( in between each pair of characters. For input abc, this transforms it into (and prints)

a(b(c

All that's left is to print the closing parentheses:

T`(p`)_

This is done with a transliteration which replaces ( with ) and deletes all other printable ASCII characters from the string.

\$\endgroup\$
  • \$\begingroup\$ Dangit. So fast... \$\endgroup\$ – mbomb007 Oct 18 '16 at 18:43
  • \$\begingroup\$ @mbomb007 ...and far from optimal. ;) \$\endgroup\$ – Martin Ender Oct 18 '16 at 19:05
13
\$\begingroup\$

><>, 19 18 bytes

io8i:&0(.')('o&!
o

Try it online!

Explanation

The first line is an input loop which prints everything up to the last character of the input (including all the () and leaves the right amount of ) on the stack:

io                 Read and print the first character.
  8                Push an 8 (the x-coordinate of the . in the program).
   i               Read a character. Pushes -1 at EOF.
    :&             Put a copy in the register.
      0(           Check if negative. Gives 1 at EOF, 0 otherwise.
        .          Jump to (8, EOF?). As long as we're not at EOF, this is
                   a no-op (apart from popping the two coordinates). At EOF
                   it takes us to the second line.
         ')('      Push both characters.
             o     Output the '('.
              &    Push the input character from the register.
               !   Skip the 'i' at the beginning of the line, so that the next
                   iteration starts with 'o', printing the last character.

Once we hit EOF, the instruction pointer ends up on the second line and we'll simply execute o in a loop, printing all the ), until the stack is empty and the program errors out.

\$\endgroup\$
12
\$\begingroup\$

C#, 32 bytes

F=s=>*s+++(0<*s?$"({F(s)})":"");

This lambda must be a static method, would I need to count any extra bytes for that requirement? Normally I wouldn't use a lambda for recursion in C#, but then I think it would be shorter not to use recursion.

/*unsafe delegate string Function(char* s);*/ // Lambda signature
/*static unsafe Function*/ F = s =>
    *s++                               // Take first char and increment pointer to next one
    + (0 < *s                          // Check if any chars left
        ? $"({F(s)})"                  // If so concat surrounding parens around recursion
        : ""                           // Otherwise done
    )
;
\$\endgroup\$
  • \$\begingroup\$ the definition should run as declared and counted \$\endgroup\$ – cat Oct 22 '16 at 11:25
9
\$\begingroup\$

J, 13 bytes

(,'(',,&')')/

J executes from right-to-left so using the insert adverb /, a verb can be used to reduce the letters of the input string.

Usage

   f =: (,'(',,&')')/
   f 'Nest a string'
N(e(s(t( (a( (s(t(r(i(n(g))))))))))))
   f 'foobar'
f(o(o(b(a(r)))))
   f '1234567890'
1(2(3(4(5(6(7(8(9(0)))))))))
   f 'code-golf'
c(o(d(e(-(g(o(l(f))))))))

You can observe the partial outputs between each reduction.

   |. f\. 'Hello'
o            
l(o)         
l(l(o))      
e(l(l(o)))   
H(e(l(l(o))))

Explanation

(,'(',,&')')/  Input: string S
(          )/  Insert this verb between each char and execute (right-to-left)
      ,&')'      Append a ')' to the right char
  '(',           Prepend a '(' to that
 ,               Append to the left char
\$\endgroup\$
9
\$\begingroup\$

R, 61 bytes

cat(gsub("(?<=.)(?=.)","(",x,F,T),rep(")",nchar(x)-1),sep="")

Regex finds and replaces spaces between characters with "(". Then cat and rep add ")" n-1 times at the end.

\$\endgroup\$
  • \$\begingroup\$ Can actually subtract 1 byte here by eliminating the F, like so, this is because each entry already has a default setting, so leaving an empty character between commas will cause the ignore.case option to use its default. But you likely knew that... Job well done! \$\endgroup\$ – Sumner18 Aug 28 '18 at 13:29
8
\$\begingroup\$

Acc!!, 129 bytes

Not bad for a fairly verbose Turing tarpit...

N
Count i while _%128-9 {
Count x while _/128%2 {
Write 40
_+128
}
Write _%128
_+128-_%128+N
}
Count j while _/256-j {
Write 41
}

(Yes, all that whitespace is mandatory.)

Note: because of the input limitations of Acc!!, it is impossible to read an arbitrary string of characters without some ending delimiter. Therefore, this program expects input (on stdin) as a string followed by a tab character.

Acc!!?

It's a language I created that only appears to be unusable. The only data type is integers, the only control flow construct is the Count x while y loop, and the only way to store data is a single accumulator _. Input and output are done one character at a time, using the special value N and the Write statement. Despite these limitations, I'm quite sure that Acc!! is Turing-complete.

Explanation

The basic strategy in Acc!! programming is to use mod % and integer division / to conceptually partition the accumulator, allowing it to store multiple values at once. In this program, we use three such sections: the lowest-order seven bits (_%128) store an ASCII code from input; the next bit (_/128%2) stores a flag value; and the remaining bits (_/256) count the number of close-parens we will need.

Input in Acc!! comes from the special value N, which reads a single character and evaluates to its ASCII code. Any statement that consists solely of an expression assigns the result of that expression to the accumulator. So we start by storing the first character's code in the accumulator.

_%128 will store the most recently read character. So the first loop runs while _%128-9 is nonzero--that is, until the current character is a tab.

Inside the loop, we want to print ( unless we're on the first iteration. Since Acc!! has no if statement, we have to use loops for conditionals. We use the 128's bit of the accumulator, _/128%2, as a flag value. On the first pass, the only thing in the accumulator is an ASCII value < 128, so the flag is 0 and the loop is skipped. On every subsequent pass, we will make sure the flag is 1.

Inside the Count x loop (whenever the flag is 1), we write an open paren (ASCII 40) and add 128 to the accumulator, thereby setting the flag to 0 and exiting the loop. This also happens to increment the value of _/256, which we will use as our tally of close-parens to be output.

Regardless of the flag's value, we write the most recent input char, which is simply _%128.

The next assignment (_+128-_%128+N) does two things. First, by adding 128, it sets the flag for the next time through the loop. Second, it zeros out the _%128 slot, reads another character, and stores it there. Then we loop.

When the Count i loop exits, we have just read a tab character, and the accumulator value breaks down like this:

  • _%128: 9 (the tab character)
  • _/128%2: 1 (the flag)
  • _/256: number of characters read, minus 1

(The minus 1 is because we only add 128 to the accumulator once during the first pass through the main loop.) All that we need now are the close-parens. Count j while _/256-j loops _/256 times, writing a close-paren (ASCII 41) each time. Voila!

\$\endgroup\$
8
\$\begingroup\$

Java 7,81 79 bytes

Saved 1 byte.Thanks to kevin.

String f(char[]a,String b,int l){return l<a.length?f(a,b+'('+a[l],++l)+')':b;}
\$\endgroup\$
  • \$\begingroup\$ Nice recursive approach. Shorter than the for-loop I was about to post. +1 Two things you can golf though: l!=a.length -> l<a.length and b=b+'('+a[l],++l)+')' -> b+="("+a[l],++l)+")" (-2 bytes) \$\endgroup\$ – Kevin Cruijssen Oct 19 '16 at 7:58
  • \$\begingroup\$ @KevinCruijssen b+="("+a[l],++l)+")" gives you 144141148))),and BTW b+"("+a[l],++l)+")" is correct. and this was very silly mistake of mine(!=). \$\endgroup\$ – Numberknot Oct 19 '16 at 14:22
  • \$\begingroup\$ No, b+='('+a[l],++l)+')' gives 144141148, but b+="("+a[l],++l)+")" doesn't. The parentheses are surrounded by String-quotes instead of char-quotes. \$\endgroup\$ – Kevin Cruijssen Oct 19 '16 at 19:06
  • \$\begingroup\$ I post my version (82 bytes in Java 7) using only the input String as parameter. Verbose but not that bad ;) If you find something to change : codegolf.stackexchange.com/a/96745/59739 \$\endgroup\$ – AxelH Oct 20 '16 at 14:10
7
\$\begingroup\$

PowerShell v2+, 46 bytes

param([char[]]$a)($a-join'(')+')'*($a.count-1)

Takes input string, char-array's it, -joins the array together with open parens (, then concatenates on the appropriate number of closed parens ).

\$\endgroup\$
7
\$\begingroup\$

APL, 19 bytes

{∊('(',¨⍵),')'⍴⍨⍴⍵}

Explanation:

{
  ('(',¨⍵)          ⍝ join a ( to each character in ⍵          
          ,')'⍴⍨⍴⍵  ⍝ for each character in ⍵, add an ) to the end
 ∊                  ⍝ flatten the list 
                   }

Alternative solution, also 19 bytes:

{⊃{∊'('⍺⍵')'}/⍵,⊂⍬}

Explanation:

{              
              ⍵,⊂⍬  ⍝ add an empty list behind ⍵ (as a base case)
  {         }/      ⍝ reduce with this function:
    '('⍺⍵')'        ⍝   put braces around input
   ∊                ⍝   flatten the list
 ⊃                  ⍝ take first item from resulting list
                   }
\$\endgroup\$
  • 6
    \$\begingroup\$ Where do you buy the keyboards for such a language!!! \$\endgroup\$ – Ronan Dejhero Oct 19 '16 at 13:13
  • \$\begingroup\$ @RonanDejhero Perhaps just remapping keys using cltr, shift, alt, capslock, numlock etc. \$\endgroup\$ – Ariana Oct 27 '16 at 5:04
7
\$\begingroup\$

MATL, 16 bytes

t~40+v3L)7MQ3L)h

Try it online!

Explanation

t     % Implicit input. Duplicate
      % STACK: 'foobar', 'foobar'
~     % Negate. Transforms into an array of zeros
      % STACK: 'foobar', [0 0 0 0 0 0]
40+   % Add 40, element-wise. Gives array containing 40 repeated
      % STACK: 'foobar', [40 40 40 40 40 40]
v     % Concatenate vertically. Gives a two-row char array, with 40 cast into '('
      % STACK: ['foobar'; '((((((']
3L)   % Remove last element. Converts to row vector
      % STACK: 'f(o(o(b(a(r'
7M    % Push array containing 40 again
      % STACK: 'f(o(o(b(a(r', [40 40 40 40 40 40]
Q     % Add 1, element-wise 
      % STACK: 'f(o(o(b(a(r', [41 41 41 41 41 41]
h     % Concatenate horizontally, with 41 cast into ')'
      % STACK: 'f(o(o(b(a(r)))))'
      % Implicit display
\$\endgroup\$
7
\$\begingroup\$

Perl, 25 bytes

Thanks to @Ton Hospel for golfing out 4 bytes.

24 bytes of code + -F.

$"="(";say"@F".")"x$#F

Needs -F and -E flags :

echo -n "I love lisp" | perl -F -E '$"="(";say"@F".")"x$#F'

Note that if you try this on an old version of perl, you might need to add -a flag.


Another interesting way (a little bit longer though : 28 bytes) :
Thanks to Ton Hospel once again for helping me getting this one right.

#!/usr/bin/perl -p
s/.(?=.)/s%\Q$'%($&)%/reg

(To use it, put the code inside a file and call it with echo -n "Hello" | perl nest.pl)

\$\endgroup\$
  • \$\begingroup\$ You don't need the "" after the -F. You also don't need the -l if you demand the input string is entered without final newline: echo -n Hello | program \$\endgroup\$ – Ton Hospel Oct 19 '16 at 4:59
  • \$\begingroup\$ @TonHospel Right, I forgot (or didn't know, not sure) about that behavious of -F, thanks. (I was wondering how to get the input without the final newline, thanks for that too) \$\endgroup\$ – Dada Oct 19 '16 at 5:23
  • \$\begingroup\$ perl -F -E '$"="(";say"@F".")"x$#F' \$\endgroup\$ – Ton Hospel Oct 19 '16 at 7:27
  • \$\begingroup\$ You can get your other idea working with something like s/.(?=.)/s%$'%($&)%/reg, but it of course doesn't support strings containing regex metacharacters \$\endgroup\$ – Ton Hospel Oct 19 '16 at 10:31
  • \$\begingroup\$ @TonHospel Thanks a lot for all of that! (About the second one, I added \Q to support regex metacharacters) :-) \$\endgroup\$ – Dada Oct 19 '16 at 15:11
6
\$\begingroup\$

Ruby, 27 bytes

->s{s.chars*?(+?)*~-s.size}

Explanation

->s{                       # Declare anonymous lambda taking argument s
    s.chars                # Get the array of chars representing s
           *?(             # Join the elements back into a string using "("s as separators
              +?)*~-s.size # Append (s.size - 1) ")"s to the end
\$\endgroup\$
6
\$\begingroup\$

Perl, 24 23 bytes

Includes +1 for -p

Give string on STDIN without newline (or add a -l option to the program)

echo -n Hello | nest.pl

nest.pl:

#!/usr/bin/perl -p
$\=")"x s/.(?=.)/$&(/g
\$\endgroup\$
6
\$\begingroup\$

GNU sed, 37 35 31 bytes (30 +1 for -r argument)

Pure linux sed solution

:;s/([^(])([^()].*)$/\1(\2)/;t
  1. Naming the subsitution :; then calling it recursively with t
  2. Making 2 regex groups:
    • First group is first char of two consecutive characters which are not parenthesis
    • Second group is the second consecutive character and the rest of the string until end of line
  3. Add parenthesis around the second group \1 ( \2 )

Edit: Thanks to @manatwork for helping removing 4 characters!

Online tester

\$\endgroup\$
  • 2
    \$\begingroup\$ Using only 2 groups seems to be enough. Capture the 2nd and 3rd together. \$\endgroup\$ – manatwork Oct 19 '16 at 23:06
  • \$\begingroup\$ Oh, and sorry, but command line options necessary to change the interpreter's default behavior for your code to work, have to be included in the size count. The barely necessary -e to pass the code to the interpreter is for free. (Ok, sed is happy without it too.) So for sed -re '…' you count +1. \$\endgroup\$ – manatwork Oct 20 '16 at 8:04
  • 1
    \$\begingroup\$ Blank labels are a GNU sed feature/bug, so maybe the title should be GNU sed. \$\endgroup\$ – Riley Oct 20 '16 at 13:43
6
\$\begingroup\$

Jellyfish, 19 18 bytes

P
,+>`
_  {I
/'␁'(

The character is the unprintable control character with byte value 0x1. Try it online!

Explanation

This is a pretty complex Jellyfish program, since many values are used in multiple places.

  • I is raw input, read from STDIN as a string.
  • '( is the character literal (.
  • The { (left identity) takes '( and I as inputs, and returns '(. The return value is never actually used.
  • ` is thread. It modifies { to return the character ( for each character of I, resulting in a string of (s with the same length as I.
  • > is tail; it takes the string of (s as input and chops off the first character.
  • + takes as arguments the string of (s and the unprintable byte, and adds the byte value (1) to each character. This gives an equal-length string of )s. Using the character guarantees that the return value is a string, and not a list of integers.
  • On the lower left corner, / takes the unprintable byte, and returns a function that takes two arguments, and joins the second argument with the first one once (since the byte value is 1).
  • _ takes this function, grabs the arguments of the lower { (which were '( and I), and calls the funtion with them. This inserts the character ( between every pair of characters in I.
  • , concatenates this string with the string of )s, and P prints the result.
\$\endgroup\$
5
\$\begingroup\$

05AB1E, 22 21 19 18 bytes

¤Ug<©FN¹è'(}X®')×J

Try it online!

Explanation:

¤Ug<©FN¹è'(}X®')×J #implicit input, call it A                                 
¤U                 #push the last letter of A, save it to X
  g<©              #push the length of A, subtract 1, call it B and save it to register_c
     F     }       #repeat B times
      N¹è          #push the Nth char of A
         '(        #push '('
            X      #push X
             ®')×  #push ')' repeated B times
                 J #join together
                   #implicit print
\$\endgroup\$
5
\$\begingroup\$

PHP, 63 Bytes

<?=str_pad(join("(",$s=str_split($argv[1])),count($s)*3-2,")‌​");

Previous version 64 Bytes

<?=join("(",$s=str_split($argv[1])).str_pad("",count($s)-1,")");
\$\endgroup\$
  • 1
    \$\begingroup\$ You can save two bytes by using <?= instead of echo and another one if you set $s to the result of the str_split call instead of $argv[1], and then use count($s) instead of strlen($s) \$\endgroup\$ – Alex Howansky Oct 18 '16 at 20:00
  • 2
    \$\begingroup\$ 63 bytes: <?=str_pad(join("(",$s=str_split($argv[1])),count($s)*3-2,")");- wordwrap would beat the split/join combination, but unfortunately fails if the input contains whitespace. \$\endgroup\$ – Titus Oct 19 '16 at 13:15
  • \$\begingroup\$ @Titus nice alternative Thank You \$\endgroup\$ – Jörg Hülsermann Oct 19 '16 at 14:08
4
\$\begingroup\$

Vim, 17 bytes

$qqha(<Esc>A)<Esc>%h@qq@q

Goes from end to beginning, because otherwise you trip over the )s you've already written. Uses ha instead of i to fail when it reaches the beginning.

Usually, you wouldn't do two separate inserts like this; you'd do something like C()<Esc>P to save a stroke. But the positioning doesn't work as well this time.

\$\endgroup\$
  • \$\begingroup\$ You can use the <End> key in insert mode instead of leaving insert mode and doing A \$\endgroup\$ – BlackCap Nov 30 '16 at 1:09
  • \$\begingroup\$ @BlackCap That's not a byte. I'd need to count strokes instead of bytes. (And Vimgolf is a better game when you ban cursor keys, though the difference here is trivial.) \$\endgroup\$ – udioica Nov 30 '16 at 1:26
4
\$\begingroup\$

Brain-Flak 103 97 Bytes

Includes +3 for -c

{({}<><(((((()()){}()){}){}){})>)<>}<>({}<([][()]){({}[()()]<(({})()<>)<>>)}{}>){({}<>)<>}<>{}

Try it Online!


Explanation:

#reverse the stack and put a 40 between every number
{({}<><(((((()()){}()){}){}){})>)<>}<>
{                                  }   #repeat this until the stack is empty
 ({}                            )      #pop the top and push it after
    <>                                 #switching stacks and
      <(((((()()){}()){}){}){})>       #pushing a 40 (evaluated as 0) 
                                 <>    #switch back to the first stack
                                    <> #switch to the stack that everything is on now    

#put as many )s on the other stack as needed
({}                                      ) #pop the top letter and put it  back
                                           #after doing the following
                                           #This leaves ( on the top
   <                                    >  #evalute this part as 0
    ([][()])                               #push the height of the stack minus one
            {                        }    #repeat until the "height" is 0
             ({}[()()]              )     #pop the "height" and push is minus two
                      <            >      #evaluate to 0
                       (        )         #push:
                        ({})              #the top of the stack (putting it back on)
                            ()            #plus one onto
                              <>          #the other stack
                                 <>       #switch back to the other stack

                                      {}  #pop what was the height of the stack

#move the string of letters and (s back, reversing the order again
{        }     # repeat until all elements are moved
 (    )        # push:
  {}           # the top of the stack after
    <>         # switching stacks
       <>      # switch back to the other stack
          <>   # switch to the stack with the final string
            {} #pop the extra (
\$\endgroup\$
  • \$\begingroup\$ Beat me to it. +1 \$\endgroup\$ – DJMcMayhem Oct 18 '16 at 20:35
  • \$\begingroup\$ Hmm. I thought that reusing the 40 to avoid pushing a large integer again would save you a lot of bytes, but the best I can come up with is {({}<><(((((()()){}()){}){}){})>)<>}<>({}<(({})<>())><>)([]){({}[()()]<(<>({})<>)>)}{}{}{({}<>)<>}<>{} which is two bytes longer... \$\endgroup\$ – DJMcMayhem Oct 18 '16 at 20:44
  • \$\begingroup\$ Thanks for giving me the idea to reuse the 40. I got it down to 95+3. Why is it 3 bytes for -a in Brain-Flak anyway? \$\endgroup\$ – Riley Oct 18 '16 at 21:34
  • \$\begingroup\$ Oh, nice work! The +3 bytes is standard for special command line flags. Which is unfortunate, but something I can put up with. I've actually been thinking of ways to shorten this, but I'm not exactly sure how yet. \$\endgroup\$ – DJMcMayhem Oct 18 '16 at 21:36
  • \$\begingroup\$ Isn't it normally 2 bytes? one for the - and one for the flag? You could have a flag for normal execution like Perl does with -e. That way it would only be 1 extra byte. \$\endgroup\$ – Riley Oct 18 '16 at 21:38
3
\$\begingroup\$

Convex, 10 bytes

_'(*\,(')*

Try it online!

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

><>, 37 bytes

i:0(?\'('
$,2l~/~
/?(2:<-1$')'
>~ror:

Row by row

  1. Pushes each char from input with an opening parenthesis after each
  2. Removes EOF and the last opening parenthesis and pushes the stack length
  3. Uses a comparison with half the stack length to push the closing parenthesis
  4. Prints the content of the stack

Try it online!

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

Perl, 36 bytes (34 + 2 for -lpflag)

Thanks to Dada for pointing out a bug and saving one byte (in total)!

Splits the string into an array, then joins it with the (delimiter. We directly add the closing )since lengthreturns the length of the string before the join.

$_=(join"(",split//).")"x(y///c-1)

Try it here!

\$\endgroup\$
  • \$\begingroup\$ Sure you don't need -l flag? I doesn't seem to work when I try it... Or maybe I missed something? \$\endgroup\$ – Dada Oct 18 '16 at 20:49
  • \$\begingroup\$ Also, you can write y///c-1 instead of -1+length to save 2 bytes. \$\endgroup\$ – Dada Oct 18 '16 at 20:51
  • \$\begingroup\$ @Dada indeed, -l is needed when you run this with the terminal. I'm always doing these things on Ideone and it's not needed there... Editing! (and thanks for the tip!) \$\endgroup\$ – Paul Picard Oct 18 '16 at 20:54
  • \$\begingroup\$ You could also do $_=(join"(",@a=split//).")"x(@a-1) which is a bit more verbose and the same number of bytes as the y///c-1. Or well, depends on the definition of verbose. \$\endgroup\$ – simbabque Oct 18 '16 at 21:25
  • 2
    \$\begingroup\$ You can again drop the -l option by demanding that the input string is entered without final newline, echo -n Hello | program \$\endgroup\$ – Ton Hospel Oct 19 '16 at 4:55

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.