N(e(s(t))) a string

85

8

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!

James

Posted 2016-10-18T18:34:27.623

Reputation: 54 537

21

Ahem: Is this message anything to do with the challenge? :-)

– wizzwizz4 – 2016-10-18T18:46:45.337

13T​I​L 4​2​ ​= 8 – ETHproductions – 2016-10-18T21:48:33.523

What is maximum length for the input string? Incase of recursive methods – Ferrybig – 2016-10-23T20:30:43.780

Is the output the execution of said function, or merely the string itself? – nl-x – 2016-10-24T12:24:53.900

@nl-x The string itself. – James – 2016-10-24T15:21:58.767

Can you take input as an array of characters or must it be a string? – kamoroso94 – 2017-09-01T08:49:09.787

1@kamoroso94 You may take the input and the output in any reasonable format. A list of characters seems perfectly reasonable to me. – James – 2017-09-01T15:29:58.547

4So that's what Lisp code looks like – caird coinheringaahing – 2017-12-17T18:35:23.857

can the last character be "function nested" - e.g. can would hello -> h(e(l(l(o())))) be acceptable? – Benji – 2020-02-27T20:13:50.843

Answers

64

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.

Post Rock Garf Hunter

Posted 2016-10-18T18:34:27.623

Reputation: 55 382

13That ~- trick is cool, I will need to remember that. – Skyler – 2016-10-18T19:25:39.580

how does the ~-trick work ? – ShadowFlame – 2016-10-19T14:08:24.973

1

@ShadowFlame - makes the number negative and ~ bit flips it. You can read a bit more about it on the tips page.

– Post Rock Garf Hunter – 2016-10-19T14:11:31.673

1@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). – Mad Physicist – 2016-10-21T17:40:34.447

Hail Python! Clever shit with the bit flips there. – Transcendental – 2016-10-24T08:49:33.767

2@MadPhysicist With Python, it works always, because ~ is defined as -x-1 – Mega Man – 2018-05-28T12:51:37.593

45

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.

Martin Rosenau

Posted 2016-10-18T18:34:27.623

Reputation: 1 921

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. – cat – 2016-10-20T23:19:19.003

6DOS 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. – Martin Rosenau – 2016-10-21T05:59:31.230

32

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!

Arnauld

Posted 2016-10-18T18:34:27.623

Reputation: 111 334

1Nice trick with 1/s. – ETHproductions – 2016-10-18T19:38:22.400

Super nice trick with ([c,...s]) you should write a tip – edc65 – 2016-10-18T21:27:51.697

@edc65 Just for sake of clarity, this one was suggested by ETHproductions. – Arnauld – 2016-10-18T21:40:36.957

o well, someone has to write a tip anyway – edc65 – 2016-10-18T21:42:51.467

@edc65 On it... – ETHproductions – 2016-10-18T21:44:10.477

@edc65 its called "destructuring assignment" check https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

– jmingov – 2016-10-18T22:40:28.513

1@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) – edc65 – 2016-10-19T07:16:02.643

... although you have to be careful, since it turns into an array. – Neil – 2016-10-19T08:05:31.967

@edc65 For reference, the tip can be found here. Feel free to suggest a way to improve it.

– ETHproductions – 2016-10-20T01:20:19.007

@ETHproductions Upvoted already - I was tracking you. – edc65 – 2016-10-20T07:01:51.027

28

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
]

Alex Howansky

Posted 2016-10-18T18:34:27.623

Reputation: 1 183

1There is usually a shorter way to get a constant than the obvious 2-factor multiplication. – Martin Ender – 2016-10-18T20:16:36.850

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. – Alex Howansky – 2016-10-18T20:58:29.263

you got one pair of brackets to much!? – Vloxxity – 2016-10-21T14:04:49.330

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. – user59468 – 2016-10-21T22:34:13.023

Ah bugger, you're right. I didn't read carefully enough and made the last letter a function call like the others. – Alex Howansky – 2016-10-23T17:54:24.250

24

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

acrolith

Posted 2016-10-18T18:34:27.623

Reputation: 3 728

18

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.

user59468

Posted 2016-10-18T18:34:27.623

Reputation: 261

+++++[->++++++++<],.,[>.>+<<.,]>+>[-<.>] is slightly shorter. – Tesseract – 2019-10-18T04:48:18.500

18

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

nimi

Posted 2016-10-18T18:34:27.623

Reputation: 34 639

2If 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". – porglezomp – 2016-10-19T01:02:37.163

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.

– Dada – 2016-10-24T13:13:33.733

@Dada: that won't work, because it would put an additional () behind the last letter, e.g. f "abc" -> "a(b(c()))". – nimi – 2016-10-24T15:52:58.863

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(\_->')'). – Jon Purdy – 2016-10-27T03:48:56.680

@JonPurdy: we don't have to handle empty input. intersperse requires import Data.List for another 17 bytes. – nimi – 2016-10-27T09:15:57.367

@nimi: I missed that part—my bad. And apparently I need to have fewer default imports in my .ghci when golfing. Something resembling intersperse could be made from e.g. >>=(:"(") but it might not be worthwhile. – Jon Purdy – 2016-10-27T20:57:53.137

16

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

Jonathan Allan

Posted 2016-10-18T18:34:27.623

Reputation: 67 804

3Btw, ³ actually causes Jelly to print the current return value, so you never have two lists of chars. – Dennis – 2016-10-18T21:09:52.823

13

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.

Martin Ender

Posted 2016-10-18T18:34:27.623

Reputation: 184 808

Dangit. So fast... – mbomb007 – 2016-10-18T18:43:34.587

@mbomb007 ...and far from optimal. ;) – Martin Ender – 2016-10-18T19:05:35.133

13

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

Martin Ender

Posted 2016-10-18T18:34:27.623

Reputation: 184 808

12

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

miles

Posted 2016-10-18T18:34:27.623

Reputation: 15 654

12

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

milk

Posted 2016-10-18T18:34:27.623

Reputation: 3 043

the definition should run as declared and counted – cat – 2016-10-22T11:25:54.000

9

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

Numberknot

Posted 2016-10-18T18:34:27.623

Reputation: 885

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) – Kevin Cruijssen – 2016-10-19T07:58:21.680

@KevinCruijssen b+="("+a[l],++l)+")" gives you 144141148))),and BTW b+"("+a[l],++l)+")" is correct. and this was very silly mistake of mine(!=). – Numberknot – 2016-10-19T14:22:31.807

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. – Kevin Cruijssen – 2016-10-19T19:06:29.033

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 : http://codegolf.stackexchange.com/a/96745/59739

– AxelH – 2016-10-20T14:10:21.613

9

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.

jmartindill

Posted 2016-10-18T18:34:27.623

Reputation: 191

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!

– Sumner18 – 2018-08-28T13:29:50.140

8

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

AdmBorkBork

Posted 2016-10-18T18:34:27.623

Reputation: 41 581

8

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
                   }

marinus

Posted 2016-10-18T18:34:27.623

Reputation: 30 224

6Where do you buy the keyboards for such a language!!! – Ronan Dejhero – 2016-10-19T13:13:15.913

@RonanDejhero Perhaps just remapping keys using cltr, shift, alt, capslock, numlock etc. – Ariana – 2016-10-27T05:04:50.600

