| Bytes | Lang | Time | Link |
|---|---|---|---|
| 063 | Nim | 250816T102614Z | janAkali |
| 028 | APLNARS | 250815T100131Z | Rosario |
| 012 | Pip | 250814T190107Z | DLosc |
| 044 | tinylisp 2 | 250814T172039Z | DLosc |
| 007 | Jelly | 161018T184320Z | Jonathan |
| 019 | Brachylog | 250814T054944Z | DLosc |
| 013 | Dyalog APL | 250814T043115Z | Aaron |
| 252 | Bespoke | 250814T033609Z | Josiah W |
| 038 | AWK | 250312T194958Z | xrs |
| 010 | Uiua 0.15.0dev.2 | 250306T203725Z | RomanPro |
| 035 | Python 3 | 250306T181524Z | The Empt |
| 040 | Brainfuck | 161018T194533Z | Alex How |
| 066 | Tcl | 170111T203848Z | sergiol |
| 010 | Thunno 2 | 230603T183346Z | The Thon |
| 073 | TypeScript's Type System | 230502T121100Z | Tristan |
| 012 | Pip | 230311T140022Z | The Thon |
| 044 | Arturo | 230501T205643Z | chunes |
| 035 | JavaScript Node.js | 230310T103634Z | Fhuvi |
| 816 | Nibbles | 230311T150651Z | Dominic |
| 064 | TIBasic | 211027T220511Z | Youserna |
| nan | 230311T135254Z | The Thon | |
| 032 | KamilaLisp v0.2 | 230310T200131Z | Kamila S |
| 007 | Vyxal | 211026T193618Z | emanresu |
| 020 | ayr | 211103T142105Z | ZippyMag |
| 007 | Vyxal | 211102T122656Z | lyxal |
| 018 | Underload | 211029T150420Z | Mayube |
| 051 | Python 3 | 211028T011716Z | Alan Bag |
| 033 | MAWP | 200809T150014Z | Razetime |
| 084 | Zig | 200302T222140Z | pfg |
| 051 | Unix TMG | 200228T154416Z | Andriy M |
| 012 | GolfScript | 200226T205912Z | Mathgeek |
| 016 | Burlesque | 200225T093746Z | DeathInc |
| 010 | 05AB1E | 191224T225832Z | mabel |
| 033 | Befunge93 | 191224T192926Z | histocra |
| 054 | Wren | 191224T090224Z | user8505 |
| 012 | Keg | 191015T215331Z | lyxal |
| 244 | Poetic | 191018T223516Z | JosiahRy |
| 084 | C gcc | 191017T031856Z | girobuz |
| 021 | Gol><> | 191017T235057Z | KrystosT |
| 058 | Forth gforth | 180828T132626Z | reffu |
| 059 | Icon | 191015T070438Z | Galen Iv |
| 059 | Red | 191015T072930Z | Galen Iv |
| 195 | Racket | 161019T021502Z | rnso |
| 033 | JavaScript ES6 | 161018T184517Z | Arnauld |
| 066 | C++ | 180828T092344Z | DimChtz |
| 029 | J | 180828T091439Z | user5812 |
| 011 | Japt | 180828T090617Z | Shaggy |
| 132 | Whitespace | 180828T090540Z | Kevin Cr |
| 037 | Gol><> | 180828T074613Z | xornob |
| 063 | Kotlin | 180525T180945Z | snail_ |
| 006 | Stax | 180524T154919Z | Khuldrae |
| 039 | Python 3.6+ | 180524T225552Z | Beefster |
| 008 | Canvas | 180525T015745Z | hakr14 |
| 111 | SNOBOL4 CSNOBOL4 | 180524T184050Z | Giuseppe |
| 056 | R | 180524T181952Z | JayCe |
| 071 | Java 10 | 180524T084025Z | Kevin Cr |
| 011 | Japt | 180524T082747Z | Bubbler |
| 023 | Implicit | 171110T181521Z | MD XF |
| 064 | QBIC | 161128T180855Z | steenber |
| 082 | Java 8 | 170901T133347Z | Roberto |
| 050 | Ly | 170901T090506Z | LyricLy |
| 083 | Swift 3.1 | 170901T082331Z | Mr. Xcod |
| 046 | Groovy | 170628T181353Z | Magic Oc |
| 030 | Haskell | 170611T174536Z | Wheat Wi |
| 063 | PHP | 161019T123354Z | Titus |
| 132 | ForceLang | 170308T011205Z | SuperJed |
| nan | BrainFlak | 161019T014637Z | Wheat Wi |
| 027 | Mathematica | 170108T224251Z | user6198 |
| 043 | Python 3 | 170108T171657Z | nedla200 |
| 048 | Clojure | 170108T220430Z | Carcigen |
| 034 | Python | 161018T183941Z | Wheat Wi |
| 014 | Dyalog APL | 161128T191918Z | ngn |
| 036 | JavaScript | 161110T201513Z | Grax32 |
| 009 | V | 161110T180810Z | DJMcMayh |
| 066 | C | 161020T183418Z | cleblanc |
| 030 | MSDOS .com file | 161018T203138Z | Martin R |
| 072 | Java | 161019T141406Z | Olivier |
| 018 | Jellyfish | 161019T101120Z | Zgarb |
| 044 | Dart | 161024T081759Z | lrn |
| 010 | Actually | 161024T063710Z | user4594 |
| 058 | Scala | 161023T184416Z | Trevor S |
| 049 | Python | 161021T123711Z | Stefan |
| 011 | CJam | 161019T171531Z | Neorej |
| 081 | Java | 161019T144233Z | AxelH |
| 081 | Factor | 161018T193820Z | cat |
| nan | GNU sed | 161019T222029Z | Doomsday |
| 010 | Pyth | 161020T020734Z | Steven H |
| 051 | Python 2 | 161019T184820Z | biowease |
| 074 | Bash / sed | 161019T203329Z | Doomsday |
| 036 | Groovy | 161019T130749Z | Magic Oc |
| 016 | k | 161019T173757Z | skeevey |
| 025 | Perl | 161018T204219Z | Dada |
| 8179 | Java 7 | 161018T192129Z | Numberkn |
| 063 | PHP | 161018T191717Z | Jör |
| 025 | Brachylog | 161019T123718Z | Emigna |
| 046 | Scala | 161019T134747Z | corvus_1 |
| 043 | Mathematica | 161018T221657Z | freddiek |
| 013 | Gema | 161019T084558Z | manatwor |
| 082 | SWIProlog | 161019T120013Z | Emigna |
| 129 | Acc!! | 161019T070829Z | DLosc |
| 036 | Zsh | 161019T052730Z | LinusKro |
| 023 | Perl | 161019T044533Z | Ton Hosp |
| 040 | Python 3 | 161019T021522Z | vpzomtrr |
| 027 | Turtlèd | 161019T020423Z | Destruct |
| 029 | Ruby | 161018T184409Z | anna328p |
| 032 | C# | 161019T012414Z | milk |
| 016 | MATL | 161018T193945Z | Luis Men |
| 097 | BrainFlak 97 Bytes | 161018T195917Z | Riley |
| 089 | C | 161018T195549Z | cat |
| 009 | Pyke | 161018T213543Z | Blue |
| nan | Perl 5 | 161018T212030Z | simbabqu |
| 061 | R | 161018T204213Z | jmartind |
| 018 | ><> | 161018T204957Z | Martin E |
| nan | Perl 5 | 161018T203017Z | simbabqu |
| nan | Perl | 161018T203726Z | Sake |
| 009 | Pyth | 161018T204951Z | Maltysen |
| 037 | ><> | 161018T203608Z | Emigna |
| 027 | Ruby | 161018T203804Z | m-chrzan |
| 017 | Vim | 161018T195223Z | udioica |
| 010 | Convex | 161018T195012Z | GamrCorp |
| 018 | 05AB1E | 161018T184944Z | Luke |
| 013 | J | 161018T192141Z | miles |
| 030 | Haskell | 161018T191631Z | nimi |
| 017 | Retina | 161018T184015Z | Martin E |
| 019 | APL | 161018T191054Z | marinus |
| 011 | 05AB1E | 161018T190858Z | acrolith |
| 044 | Brainfuck | 161018T190240Z | user5946 |
| 088 | Lua | 161018T185652Z | IDid |
| 046 | PowerShell v2+ | 161018T184255Z | AdmBorkB |
APL(NARS), 28 chars
{1≥≢⍵:⍵⋄(↑⍵),'(',(∇1↓⍵),')'}
test:
f←{1≥≢⍵:⍵⋄(↑⍵),'(',(∇1↓⍵),')'}
f 'Hello'
H(e(l(l(o))))
f 'Hello world!'
H(e(l(l(o( (w(o(r(l(d(!)))))))))))
Pip, 12 bytes
POa.:a&pJREa
Explanation
Different approach from The Thonnu's 12-byte solution, which you should also upvote.
POa.:a&pJREa
POa Pop the first character from the argument
.: Concatenate it to the following:
a& If the remainder of the argument is falsey (""), return it; else,
REa Recurse on the remainder of the argument
pJ Join p (builtin for "()") on the result
tinylisp 2, 44 bytes
(d F(\(s)(c(h s)(?(t s)(,(,"("(F(t s)))")")"
Explanation
(d F(\(s)(c(h s)(?(t s)(,(,"("(F(t s)))")")""))))
(d F ) ; Define F as
(\(s) ) ; A function of s:
(c(h s) ) ; Cons head of s to...
(?(t s) ) ; Is tail of s nonempty?
(,"(" ) ; Concat open paren to
(F ) ; Recursive call
(t s) ; On tail of s
(, ")") ; Concat that to close paren
"" ; Otherwise, empty string
Jelly, 9 8 7 bytes
Uses a modified form of Lyxal's 8 byte suggestion from 2021.
L’Ø(xż@
A full program that accepts a string and prints to stdout.
How?
L’Ø(xż@ - Link: list of characters, S e.g. ['a','b','c'] (from input "abc")
L - length {S} 3
’ - decrement 2
Ø( - literal ['(',')'] ['(',')']
x - {['(',')']} times {len(S)-1} ['(','(',')',')']
ż@ - {S} zip with {that} [['a','('],['b','('],['c',')'],[')']]
- implicit, smashing print a(b(c))
Original
At the time of posting, features newer than the question were not allowed to be used.
-1 byte thanks to @Dennis (use mould, ṁ, in place of length, L, and repeat, x)
j”(³”)ṁṖ
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))))))))
Brachylog, 19 bytes
l₁|⟨hc{b↰₀;")("c↻}⟩
Explanation
Recursion in Brachylog can be a bit fiddly, but I'm fairly happy with how this turned out.
l₁|⟨hc{b↰₀;")("c↻}⟩
l₁ Base case: if the input's length is 1, return it unchanged
| If that case fails, recursive case:
⟨ c ⟩ Concatenate
h The head (first character)
{ } with the result of this nested predicate:
b Behead (remove first character)
↰₀ Call the 0th predicate (the whole line) recursively
;")("c Concatenate the result with ")("
↻ Rotate the last character to the beginning
Dyalog APL, 13 chars
⊃{∊⍺⍵,¨'()'}/
{ }/ Reduce over input
,¨ Concat each
⍺⍵ the strand of left and right args
'()' with the parens
∊ Flatten
⊃ And disclose the result
Bespoke, 252 bytes
given my string to nest:a(b)I blindly printed first of it
then repeated bracket nesting,as all my text characters raised my number of brackets
bracket,then a further character
if I do last,bracket after end is used,a number of repeated instants as seen
I rarely ever use the CONTROL OTHERWISE command in golfed Bespoke programs, but in this case, it let me omit three CONTROL ENDs that occur at the end of the program.
AWK, 38 bytes
{for(s=$NF;NF>1;)s=$(--NF)"("s")"}$0=s
{for(s=$NF; # catches if only one char
NF>1;) # going backwards
s= # set string
$(--NF)"(" # to previous char, parens
s")"} # string, and another parens behind
$0=s # set default output to string s
Brainfuck, 42 40 bytes
>+[-->+[<]>-]>+>>,.,[<+<.>>.,]<<+>[-<.>]
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
]
Thunno 2, 10 bytes
'(j$l⁻')×+
Explanation
'(j$l⁻')×+ # Implicit input
'(j # Join the input by "("
$l⁻ # Length of input minus one
')× # Multiplied by ")"
+ # Concatenate the strings
# Implicit output
TypeScript's Type System, 212 73 bytes
type X<S>=S extends`${infer A}${infer B}`?B extends""?A:`${A}(${X<B>})`:S
- Remove three redundant types (Jacob)
Pip, 15 12 bytes
OaJ'(')X#a-1
-3 thanks to @DLosc
Explanation
OaJ'(')X#a-1 ; Input on command line
a ; The input string
J ; Joined by
'( ; The character "("
O ; Output and pass through
') ; The character ")"
X ; Repeated this many times
#a ; Length of input
-1 ; Minus one
; Implicit output
Old:
(aJ'().')X(D#a) ; Input on command line
a ; The input string
J ; Joined by
'( ; The character "("
( ). ; Concatenated with
') ; The character ")"
X( ) ; Repeated this many times
#a ; Length of the input
D ; Minus one
; Implicit output
Arturo, 44 bytes
f:$[s]->(one? s)?->s->~«|s\0|(|f drop s 1|)
f:$[s]-> ; a function named f taking an argument s
(one? s)? ; does s have a length of one?
->s ; then return s
-> ; otherwise return
~« ; interpolated string that spans the rest of the line
|s\0| ; first character in s
( ; followed by open paren
|f drop s 1| ; followed by calling f on s without its first char
) ; followed by closing paren
JavaScript (Node.js), 35 40 bytes
Only 2 bytes above the best JS answer! (using array of characters as input, as OP apparently allowed in his comments)
s=>s.reduceRight((a,e)=>e+`(${a})`)
The reduceRight combines the advantage of the reduce (n-1 iterations for n items, because in the output there is always one less couple of parenthesis than characters) with a reverse (necessary in this approach for accumulating the nesting by starting with the end)
Nibbles, 8 bytes (16 nibbles)
`)+.$:"("$^,@")"
# first string:
. # map over
$ # input:
: # join
"(" # "("
$ # to each element
+ # flatten this list
`) # and remove the first element;
# second string:
^ # replicate
")" # ")"
,@ # length of input times
# (and the two strings are printed
# one-after-the other in the output)
TI-Basic, 62 64 bytes
For(I,1,2length(Ans)-2,2
sub(Ans,1,I)+"("+sub(Ans,I+1,length(Ans)-I
End
For(I,1,.5length(Ans
Ans+")
End
Ans
Takes input in Ans. Output is displayed and stored in Ans.
Thunno D, \$ 12 \log_{256}(96) \approx \$ 9.88 bytes
'(sjsL')*+ZH
Explanation
'(sjsL')*+ZH # Implicit input
sj # Join the input by...
'( # The "(" character
sL # Push the length of the input
* # And multiply it by...
') # The ")" character
+ # Add these together
ZH # And remove the last character
# Implicit output
KamilaLisp v0.2, 32 (APL SBCS)
$(⌿.← \λ(x y)\⍫∊ "{?y}({?x})")∘⌽
Equivalent to $(foldl1 \lambda(x y)\str:format "{?y}({?x})")@reverse.
Vyxal, 7 bytes
÷!‹(øb+
÷ # Push each to the stack
!‹( # (input-1) times...
øb # Parenthesise what's currently on the stack
+ # and append it
ayr, 20 bytes
(:1},;'(',"),')'#}&#
Explained
}&# Length - 1
')'# Repeat ')' that many times
, Append to end of
(: xx) The result of applying input to partial application xx
Where xx is:
'('," Append '(' to beginning of each char
,; Convert from vec of strs to str (mix before flatten)
1} Remove first char
Vyxal, 7 bytes
L‹k(*sY
Get gamed on @emanresuA
Explained
L‹k(*sY
L‹ # Push the length of the input, but decremented
k( # Push "()"
* # and repeat it ↑↑ times
s # sort that
Y # and interleave it with the input
Underload, 18 bytes
(~*a~a:*~a*^~):()~
Takes input as a reversed list of characters.
Explanation
Arbitrary-length list handling is a little weird in Underload.
Typically, inputs are passed in the form (a)~(b)~(c)~^S with the assumption that there is a function on the stack. This pushes each input one at a time and then swaps them with the function, keeping the function on top, then finally executes the function and prints the top of the stack.
For arbitrary-length lists however, we need to make 2 changes.
Firstly, the function must be self-replicating, and must operate on each individual item on the stack.
Secondly, inputs must be passed in the form (a)~^(b)~^(c)~^!S
This executes the function after each input, with the expectation that after the function is run, the top of the stack will be the function. (^ pops the function from the stack before execution).
(~*a~a:*~a*^~):()~
( ) Main function
~ Swap the top two items on the stack
* Concatenate them
a Wrap the result in parentheses
~a:*~a*^~ Function self-replication.
Assumed that the top of the stack is the result of the function
and the 2nd item is the function.
ie for stack [f, a], produces [f, a, f]
:()~ Duplicate function and push an empty string between them
Resulting stack when execution begins is
['~*a~a:*~a*^~', '', '~*a~a:*~a*^~']
Python 3, 51
Just a simple recursive function.
lambda s:s if len(s)<2else s[0]+"("+nest(s[1:])+")"
Zig, 84 bytes
fn p(q:var)[]const u8{return[_]u8{q[0]}++if(q.len>1)"("++p(q[1..q.len])++")"else"";}
tests:
fn p(q: var) []const u8 {
return [_]u8{q[0]} ++ if (q.len > 1) "(" ++ p(q[1..q.len]) ++ ")" else "";
}
const std = @import("std");
const Test = struct { in: []const u8, out: []const u8 };
test "it works" {
comptime const tests = [_]Test{
.{ .in = "Hello", .out = "H(e(l(l(o))))" },
.{ .in = "foobar", .out = "f(o(o(b(a(r)))))" },
.{ .in = "a", .out = "a" },
};
inline for (tests) |i| {
std.testing.expect(std.mem.eql(u8, comptime p(i.in), i.out));
}
}
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.
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
Burlesque, 16 bytes
'([]sa2./')j.*.+
'([] # Insert "(" between each char
sa2./ # Find length/2
')j.* # That many ")"s
.+ # Concatenate
05AB1E, 11 10 bytes
-1 byte thanks to @Kevin Cruijssen
S'(ý?¨v')?
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
Befunge-93, 33 bytes
~# <\,"()"_v#+1:~,
:,_@#
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.
Wren, 54 bytes
Fn.new{|x|x.map{|i|i+"("}.join()[0..-2]+")"*~-x.count}
Wren, 36 bytes
I didn't write this myself. Therefore it is boring.
Fn.new{|x|x.join("(")+")"*~-x.count}
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
?!&("\()_^`)`&*
-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
?!&("\()'^_`)`&*
-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|\))^(,
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
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
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.
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));}
Gol><>, 21 bytes
TiE!tlF`(}}|~l2,R`)rH
24 bytes
TiE!trlF}8ss}|r~l2,R`)rH
It's hideous, I know. I am going to golf this profusely.
Forth (gforth), 66 58 bytes
: f over 1 type 1 -1 d+ dup 0> if ." ("recurse ." )"then ;
-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
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)
JavaScript (ES6), 40 34 33 bytes
Saved 6 bytes, thanks to ETHproductions
A recursive function.
f=([c,...s])=>s+s?c+`(${f(s)})`:c
C++, 66 bytes
[&](string s){return s[1]?s.substr(0,1)+"("+f(s.substr(1))+")":s;}
Matlab, 45 bytes
@(s)fold(@(x,y)strcat(y,'(',x,')'),fliplr(s))
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.
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
Gol><>, 37 bytes
14a*iov
!vo$P$>:oi:P?
:>~~:?!;9sso1-:
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 '~'
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)}
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!
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
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
R, 56 bytes
function(s)c(paste(s,collapse="("),rep(")",length(s)-1))
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)
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.
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
Japt, 11 bytes
ç q') iUq'(
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.
Implicit, 24 23 bytes
~@~.(0-1@40@~.);;(0@41;
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)
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+@)
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.
Ly, 50 bytes
iyspr1[1[=!["("o1$]p1$]1[=[pp2$]p1$]o]l1-[")"o1-];
This is ridiculous. Ly is lacking severely in the string manipulation department.
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
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())}
Groovy, 46 bytes
{it.reverse().inject{r,i->")$r($i"}.reverse()}
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.
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;}
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
Brain-Flak, 118 84 + 1 = 85 bytes
([[]]<{({}<>)((((()()()()()){}){}){})<>}>()){({}()<(<>({})<>())>)}{}<>{}{({}<>)<>}<>
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
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))))"
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.
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) \))))))
Python, 41 39 34 bytes
lambda e:"(".join(e)+")"*~-len(e)
Pretty self explanatory.
It puts a parenthesis between every other character then adds one less than the length parentheses to the end.
Dyalog APL, 14 bytes
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
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.
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))))))))
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.
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));
}
}
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.
Iis raw input, read from STDIN as a string.'(is the character literal(.- The
{(left identity) takes'(andIas inputs, and returns'(. The return value is never actually used. `is thread. It modifies{to return the character(for each character ofI, resulting in a string of(s with the same length asI.>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'(andI), and calls the funtion with them. This inserts the character(between every pair of characters inI.,concatenates this string with the string of)s, andPprints the result.
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.
Actually, 10 bytes
lD')*ß'(j+
Explanation:
lD')*ß'(j+
lD')* ")"*(len(input)-1)
ß'(j insert a "(" between every pair of characters in the input
+ append the closing parens
Scala, 58 bytes
"Hello world!"match{case s =>s.mkString("(")+")"*s.length}
Could be shorter
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
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(!)))))))))))
Factor, 81 bytes
[ [ >array [ 1string ] map "("join ] [ length 1 - [ 40 ] replicate >string ] bi ]
GNU sed, 37 35 31 bytes (30 +1 for -r argument)
Pure linux sed solution
:;s/([^(])([^()].*)$/\1(\2)/;t
- Naming the subsitution
:; then calling it recursively witht - 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
- Add parenthesis around the second group
\1 ( \2 )
Edit: Thanks to @manatwork for helping removing 4 characters!
Pyth, 10 characters
+j\(Q*\)tl
Joins the input on (, and appends length - 1 closing parens afterwards.
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)))))))'
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
xandztruncated of one character.
To test, put this code into a file, and run the shell script with any arguments.
Groovy, 38 36 Bytes thanks to @manatwork
{it.reverse().inject{r,i->i+"($r)"}}
Yeah, the C&P messed up the first time.
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))))))))))"
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)
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;}
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,")");
Brachylog, 35 28 25 bytes
l-L,")":LjkC,?:"("zckc:Cc
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
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 ")"
)
Mathematica, 45 43 bytes
#2<>"("<>#<>")"&~Fold~Reverse@Characters@#&
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(!)))))))))))
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.
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!
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
- Assign all but the first character of the first argument to a variable z
- Print the first character of the input
- Print z, with "the empty string replaced with (" which actually places a ( before each character of z
- 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.
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
Python 3, 40 chars
s=input()
print("(".join(s)+len(s)*")")
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
Ruby, 41 29 bytes
->s{s.split("").join(?()+?)*(s.length-1)}
->s{(s.chars*?()+?)*~-s.size}
Thanks @ValueInk
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
)
;
MATL, 16 bytes
t~40+v3L)7MQ3L)h
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
Brain-Flak 103 97 Bytes
Includes +3 for -c
{({}<><(((((()()){}()){}){}){})>)<>}<>({}<([][()]){({}[()()]<(({})()<>)<>>)}{}>){({}<>)<>}<>{}
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 (
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++;}
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
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.
><>, 19 18 bytes
io8i:&0(.')('o&!
o
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.
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))))
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)
><>, 37 bytes
i:0(?\'('
$,2l~/~
/?(2:<-1$')'
>~ror:
Row by row
- Pushes each char from input with an opening parenthesis after each
- Removes EOF and the last opening parenthesis and pushes the stack length
- Uses a comparison with half the stack length to push the closing parenthesis
- Prints the content of the stack
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
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.
05AB1E, 22 21 19 18 bytes
¤Ug<©FN¹è'(}X®')×J
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
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
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 ).
Retina, 22 17 bytes
\1>`.
($&
T`(p`)_
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.
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
}
05AB1E, 11 bytes
S'(ý¹g<')×J
Explanation:
S'(ý join input by "("
¹g< push length of input - 1, call it n
')× push a string with char ")" n times
J concatenate
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.
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.
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 ).
