Alternesting, is the act of taking a string and nesting it in alternating brackets. Here is how you alternest a string.
For a string of length N, take the center N characters, and surround them in parenthesis. So if our string was
Hello world!(12 characters), we'll end up with
Then, take the remaining center
n-2characters, and surround them in square brackets. In this case, the center 10 characters are
ello world, so the next iteration is:
As long as there are more than two characters left in the middle of the string, repeat the last two steps, alternating between
. Here are the last steps:
(Hello world!) (H[ello world]!) (H[e(llo worl)d]!) (H[e(l[l(o[ w]o)r]l)d]!)
Since there are only two characters left in the middle on the last iteration, we stop. Our final string is
Note how there are two characters in the middle brackets. This happens when the input is an even length. If the input was an odd length (for example,
Hello, world!with a comma added), we would have only one character in the middle:
For today's challenge, you must write a program or function that takes a string as input, and alternests it, outputting the new string. You can take input and output in any reasonable format you like. The input will always be at least one character long, and will only contain printable ASCII. You can also assume that the input will not contain any parenthesis or square brackets. For traditional languages, this shouldn't matter too much, but it might make it easier for some esoteric languages.
As usual, this is a code-golf competition, so try to make the shortest possible answer in the language of your choice. Have fun!
#Input #Output "Alternesting is fun!" --> (A[l(t[e(r[n(e[s(t[in]g) ]i)s] )f]u)n]!) "PPCG" --> (P[PC]G) "Code-golf" --> (C[o(d[e(-)g]o)l]f) "4 8 15 16 23 42" --> (4[ (8[ (1[5( 6) ]2)3] )4]2) "a" --> (a) "ab" --> (ab) "abc" --> (a[b]c)