It can be shortened using trains, I guess: (∊'('∘,¨,')'⍴⍨⍴) But doesn't this add an extra couple of brackets? – Popov – 2019-12-24T12:02:30.120

8

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

Luis Mendo

Posted 2016-10-18T18:34:27.623

Reputation: 87 464

8

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!

DLosc

Posted 2016-10-18T18:34:27.623

Reputation: 21 213

7

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)

Dada

Posted 2016-10-18T18:34:27.623

Reputation: 8 279

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 – Ton Hospel – 2016-10-19T04:59:16.917

@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) – Dada – 2016-10-19T05:23:51.827

perl -F -E '$"="(";say"@F".")"x$#F' – Ton Hospel – 2016-10-19T07:27:55.553

You can get your other idea working with something like s/.(?=.)/s%$'%($&)%/reg, but it of course doesn't support strings containing regex metacharacters – Ton Hospel – 2016-10-19T10:31:52.517

@TonHospel Thanks a lot for all of that! (About the second one, I added \Q to support regex metacharacters) :-) – Dada – 2016-10-19T15:11:02.463

7

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

Ton Hospel

Posted 2016-10-18T18:34:27.623

Reputation: 14 114

6

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,")");

Jörg Hülsermann

Posted 2016-10-18T18:34:27.623

Reputation: 13 026

1You 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) – Alex Howansky – 2016-10-18T20:00:36.547

263 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. – Titus – 2016-10-19T13:15:06.453

1@Titus nice alternative Thank You – Jörg Hülsermann – 2016-10-19T14:08:51.440

6

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

m-chrzan

Posted 2016-10-18T18:34:27.623

Reputation: 1 390

6

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.

Zgarb

Posted 2016-10-18T18:34:27.623

Reputation: 39 083

6

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

Doomsday

Posted 2016-10-18T18:34:27.623

Reputation: 201

2Using only 2 groups seems to be enough. Capture the 2nd and 3rd together. – manatwork – 2016-10-19T23:06:16.143

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. – manatwork – 2016-10-20T08:04:57.150

1Blank labels are a GNU sed feature/bug, so maybe the title should be GNU sed. – Riley – 2016-10-20T13:43:57.460

5

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

Luke

Posted 2016-10-18T18:34:27.623

Reputation: 81

5

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.

udioica

Posted 2016-10-18T18:34:27.623

Reputation: 2 381

You can use the <End> key in insert mode instead of leaving insert mode and doing A – BlackCap – 2016-11-30T01:09:42.653

@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.) – udioica – 2016-11-30T01:26:33.090

4

Dyalog APL, 14 bytes

⊃{⍺,1⌽')(',⍵}/

this is an atop of and { }/

(get first element) will be applied after { }/ (reduction of a lambda)

⍺,1⌽')(',⍵ - the left argument () concatenated with (,) the rotation by one element to the left (1⌽) of the string ')(' concatenated with (,) the right argument ()

reduction in APL folds from right to left, as required here

ngn

Posted 2016-10-18T18:34:27.623

Reputation: 11 449

4

Factor, 81 bytes

[ [ >array [ 1string ] map "("join ] [ length 1 - [ 40 ] replicate >string ] bi ]       

cat

Posted 2016-10-18T18:34:27.623

Reputation: 4 989

4

Convex, 10 bytes

_'(*\,(')*

Try it online!

GamrCorps

Posted 2016-10-18T18:34:27.623

Reputation: 7 058

4

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 (

Riley

Posted 2016-10-18T18:34:27.623

Reputation: 11 345

Beat me to it. +1 – James – 2016-10-18T20:35:36.857

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... – James – 2016-10-18T20:44:56.647

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? – Riley – 2016-10-18T21:34:16.457

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.

– James – 2016-10-18T21:36:29.563

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. – Riley – 2016-10-18T21:38:23.490

Well, there's also one for the space (which isn't necessary for perl). But the -e flag is a good idea, although I don't know exactly how it would work. Do you want to talk about it more in the brain-flak room?

– James – 2016-10-18T21:41:16.253

4

><>, 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!

Emigna

Posted 2016-10-18T18:34:27.623

Reputation: 50 798

3

Stax, 8 6 bytes

-2 thanks to @recursive!

çΔ \Γ]

Run and debug it at staxlang.xyz!

Unpacked (7 bytes) and explanation:

Mrks:{+
M          Transpose array. This turns a string into an array of length-1 strings.
 r         Reverse string.
  k        Fold array using the rest of the program as a block:
   s         Swap. This puts the accumulator on top of the current element.
    :{       Wrap in parentheses.
      +      Concatenate.
           Implicit print at end of program!

Khuldraeseth na'Barya

Posted 2016-10-18T18:34:27.623

Reputation: 2 608

If you transpose the input string, you can get rid of the stringifications, and pack down to 6. Mrks:{+ – recursive – 2018-05-24T17:03:27.260

@recursive Ah. That's what I was looking for. Definitely beats {]m for the same functionality! – Khuldraeseth na'Barya – 2018-05-25T19:57:07.283

3

05AB1E, 11 10 bytes

-1 byte thanks to @Kevin Cruijssen

S'(ý?¨v')?

Try it online!

Explanation

             #implicit input
S            #cast input to list
   ý         #list join
 '(          #( character
    ?        #print list without a newline
      v      #foreach item in
     ¨       #first input[0:-1]
       ')?   #print ) without a newline

mabel

Posted 2016-10-18T18:34:27.623

Reputation: 1 489

Welcome to the site! – Post Rock Garf Hunter – 2019-12-25T00:24:29.753

thank you! @WheatWizard – mabel – 2019-12-25T01:23:59.977

1You can remove the ¹ to save a byte. It will use the input implicitly again, since the stack is empty. :) – Kevin Cruijssen – 2020-01-03T09:12:15.557

3

Perl 5, 44 33 bytes (31 + 1 for -l + 1 for -p)

saved 11 bytes thanks to Dada

s/([\w ])([\w ]+)/$1($2)/&&redo

Can be run from the command line with the -p and -e options.

$ perl -ple 's/([\w ])([\w ]+)/$1($2)/&&redo' <<< 'Hello'

Output:

H(e(l(l(o))))

simbabque

Posted 2016-10-18T18:34:27.623

Reputation: 487

1You can use -l instead of chomp to save 5 bytes. Also, since -p surround the code with a while, you can do s/../../&&redo instead of 0while s/../../. As it happens, this regex is shorter : s/([\w ])([\w ]+)/$1($2)/. – Dada – 2016-10-18T20:38:20.463

Another thing : usually, when you really need to chomp, you can chop instead to save one byte ;) – Dada – 2016-10-18T20:49:52.323

@Dada thanks, didn't think about the redo and got caught up building a complicated regex. I need to understand that golf is not obfuscation. ;) – simbabque – 2016-10-18T21:06:24.350

1You code wasn't that bad! It just takes time and practice! And even after that, Ton Hospel will always find a shorter way than everybody else! ;-) – Dada – 2016-10-18T21:16:11.057

thanks @dada. I borrowed the python code and made it shorter in Perl in another answer – simbabque – 2016-10-18T21:21:35.983

You don't need the -l if you demand the input string is entered without final newline: echo -n Hello | program. – Ton Hospel – 2016-10-19T05:00:42.820

1You are supposed to support all printable ASCII so you need [^()] instead of [\w ]. The first one in fact only needs [^(] – Ton Hospel – 2016-10-19T05:09:08.397

3

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!

Paul Picard

Posted 2016-10-18T18:34:27.623

Reputation: 863

Sure you don't need -l flag? I doesn't seem to work when I try it... Or maybe I missed something? – Dada – 2016-10-18T20:49:05.630

Also, you can write y///c-1 instead of -1+length to save 2 bytes. – Dada – 2016-10-18T20:51:06.403

@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!) – Paul Picard – 2016-10-18T20:54:09.457

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. – simbabque – 2016-10-18T21:25:57.280

2You can again drop the -l option by demanding that the input string is entered without final newline, echo -n Hello | program – Ton Hospel – 2016-10-19T04:55:14.690

3

Brain-Flak, 118 84 + 1 = 85 bytes

Try it online

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

This requires the -fc flag to run giving it an extra byte. -f flag is standard for passing input.


Explanation

([[]]<        #Store a copy of the stack height before hand in the scope
 {            #While there is something on the stack...
  ({}<>)      #Move something over and...
  ((((()()()()()){}){}){}) #Put a paren on top
  <>          #Swap back
}
>())          #Put the 1-stack height down
{             #While that is not zero
 ({}()<       #Add one and
  (<>({})<>())#Silently move a copy of the top of the other stack over (close paren)
 >)
}{}
<>{}          #Remove extra open paren
{({}<>)<>}<>  #Combine the two stacks

Post Rock Garf Hunter

Posted 2016-10-18T18:34:27.623

Reputation: 55 382

3

Brachylog, 35 28 25 bytes

l-L,")":LjkC,?:"("zckc:Cc

Try it online!

Explanation

l-L,          # L is length of input - 1
")":LjkC,     # C is ")" repeated L-1 times
              # output is
?:"("z        # input zipped with "("
      ckc     # flattened to a string with the last element removed
         :Cc  # concatenated with C

Emigna

Posted 2016-10-18T18:34:27.623

Reputation: 50 798

3

Java 82 81

Thanks to Olivier Grégoire for the correction leading to 1byte less.

Solution

I forced myself in using a String a not a char[] so this is a bit more verbose :/

String n(String s){return s.length()>1?s.charAt(0)+"("+n(s.substring(1))+")":s;}

A simple recursive function.

Test

public static void main(String[] a){
    System.out.println(n("test"));
    System.out.println(n("Hello world!"));
}

t(e(s(t)))

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

AxelH

Posted 2016-10-18T18:34:27.623

Reputation: 151

1For Java 7, did you notice that the last character is duplicated? For Java 8, it won't compile and work because you have to define a recursive function like this: n=s->...n.apply(...) instead of s->...n(...), also there are some other issues which make your answer don't work. – Olivier Grégoire – 2016-10-21T09:30:43.613

1Thanks, indeed I missed that ... I just made the correction and gain a byte, thanks :) . I removed the Java 8 part since I can't test it here and don't have enought experience to do it blindly ;) – AxelH – 2016-10-21T09:45:39.817

Well, actually a recursive function can't work in Java 8. You always get a "self-reference in intializer" error. – Olivier Grégoire – 2016-10-21T09:55:01.090

@OlivierGrégoire Never used Lambda for complex code, mainly for small validation process. But thanks for the info, I will dig into this. – AxelH – 2016-10-21T09:56:28.887

2

QBIC, 64 bytes

Way too large. Posted as an incentive to get my butt moving again on the QBIC project.

;_LA|[a-1|Z=Z+$mid$|(A,b,1)+@(|]Z=Z+$right$|(A,1)[a-1|Z=Z+@)|]?Z

All those $mid$| and $right$|s should be turned into QBIC commands, but to do that I first need to solve a problem with nesting function calls...


EDIT: Got my butt moving. Now in 48 bytes:

_L;|[a-1|Z=Z+_sA,b,1|+@(`]Z=Z+_sA,-1|[a-1|Z=Z+@)

steenbergh

Posted 2016-10-18T18:34:27.623

Reputation: 7 772

Huh. QBIC looks interesting. Is there a github project I could follow? Or a README describing what it is? – James – 2016-11-28T18:11:18.503

@DrMcMoylex I swear, the day I figure out how Github works ... The project lives in a shared folder on a Google Drive, link in the header. Some info o getting started here and here.

– steenbergh – 2016-11-28T18:23:11.517

Why is QBIC not on TIO? – MD XF – 2017-11-10T18:36:15.527

@MDXF Well, QBIC code is converted into QBasic code, which is run in Dosbox. I do not believe that such an environment can be easily set up for use on the web... I am taking suggestions however :) – steenbergh – 2017-11-10T20:19:58.677

@steenbergh Ah, that's true. I'm actually looking into ways to get QBasic / ABASIC / Applesoft Basic onto TIO. Right now it's looking like I'm going to need to write my own interpreters. >.< – MD XF – 2017-11-11T04:55:46.200

@MDXF The closest I've come to a web-interpreter yet is an Emscripten port of Dosbox someone made. You can add QBasic to its filesystem and let JS run the whole thing, but it's huge, slow and has drawbacks on interactivity. – steenbergh – 2017-11-11T05:38:57.710

@steenbergh Actually, QBasic is on repl.it, and it may be added to TIO soon.

– MD XF – 2017-11-11T05:39:52.577

@MDXF The implementation at repl.it seems to be a bit lacking...

– steenbergh – 2017-11-11T13:22:47.207

@steenbergh ....indeed. – MD XF – 2017-11-11T18:38:25.320

2

Mathematica, 35 27 bytes bytes

Saved 8 bytes on adding the appropriate number of ")" to the end thanks to alephalpha

#~Riffle~"("<>Most[0#+")"]&

Input is a list of characters. Riffles "(" between each character, then adds that many ")" minus 1 to the end. Specifically, multiplies the input by 0, adds ")" and then takes Most of the list.

e.g.

#~Riffle~"("<>Most[0#+")"]&[{"H","e","l","l","o"}]

{"H","e","l","l","o"}~Riffle~"("<>Most[0{"H","e","l","l","o"}+")"]

{"H","(","e","(","l","(","l","(","o"}<>Most[{0,0,0,0,0}+")"]

{"H","(","e","(","l","(","l","(","o"}<>Most[{")",")",")",")",")"}]

{"H","(","e","(","l","(","l","(","o"}<>{")",")",")",")"}

"H(e(l(l(o))))"

ngenisis

Posted 2016-10-18T18:34:27.623

Reputation: 4 600

1#~Riffle~"("<>Most[0#+")"]& – alephalpha – 2017-01-11T14:30:42.660

2

R, 56 bytes

function(s)c(paste(s,collapse="("),rep(")",length(s)-1))

Try it online!

Plain old R. Recursive solution below. Both input and output are vectors of characters.

R, 57 bytes

f=function(s)"if"(length(s)>1,c(s[1],"(",f(s[-1]),")"),s)

Try it online!

JayCe

Posted 2016-10-18T18:34:27.623

Reputation: 2 655

2

Forth (gforth), 66 58 bytes

: f over 1 type 1 -1 d+ dup 0> if ." ("recurse ." )"then ;

Try it online!

-8 bytes by switching to a recursive solution

Explanation

Prints the first character of the string. If it's not the last character in the string, print an open parentheses, recursively call on the remainder of the string, and print a close parentheses.

Code Explanation

: f             \ start a new word definition
  over 1 type   \ print the first character of the string
  1 -1 d+       \ remove the first character of the string
  dup           \ duplicate the string length value
  0> if         \ check if remaining string length is greater than 0
    ." ("       \ print an open parentheses
    recurse     \ call recursively on remainder of string
    ." )"       \ print a close parentheses
  then          \ end the if block
;               \ end the word definition            

reffu

Posted 2016-10-18T18:34:27.623

Reputation: 1 361

2

Poetic, 244 bytes

life is a quest,i say
i choose a fun course to cross
i cant say quite if survival excites
i say i am laughing
i create a way i relive a feeling
exile is torture,i say
i am thankful,of course,to say i adore u
i desire a wedding where i said i do

Try it online!

Poetic is an esolang I made in 2018 for a class project. It's basically brainfuck with word-lengths instead of symbols.

The point of the language is to allow for programs to be written in free-verse poetry.

JosiahRyanW

Posted 2016-10-18T18:34:27.623

Reputation: 2 600

2

Ruby, 41 29 bytes

->s{s.split("").join(?()+?)*(s.length-1)}

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

Thanks @ValueInk

dkudriavtsev

Posted 2016-10-18T18:34:27.623

Reputation: 5 781

chars is more efficient than split, and I believe you want s.length-1 – Lee W – 2016-10-18T19:16:22.117

size is more efficient than length, and multiplying an array by a string does an implicit join. And finally, (x-1) can be substituted to ~-x. Combining with Lee W suggestions, you end up with ->s{(s.chars*?()+?)*~-s.size} for 29 bytes! – Value Ink – 2016-10-19T00:36:33.430

2

And then I realize that these standard optimizations causes it to be exactly like @m-chrzan's answer, and now this is a tad awkward

– Value Ink – 2016-10-19T00:38:44.133

2

Lua, 88 bytes

Probably not nearly as short as it could be.

x=""y=...for i=1,#y-1 do x=x..y:sub(i,i).."("end print(x..y:sub(-1,-1)..(")"):rep(#y-1))

Takes input from the command line.

IDid

Posted 2016-10-18T18:34:27.623

Reputation: 101

Here's even better! y=...print(y:gsub('.','%1(',#y-1)..(')'):rep(#y-1)) 51 bytes I also made variations for repeat until and while end but they were longer than yours even though as minified as possible. – ascx – 2016-10-20T12:38:03.183

@ascx In here, you're not allowed to edit his answer just to golf it further. Let the author did that. – Akangka – 2016-10-23T14:33:21.223

@ascx http://meta.codegolf.stackexchange.com/a/1619/46245

– Akangka – 2016-10-23T14:35:25.883

2

C, 102 89 bytes

Maybe this can be golfed more? I'm just happy to answer in C! :D

i=0,j=0;f(char*a){while(*a)putchar(*a),*++a?putchar(40),i++:0;while(j<i)putchar(41),j++;}

cat

Posted 2016-10-18T18:34:27.623

Reputation: 4 989

179 bytes – ceilingcat – 2019-10-17T20:31:28.573

@ceilingcat braver than me. – cat – 2019-10-18T04:58:13.530

2

Mathematica, 45 43 bytes

#2<>"("<>#<>")"&~Fold~Reverse@Characters@#&

freddieknets

Posted 2016-10-18T18:34:27.623

Reputation: 199

You can use # instead of #1. And infix notation ~Fold~ should also work. – Martin Ender – 2016-10-19T08:42:45.507

2

Turtlèd, 25 27 bytes

(original didn't work for single char inputs ;_;)

This is what Turtlèd ended up being for even though it as originally ascii art stuff.

!-l[*+.r'(r_]l-_[*-')r_]"  [2 trailing spaces]

Try it online!

Explanation:

put the input on to the cells with ( after each char

!                        Take a string as input
 -                       decrement the string pointer, so it points at last char
  l                      move left
   [*       ]            while the current cell is not *
     +.r                 increment string pointer and write the pointed char, move right
        '(r              write (, move right
           _             write * if pointed char is last char, else " "


Write the terminating parens, the first one overwriting the last open paren

             l-           move left, decrement string pointer
               _          write * if pointed char is last char, else " "
                [*     ]  while the current cell is not *
                  -')r    decrement string pointer, write ), move right
                      _   write * if pointed char is last char, else " "

                        "[2 spaces]  Remove the last *, or two *s if input is one char

Destructible Lemon

Posted 2016-10-18T18:34:27.623

Reputation: 5 908

2

SWI-Prolog, 82 bytes

q([H],[H]).
q([H|T],[H,40|S]):-q(T,R),append(R,[41],S).
X*Y:-q(X,Z),atom_codes(Y,Z).

Called like: `Hello World!`*X.

Online interpreter

Emigna

Posted 2016-10-18T18:34:27.623

Reputation: 50 798

2

PHP, 51 60 68 63 bytes

Why not just do what´s asked for instead of emulating it? Recurse!

function n($s){return$s[1]>""?"$s[0](".n(substr($s,1)).")":$s;}

Titus

Posted 2016-10-18T18:34:27.623

Reputation: 13 814

why not change $s[1]>"" into just $s[1]? 3 chars less. – nl-x – 2016-10-24T13:40:26.637

@nl-x because the 0 character evaluates to false – Titus – 2016-10-24T13:43:30.413

@nl-x ... but I learned something just as long in the meantime. – Titus – 2017-03-07T23:53:41.507

Please do explain what you did there... – nl-x – 2017-03-08T07:26:44.543

@nl-x I messed it up. I intended a shorter check on the second character using bitwise arithmetics, but checked the string for emptiness instead. Rolled back. – Titus – 2017-03-08T13:02:30.423

2

CJam, 12 11 bytes

One byte saved by Martin Ender.

q_'(*\,(')*

Try it online

Neorej

Posted 2016-10-18T18:34:27.623

Reputation: 179

1You can save a byte by avoiding the second \: q_'(*\,(')* – Martin Ender – 2016-10-21T12:01:28.943

2

k, 16 bytes

This is an anonymous function composition

{y,"(",x,")"}/|:

Example

k){y,"(",x,")"}/|:"hello world"
"h(e(l(l(o( (w(o(r(l(d))))))))))"

skeevey

Posted 2016-10-18T18:34:27.623

Reputation: 4 139

2

Pyth, 10 characters

+j\(Q*\)tl

Try it online!

Joins the input on (, and appends length - 1 closing parens afterwards.

Steven H.

Posted 2016-10-18T18:34:27.623

Reputation: 2 841

2

Scala, 58 bytes

"Hello world!"match{case s =>s.mkString("(")+")"*s.length}

Could be shorter

Trevor Sibanda

Posted 2016-10-18T18:34:27.623

Reputation: 31

I think you meant (s:String)=>s.mkString("(")+")"*s.length (40 bytes) (no need for match case here) – Jacob – 2018-05-28T07:22:31.983

Also - I think it's not correct. You'll need *(s.length-1) – Jacob – 2018-05-28T07:26:34.707

2

Actually, 10 bytes

lD')*ß'(j+

Try it online!

Explanation:

lD')*ß'(j+
lD')*       ")"*(len(input)-1)
     ß'(j   insert a "(" between every pair of characters in the input
         +  append the closing parens

Mego

Posted 2016-10-18T18:34:27.623

Reputation: 32 998

2

V, 9 bytes

$òys$)hhl

Try it online!

James

Posted 2016-10-18T18:34:27.623

Reputation: 54 537

1

Python 3, 43 bytes

lambda x:print(*x,sep='(',end=')'*~-len(x))

Longer than shortest Python submission, but it is fairly different, so I thought I should post it. It is a function, but prints to STDOUT.

nedla2004

Posted 2016-10-18T18:34:27.623

Reputation: 521

This prints one extra close paren each time. Try ~-len(x) rather than len(x) – Post Rock Garf Hunter – 2017-01-11T02:16:49.863

@WheatWizard Thank you, I don't know how I missed that. – nedla2004 – 2017-01-11T12:49:52.040

1

Clojure, 94 60 59 48 bytes

-34 by making it a actual recursive solution. The biggest saving here was getting rid of the repeat part to generate the end brackets.

-1 by rearranging it, eliminating a conditional.

-11 bytes thanks to NikoNyrh. Now deconstructs the parameter directly.

(defn n[[f & r]](if(str f(if r(str\((n r)\))))))

Recursive. Basically (str head "(" (recur tail) ")"), with the brackets being added only if a tail exists.

Uses unoptimized recursion. Can handle strings up to around 5235 characters long.

Ungolfed:

(defn nest [[f & r]]
    (if f ; When it exists, construct string and recur, else, base-case
      (str f (if r (str \( (nest r) \))))))

Carcigenicate

Posted 2016-10-18T18:34:27.623

Reputation: 3 295

I guess you could merge function definition and let to (defn n[[f & r]](if f(str f(if r(str\((n r)\))))) :) – NikoNyrh – 2017-01-11T00:38:12.900

@NikoNyrh You're right! I hate deconstructing in the parameter list in real code, but that certainly helps here. Thanks! – Carcigenicate – 2017-01-11T00:39:13.257

1

Haskell, 38 30 bytes

8 bytes saved thanks to @JanDvorak

f[x]=[x]
f(x:s)=x:'(':f s++")"

This is my first attempt at a haskell golf, probably not optimal yet.

Explanation

We define a function f. If this function receives input that matches the pattern [x], that is a length 1 string, we return the input. If we receive anything else as input we return the x:'(':f s++")", or the first character plus the rest result of f on the rest of the string all enclosed in parentheses.

Post Rock Garf Hunter

Posted 2016-10-18T18:34:27.623

Reputation: 55 382

1

Groovy, 46 bytes

{it.reverse().inject{r,i->")$r($i"}.reverse()}

Magic Octopus Urn

Posted 2016-10-18T18:34:27.623

Reputation: 19 422

1

Swift 3.1,  85  83 bytes

This is an anonymous function accepting an Array of Strings and returning a String.

{$0.joined(separator:"(")+String(repeating:")",count:$0.count-1)}as([String])->String

Try it here!

Swift 3.1,  88 87  86 bytes

This is a named function accepting an Array of Strings and printing a String.

func f(n:[String]){print(n.joined(separator:"(")+(1..<n.count).map{_ in")"}.joined())}

Try it here!

Mr. Xcoder

Posted 2016-10-18T18:34:27.623

Reputation: 39 774

1

Ly, 50 bytes

iyspr1[1[=!["("o1$]p1$]1[=[pp2$]p1$]o]l1-[")"o1-];

Try it online!

This is ridiculous. Ly is lacking severely in the string manipulation department.

LyricLy

Posted 2016-10-18T18:34:27.623

Reputation: 3 313

1

Java 8 (63 82 bytes)

"s" is a char[]

s->{String r="",p=r;for(char c:s){r+="("+c;p+=")";}return r+p;}

s->{String r="",p=r;for(char c:s){if(r==p)r+=c;else{r+="("+c;p+=")";}}return r+p;}

Edit: I didn't realise there aren't parentheses around the whole string.

Roberto Graham

Posted 2016-10-18T18:34:27.623

Reputation: 1 305

1

Implicit, 24 23 bytes

~@~.(0-1@40@~.);;(0@41;

Try it online!

Ungolfed/explained:

~@~.     # read first character, print, read second, increment
(0       # do-while top of stack truthy
 -1      #  decrement top of stack
 @40     #  print open parenthesis (ASCII 40)
 @       #  print top of stack
 ~.      #  read char and increment
)        # while top of stack truthy
;;       # pop top two values (EOF, last char)

(0       # do-while top of stack truthy
 @41     #  print close parenthesis (ASCII 41)
 ;       #  pop top of stack
¶        # (implicit) forever

Test cases:

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

foobar
f(o(o(b(a(r)))))

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

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

a
a

42
4(2)

MD XF

Posted 2016-10-18T18:34:27.623

Reputation: 11 605

1

SNOBOL4 (CSNOBOL4), 111 bytes

	INPUT LEN(1) . O REM . N
	W =SIZE(N)
N	N LEN(1) . X REM . N	:F(O)
	O =O '(' X	:(N)
O	OUTPUT =O DUPL(')',W)
END

Try it online!

Giuseppe

Posted 2016-10-18T18:34:27.623

Reputation: 21 077

1

Canvas, 8 bytes

(*;L╷)×+

Try it here!

hakr14

Posted 2016-10-18T18:34:27.623

Reputation: 1 295

1

Kotlin, 83 63 bytes

-20 bytes using toList; thanks to 12Me21 tipping me off this could be shorter.

{s:String->s.toList().joinToString("(")+")".repeat(s.length-1)}

Try it online!

snail_

Posted 2016-10-18T18:34:27.623

Reputation: 1 982

1

Whitespace, 132 bytes

[S S S N
_Push_0][N
S S N
_Create_Label_LOOP][S N
S _Duplicate][S N
S _Duplicate][T N
T   S _Read_characters_as_STDIN][T  T   T   _Retrieve][S S S T  S T S S T   N
_Push_41_)][T   S S T   _Subtract][N
T   S S N
_If_0_Jump_to_Label_PRINT_TRAILING][S N
S _Duplicate][N
T   S T N
_If_0_Jump_to_Label_SKIP][S S S T   S T S S S N
_Push_40_(][T   N
S S _Print_as_character][N
S S T   N
_Create_Label_SKIP][S N
S _Duplicate][T T   T   _Retrieve][T    N
S S _Print_as_character][S S S T    N
_Push_1][T  S S S _Add][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_PRINT_TRAILING][S S S T   N
_Push_1][T  S S T   _Subtract][S N
S _Duplicate][N
T   S S S N
_If_0_Jump_to_Label_EXIT][S S S T   S T S S T   N
_Push_41_)][T   N
S S _Print_as_character][N
S N
S N
_Jump_to_Label_PRINT_TRAILING]

Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

Since Whitespace's STDIN don't know when the input is done since it can only read a single character or number at a time, the input will need a trailing ) to indicate we're done inputting (which is possible since the challenge rules state: "For simplicity's sake, you may also assume the input will not contain parentheses").

Explanation in pseudo-code:

Integer n = 0
Start LOOP:
  Character c = read character from STDIN
  If(c == ')'):
    Jump to function PRINT_TRAILING
  If(n != 0)
    Print '(' to STDOUT
  Print c to STDOUT
  n = n + 1
  Jump to next iteration of LOOP

function PRINT_TRAILING:
  n = n - 1
  If(n == 0)
    Stop program
  Print ')' to STDOUT
  Jump to function PRINT_TRAILING

Kevin Cruijssen

Posted 2016-10-18T18:34:27.623

Reputation: 67 575

1

J, 29 bytes

f=:(')'#~<:@#),~}.@,@('(',.])

Try it online!

user58120

Posted 2016-10-18T18:34:27.623

Reputation:

1

C++, 66 bytes

[&](string s){return s[1]?s.substr(0,1)+"("+f(s.substr(1))+")":s;}

Try it Online

Matlab, 45 bytes

@(s)fold(@(x,y)strcat(y,'(',x,')'),fliplr(s))

Try it Online!

The problem with this is that octave in try it online doesn't really support the fold function which of course exists in Matlab. Let me know if I should delete this solution since we can't test it on tio.

DimChtz

Posted 2016-10-18T18:34:27.623

Reputation: 916

1Being able to test a submission on TIO is not a requirement, so your MATLAB answer is just fine. It's preferable to post different solutions in different answers though, so they can be voted on independently. – Dennis – 2018-08-28T14:18:09.087

Octave implementation of fold() – ceilingcat – 2019-10-16T05:22:59.097

1

Keg, 22 16 15 12 bytes

?^⑷`(`⑸÷_(\)

Explained

?^⑷`(`⑸÷_(\)
#?^         Takes input and reverse it
#⑷`(`⑸÷    Maps an additional "(" to each letter
#÷_         Takes the last item and removes the extra bracket
#(\)        Appends a ")" for each item on the stack

Answer History

15 bytes

?!&("\()_^`)`&*

Try it online!

-1 byte due to some sort of stack-mechanic magic. I don't really know what I did, but it's shorter! Also, it's still ASCII only!

Explained:

?!&("\()_^`)`&*
?!&             #Take input and store the length in the register
   ("\()        #For each item on the stack, right shift and push a "("
        _^      #Pop the top and reverse
          `)`&* #Push ")" multiplied by the register (python-like string multiplication)

Answer History

16 bytes

?!&("\()'^_`)`&*

Try it online!

-6 bytes due to usage of the register rather than a custom variable. Also, that's 16 UTF-8/ASCII bytes for once.

Explained:

?!&("\()'^_`)`&*
?!&                 #Take input and store the length in the register
   ("\()            #For each item on the stack, right shift and push a "("
        '^_         #Left shift the stack, reverse and pop the top of stack
           `)`&*    #Push ")" multiplied by the register (python-like string multiplication)

22 bytes (SBCS)

?!®c("\()'^_(©c|\))^(,

Try it online!

Note that due to a newly discovered bug, TIO won't work properly, but the github interpreter will work correctly.

Explanation

#?!®c("\()'^_(©c|\))^(,
?!®c    #Get user input, and store the length in variable c
("\()   #For each item in the stack, right shift and push a "("
'^_ #Reverse the stack and pop the last most "("
(©c|\)) #For _ in range(0, var_c): append a ")"
^(, #Reverse and print the stack as characters

Lyxal

Posted 2016-10-18T18:34:27.623

Reputation: 5 253

Just for fun: achieves the same bytecount using non-extended Keg.

– None – 2019-10-26T06:34:49.673

1

C (gcc), 97 84 bytes

Thanks to ceilingcat for -13 bytes

f(char*b){printf(*++b?"%c(":"%c",*b);*b&&f(b)+printf(")");}a[99];main(){f(gets(a));}

Try it online!

girobuz

Posted 2016-10-18T18:34:27.623

Reputation: 391

1

Gol><>, 21 bytes

TiE!tlF`(}}|~l2,R`)rH

Try it online!

24 bytes

TiE!trlF}8ss}|r~l2,R`)rH

It's hideous, I know. I am going to golf this profusely.

Try it online!

KrystosTheOverlord

Posted 2016-10-18T18:34:27.623

Reputation: 681

1

Wren, 54 bytes

Fn.new{|x|x.map{|i|i+"("}.join()[0..-2]+")"*~-x.count}

Try it online!

Wren, 36 bytes

I didn't write this myself. Therefore it is boring.

Fn.new{|x|x.join("(")+")"*~-x.count}

Try it online!

user85052

Posted 2016-10-18T18:34:27.623

Reputation:

1

Befunge-93, 33 bytes

~# <\,"()"_v#+1:~,
         :,_@#

Try it online!

Due to the < character, the first line should be read backwards.

, : Output the most recently read character.

~ : Read a new character.

1+#v_: If there is no new character, go to the second line.

")(": Push parentheses characters onto the stack.

, : Output left parenthesis.

\ : Bury the right parenthesis deeper in the stack so it won't output until the end.

The rest of the first line is code to special-case the first character so that it gets output without creating parentheses.

The second line then simply outputs the stack until it's empty.

histocrat

Posted 2016-10-18T18:34:27.623

Reputation: 20 600

1

Pyth - 9 bytes

+j\(Qsm\)

Try it online here.

Maltysen

Posted 2016-10-18T18:34:27.623

Reputation: 25 023

The output has one ) too many. – Neorej – 2016-10-19T11:40:40.327

Use +j\(Qstm\) instead. – Erik the Outgolfer – 2016-10-19T12:27:19.700

1

Perl 5, 27 bytes (25 + 1 for -l + 1 for -n)

This is a translation of Wheat Wizard's approach to Perl.

say$_.")"x s/.(?!$)/$&(/g

Run it like this:

perl -nlE 'say$_.")"x s/.(?!$)/$&(/g' <<< 'Hello'

Explanation:

say$_.")"x s/.(?!$)/$&(/g
           s/.(?!$)/   /g # replace every char not followed by end of string ...
                    $&    # ... with the full match (that's the one char)
                       (  # and an open parenthesis
           s/.(?!$)/$&(/g # this operates on and changes $_ and ...
                          # ... returns the number of substitutes
      ")"x                # repeat closing paren number of substitues times
     .                    # append
   $_                     # to the string that has already been changed to f(o(o
say                       # print with newline

simbabque

Posted 2016-10-18T18:34:27.623

Reputation: 487

That's some very nice golfing! :-) – Dada – 2016-10-18T21:31:07.840

You don't need the -l if you demand the input string is entered without final newline: echo -n Hello | program – Ton Hospel – 2016-10-19T05:14:03.627

1

Pyke, 9 bytes

\(JQl\)*+

Try it here!

Blue

Posted 2016-10-18T18:34:27.623

Reputation: 26 661

1

Racket 195 bytes

(let p((r "")(l(reverse(string->list s)))(i 0))(cond[(= i(length l))r][(= i 0)(set! r(string(list-ref l i)))
(p r l(+ 1 i))][(set! r(string-append(string(list-ref l i))"("r")" ))(p r l(+ 1 i))]))

Ungolfed:

(define (f s)
  (let loop ((r "")
             (l (reverse (string->list s)))
             (i 0))
    (cond
      [(>= i (length l)) r] 
      [(= i 0) (set! r (string (list-ref l i)))
               (loop r l (add1 i))]
      [else (set! r (string-append (string (list-ref l i)) "(" r ")" ))
            (loop r l (add1 i))]
      )))

Testing:

(f "Hello")

Output:

"H(e(l(l(o))))"

Edit: 2 bytes saved following suggestion by @JonathanFrech (add1 to + 1)

rnso

Posted 2016-10-18T18:34:27.623

Reputation: 1 635

+ 1 is shorter than add1. – Jonathan Frech – 2018-08-28T16:15:56.300

1

Python 3, 40 chars

s=input()
print("(".join(s)+len(s)*")")

vpzomtrrfrt

Posted 2016-10-18T18:34:27.623

Reputation: 201

1

Zsh, 36 Bytes

z=${1:1};<<<${1[1]}${z///(}${z//?/)}

This should be possible in 34 bytes, but zsh syntax is inconsistent. $a[1] will return the first character of the string $a, but $1[1] returns the entire contents of $1 plus the string "[1]". I'd love to know if this is intended behavior, or just on a long list of zsh documentation not covering edge cases.

The logic used is

  1. Assign all but the first character of the first argument to a variable z
  2. Print the first character of the input
  3. Print z, with "the empty string replaced with (" which actually places a ( before each character of z
  4. Print z, with all of the characters replaced with )

I don't think its golfable much farther from here, even though I how many characters it takes to just split the first character from the rest of the string. There is probably a more efficient "logic" though, I just couldn't find one that synergizes with zsh or bash.

Speaking of bash, this doesn't work because the cute trick with sed-style replacing the empty string does not do anything in bash. I will edit with a solution that is better designed for bash-compatible syntax.

LinusKrom

Posted 2016-10-18T18:34:27.623

Reputation: 113

1

Gema, 31 13 characters

Shamelessly borrowing Titus's idea from his recursive PHP solution.

\B?=?
?#=(?#)

Sample run:

bash-4.3$ echo -n 'Hello world!' | gema '\B?=?;?#=(?#)'
H(e(l(l(o( (w(o(r(l(d(!)))))))))))

manatwork

Posted 2016-10-18T18:34:27.623

Reputation: 17 865

1

Groovy, 38 36 Bytes thanks to @manatwork

{it.reverse().inject{r,i->i+"($r)"}}

Yeah, the C&P messed up the first time.

Magic Octopus Urn

Posted 2016-10-18T18:34:27.623

Reputation: 19 422

I think your code was destroyed on copy paste, as is neither functional and is far from your byte count. BTW, no need for braces around simple variables in expansion. – manatwork – 2016-10-19T19:14:52.140

@manatwork was missing a brace, the braces are for string interpolation and you're right I effed the byte-count, forgot it needed reverse. – Magic Octopus Urn – 2016-10-19T19:41:30.937

I use http://lettercount.com for groovy byte count, NO IDEA what was going on. I thought 68 seemed high...

– Magic Octopus Urn – 2016-10-19T19:42:47.100

1Cool. But you still have extra braces in interpolation: "(${r})""($r)". At least Groovy 2.4.5 is happy without them too. – manatwork – 2016-10-19T19:51:09.873

@manatwork most of my experience is with Groovy on Grails and $ notation isn't accepted in views AFAIK. – Magic Octopus Urn – 2016-10-19T19:52:59.860

1

Scala, 46 bytes

(s:String)=>(s.init:\(""+s.last))(_+"("+_+")")

Explanation:

(s:String)=>    //define a function
  (s.init       //take everything but the last char
   :\           //foldRight
   (""+s.last)    //with the last char as a string as a start
  )(              //combine the chars right to left with this function:
    _+"("+_+")"   //take the char, append "(", append everything we've got so far, append ")"
  )

corvus_192

Posted 2016-10-18T18:34:27.623

Reputation: 1 889

1

Java, 72 bytes

(a,s,l)->{l=a.length;s=""+a[--l];for(;l>0;)s=a[--l]+"("+s+")";return s;}

Ungolfed

public class Main {

  interface X {
    String f(char[]a,String s,int l);
  }

  static X x = (a,s,l) -> {
    l = a.length;
    s = "" + a[--l]; // start with the last character
    for (;l>0;)
      s = a[--l] + "(" + s +")"; // wrap in parentheses and prepend with the previous letter.
    return s;
  };

  public static void main(String[] args) {
    System.out.println(x.f("Hello World!".toCharArray(),"",0));
  }
}

Olivier Grégoire

Posted 2016-10-18T18:34:27.623

Reputation: 10 647

1

Python 2, 60 57 51 Bytes

def c(s):if(len(s)==1):return s;return s[0]+"("+c(s[1:])+")"

After some clarification on the rules from @manatwork on white space,

def c(s):return s if(len(s)==1)else s[0]+"("+c(s[1:])+")"

Thanks again @manatwork

def c(s):return s[0]+"("+c(s[1:])+")"if s[1:]else s

Ungolfed:

def c(s):
    if(len(s)==1):
        return s;
    return s[0]+"("+c(s[1:])+")"

Recursively calls itself and adds to the string.

c("CodeGolf") = 'C(o(d(e(G(o(l(f)))))))'

bioweasel

Posted 2016-10-18T18:34:27.623

Reputation: 307

3This doesn't work. You can't have if statements in one line. SyntaxError – Blue – 2016-10-19T19:00:09.347

I just put in on the one line to show it concisely without whitespace. You actually run the ungolfed version – bioweasel – 2016-10-19T19:23:12.013

1Sorry, @bioweasel, but the spaces needed for the code to run have to be counted. Better refactor it to have a single statement inside the function: def c(s):return s if(len(s)==1)else s[0]+"("+c(s[1:])+")". – manatwork – 2016-10-19T20:02:17.167

Ah, gotcha. Sorry, this is my first time and I wasn't quite sure on the rules 100%, especially with Python and the whitespace – bioweasel – 2016-10-19T20:09:16.133

You could use that s[1:] syntax in the condition too: def c(s):return s[0]+"("+c(s[1:])+")"if s[1:]else s. – manatwork – 2016-10-19T20:24:35.350

1

Bash / sed, 74 bytes

y=$(echo $1|sed "s/./\0(/g");z=$(echo $1|sed "s/./)/g");echo ${y%?}${z%?}
  • Puts a parenthesis after each characters in y.
  • Puts a parenthesis for each characters in z.
  • Print x and z truncated of one character.

To test, put this code into a file, and run the shell script with any arguments.

Doomsday

Posted 2016-10-18T18:34:27.623

Reputation: 201

1

C, 84 82 76 70 68 66 Bytes

i;f(char*s){for(i=1;*s+~i;putchar(*s?i&1?*s++:40:41),i+=*s?1:-2);}

Now using just one for loop and one putchar...

Test is like this

main(c,v)char**v;
{
    f(v[1]);puts("");
    f("foobar");puts("");     
    f("code-golf");puts("");     
}

output

H(e(l(l(o( (W(o(r(l(d))))))))))
f(o(o(b(a(r)))))
c(o(d(e(-(g(o(l(f))))))))

cleblanc

Posted 2016-10-18T18:34:27.623

Reputation: 3 360

1

Dart 44 bytes

p(s)=>s.split("").join("(")+")"*~-s.length;

I tried to be clever, but nothing beat this simple version. Notable mention:

r(s,[x=0])=>s[x++]+(x<s.length?"(${r(s,x)})":"");
q(s)=>s[0]+((s=s.substring(1))==""?s:"(${q(s)})");

but they drowned in necessary parentheses.

lrn

Posted 2016-10-18T18:34:27.623

Reputation: 521

1

JavaScript, 36 bytes

([...v])=>v.join`(`+v.fill``.join`)`

I can't seem to beat the top score of 34 bytes, but I thought I would share my different approach.

Grax32

Posted 2016-10-18T18:34:27.623

Reputation: 1 282

0

tcl, 66

puts [join [split $s ""] (][string repe ) [expr [string le $s]-1]]

Testable on http://rextester.com/live/SAXFO71660

sergiol

Posted 2016-10-18T18:34:27.623

Reputation: 3 055

0

ForceLang, 132 bytes

def S set
S a io.readln()
S i 0
S b ")"
label 1
io.write a.charAt i
S i i+1
if i+-a.len
 io.write "("
 goto 1
io.write b.repeat i+-1

SuperJedi224

Posted 2016-10-18T18:34:27.623

Reputation: 11 342

0

Japt, 11 bytes

ç q') iUq'(

Try it online!

Takes an array of 1-length strings as input.

How it works

Uç q') iUq'(

Uç    Replace input array's every element with `undefined`
q')   Join with ")"
i     Insert to the beginning of above result...
Uq'(    Input array joined with "("

Uses a JS trick: undefined elements of an Array is converted to empty strings on join.

Bubbler

Posted 2016-10-18T18:34:27.623

Reputation: 16 616

0

Java 10, 71 bytes

s->{var r="";for(int i=s.length;i-->1;r="("+s[i]+r+")");return s[0]+r;}

Shorter than the existing two recursive Java answers.

Input as String-array of each character.

Try it online.

s->{               // Method with String-array parameter and String return-type
  var r="";        //  Result-String, starting empty
  for(int i=s.length;i-->1; 
                   //  Loop backwards over the array, skipping the first character
    r=             //   Set the result to:
      "("          //    An opening parenthesis,
      +s[i]        //    appended with the current character,
      +r           //    appended with the current result-String,
      +")");       //    appended with a closing parenthesis
  return s[0]+r;}  //  Return the first character, appended with the result-String

Kevin Cruijssen

Posted 2016-10-18T18:34:27.623

Reputation: 67 575

0

Python 3.6+, 39 bytes

z=lambda x,*y:x+f'({z(*y)})'if y else x

Takes each character as an individual argument (can be used like z(*'asdf')). This uses recursion with iterable unpacking and f-string interpolation.


Note: This is almost non-competing. Python 3.6 was released after this challenge was posted, but was feature-frozen in beta on 2016-09-12, so this feature was available before the challenge was posted.


Though it turns out you can do it in the same number of bytes with %-interpolation (this works on more Python versions):

z=lambda x,*y:x+'(%s)'%z(*y)if y else x

Beefster

Posted 2016-10-18T18:34:27.623

Reputation: 6 651

0

Gol><>, 37 bytes

14a*iov
!vo$P$>:oi:P?
:>~~:?!;9sso1-:

Try it online!

Reads from stdin, outputs to stdout

Explanation:

14a*            Pushes 1 (num of characters so far) and 40 (ASCII for open paren) onto stack
    io          Reads a character and outputs it
      v         Drops to next line of golfed code

      >         Directs pointer to the right
       :o       Duplicates and outputs the (
         i      Inputs a character
!v        :P?   Drops to next line of golfed code if no more chars
  o             Outputs character
   $P$          Increments the character counter

 >              Directs pointer to the right
  ~~            Discard unneeded stack values
    :?!;        Exits if counter == 0
        9sso    Outputs closing paren
            1-  Decrement counter
:             : Duplicate counter twice (so that it isn't discarded by the '~'

xornob

Posted 2016-10-18T18:34:27.623

Reputation: 181

ioiEH')('o$! – Jo King – 2018-08-28T08:17:54.847

@JoKing well now I feel inadequate /s – xornob – 2018-08-28T08:24:11.430

Well, when creating a Gol><> answer you need to check if there's an existing ><> answer you can adapt ;)

– Jo King – 2018-08-28T08:26:26.907

Welcome to PPCG! looks like you have too many parentheses: there should be no opening parenthese after the last letter of the string. – JayCe – 2018-08-28T13:34:55.863

0

Japt, 11 bytes

¬q'( +UÅî')

Try it

Shaggy

Posted 2016-10-18T18:34:27.623

Reputation: 24 623

0

Icon, 59 bytes

procedure f(s)
return(*s>1&s[1]||"("||f(s[2:0])||")")|s
end

Try it online!

Galen Ivanov

Posted 2016-10-18T18:34:27.623

Reputation: 13 815

0

Red, 59 bytes

func[s][either 1 < length? s[rejoin[s/1"("f next s")"]][s]]

Try it online!

Galen Ivanov

Posted 2016-10-18T18:34:27.623

Reputation: 13 815

0

Burlesque, 16 bytes

'([]sa2./')j.*.+

Try it online!

'([]  # Insert "(" between each char
sa2./ # Find length/2
')j.* # That many ")"s
.+    # Concatenate

DeathIncarnate

Posted 2016-10-18T18:34:27.623

Reputation: 916

0

GolfScript, 12 bytes

.'('*')'@,(*

What a cute little solution!

.            #Duplicate entry string
 '('*        #Join the string with left-paren
     ')'     #Right paren string
        @    #Bring up our duplicate
         ,   #Count the number of characters
          (  #Decrease that number by 1
           * #Add that many ')' to the end

Try it online!

Mathgeek

Posted 2016-10-18T18:34:27.623

Reputation: 408

0

Unix TMG, 51 byte

p:parse(s)s:smark any(!<<>>)scopy s/d={2<(>1<)>}d:;

Works by recursive descent parsing.

Exploits absence of semicolons between parsing rules to make it two bytes shorter.

Andriy Makukha

Posted 2016-10-18T18:34:27.623

Reputation: 404

0

Python 50 49 bytes

saved 1 byte (actually 3) thanks to @ETHproductions

This is my recursive version written in Python. Would probably be shorter the iterative aproach.. but I simply like recursion :)

F=lambda s:s[0]+'('+F(s[1:])+')'if len(s)>1else s

Stefan

Posted 2016-10-18T18:34:27.623

Reputation: 261

If a function entry needs to call itself, you must include the assignment (i.e. F=) in the byte count. Also, I think you can do s at the end instead of s[0], as the string's length is already 1. – ETHproductions – 2016-10-21T13:05:55.093

ups, I actually had it like that but forgot to copy it.. thanks! – Stefan – 2016-10-21T14:58:40.873

Quite similar to bioweasel's Python solution.

– manatwork – 2016-10-21T15:05:14.237

Indeed, didn't see his solution.. – Stefan – 2016-10-21T15:16:23.583

Possible 48 bytes. – Jonathan Frech – 2018-08-28T16:20:13.277