[Question]
  [
*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
```
(Hello world!)
```
* Then, take the remaining center `n-2` characters, and surround them in square brackets. In this case, the center 10 characters are `ello world`, so the next iteration is:
```
(H[ello world]!)
```
* As long as there are more than two characters left in the middle of the string, repeat the last two steps, alternating between `()` and `[]`. 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
```
(H[e(l[l(o[ w]o)r]l)d]!)
```
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:
```
(H[e(l[l(o[,( )w]o)r]l)d]!)
```
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](/questions/tagged/code-golf "show questions tagged 'code-golf'") competition, so try to make the shortest possible answer in the language of your choice. Have fun!
## Test IO
```
#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( [1]6) ]2)3] )4]2)
"a"                     --> (a)
"ab"                    --> (ab)
"abc"                   --> (a[b]c)
```
  
[Answer]
# [Python 3](https://docs.python.org/3/), ~~70~~ ~~69~~ 65 bytes
*-1 byte thanks to @Uriel*  
*-4 bytes thanks to @xnor*
```
f=lambda s,b=0:s and'(['[b]+s[0]+f(s[1:-1],~b)+s[1:][-1:]+')]'[b]
```
[Try it online!](https://tio.run/##FY49C4MwGIT3/orr9Caoxa@WErBQHLq6hwyKxgoaxaRDEfvXrS5398DB3fR179Ek26azvhyquoT1qywUFqWpiUmSlfKsDJWnmZWRCCLl/yruHVnJYBePuDpamx5nWHQGkp69a2bTWNeZFp2F/pgz@aCiyF@H52PdBO3Y6wNS3BFdEd0QJ0hjUuIETHNnHKNFxOGK4IFlpcs@MJSOWR/7F8759gc "Python 3 – Try It Online")
[Answer]
# C, ~~143~~ ~~137~~ 135 bytes
```
i,l,k;f(char*s){for(k=i=0,l=strlen(s);*s;printf("%c%c","([])"[i++%2+2*(i>l/2+!k)],*s++))i>l/2-1&&l&1^1&&putchar(*s++,k=++l);puts(")");}
```
[Try it online!](https://tio.run/##TY3BisIwEIbvPsUYaJlpUnYbXVkIXVg87NW7uCCx6YbGVJJ4Ep@9mwqCc/mZ7xvm13Wv9TRZ4cSgDOq/Y6gi3cwYcGht@y5cG1NwncdIqorqEqxPBlmhC80Ew/2B2N5yXkguK7Rf7k3y5UAHUUXOiR6gbsrSlc1vjss1zRU4WzG0nDtSmUVkxEjdp/wczkfrkRa3BeTJVd8udcF3MVnfg41grn6Zj596t9v@vKzb8dTV/ejMC1vDJzQf0GxArmAtZ3Of/gE)
**Explanation:**
```
// Function (and variable) declaration.
i,l,k;f(char*s){
// Start the loop and initialize the variables. The loop terminates
// when the NUL-terminator of the string is reached.
for(k=i=0,l=strlen(s);*s;<this part saved for later>)
// Check if we have reached the middle of the string. Because of the
// short-circuiting of the conditions, we don't need to use an 'if'
// statement here; if a condition is false, no further conditions
// are evaluated.
i>l/2-1&&
// Equivalent to '!(l%2)', but one byte shorter. Checks if the length
// of the string is even.
l&1^1
// If we have reached the middle and the length of the string is even, 
// we'll need to skip one bracket, so we'll print the current character
// of the string and increment the pointer. Also we increment 'l' to
// avoid this getting done more than once, and give 'k' a non-zero
// value.
&&putchar(*s++,k=++l);
// The following is inside the 'increment' part of the 'for' loop.
// We print two characters. The first one is a bracket and the second
// one is the current character in the string.
printf("%c%c","([])"[i++%2+2*(i>l/2+!k)],*s++)
// The type of bracket is  chosen depending on the value of 'i'. A 
// character from the string "([])" is selected with the index 'i%2 + 2', 
// if we have reached the  middle of the string, and with index 'i%2', if
// we haven't.
// The exact part where this change happens depends on the parity of 
// the string length, so we use 'k' to signal if the length is even or 
// odd. If the length is odd, 'k==0', so '+!k' is the same as '+1'.  
// Otherwise 'k' is non-zero, so '+!k' is the same as '+0'.
// Output the final ')'.
puts(")");}
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 52 bytes
```
+`(?<!\()[^()]+(?!\))
($&)
(\(.)\(
$1[
r`\)(.\))
]$1
```
[Try it online!](https://tio.run/##K0otycxL/P9fO0HD3kYxRkMzOk5DM1Zbw14xRlOTS0NFDUjEaOhpxmhwqRhGcxUlxGhq6IGkYlUM///3SM3JyVcozy/KSVEEAA "Retina – Try It Online") The first stage inserts pairs of parentheses between each pair of input characters, while the second and third stages correct alternate parentheses to brackets.
[Answer]
# JavaScript (ES6), ~~69 68~~ 62 bytes
*-6 thanks to [@Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)*
```
f=([c,...s],i,l=s.pop()||s)=>c?'[('[i^=1]+c+f(s,i)+l+'])'[i]:s
```
[Try it online!](https://tio.run/##dY9Ba8MwDIXv@xWqL5VImpI0LWWQjZJDr7kbDRI3Dh7GLnW6U/975sNgI1kFQkK89/H02X61Qd3Mddw4f@mnSVcoVZplWeDUpLYK2dVfkR6PQNWbel9LXEvzUeWcqERjSA0lNlkzxSu/hkl5F7ztM@sH1ChOduxvrg@jcQOYAPruVoIItlvAk7Q4yh5v0mEvQ9yN44GADQUG0nwnxyt6mSGbpj4LmNUPspFNzeeFpY6fbQZvtVhaaunxElNsaGBPlvXCXcIR8j3kByh2UBbir7uUgMfYudwjyJwPMX5Buxi/jHNOahe5f0ntUt2J5@ruH7kST@WyY0XTNw "JavaScript (Node.js) – Try It Online")
[Answer]
# Sed, 78
Score includes +1 for `-r` option passed to sed.
```
s/.*/(&)/
:
s/(\(.)([^][]+)(.\))/\1[\2]\3/
t
s/(\[.)([^)(]+)(.\])/\1(\2)\3/
t
```
[Try it online](https://tio.run/##JcqxCsIwEADQPV9xLvZOaULSKuImHVy7JxGUprVQUujF748Y3/xeT35nDgPUG1SZlTwo3JMSV8EKHUpC@/DWHwmlI1JOW2e8a5RIJdgSCP/B/wI6QyXkKt@WFLYYOM1xgplh/MSd6PvuLrp1CPW0LqNo4QL6BPoMpoHWfAE).
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~25~~ ~~26~~ 25 bytes
~~1~~ 2 bytes off thanks to @DJMcMayhem
```
òC()Pé
%llòÍî
òF)%r[r];
```
[Try it online!](https://tio.run/##ATAAz/92///DskMoKRtQw6kKJWxsw7LDjcOuCsOyRiklclsPcl07//9oZWxsbG8gd29ybGQ "V – Try It Online")
Borrowed some of [@udioca's ideas.](https://codegolf.stackexchange.com/a/96665/62346) ~~Also finally used the [surround plugin](https://github.com/tpope/vim-surround) included in V for an answer, although it may not have been the best way, who knows.~~ The plugin does NOT want to be used.
Hexdump:
```
00000000: e3e1 0a6b f2e9 286c 6ce9 5b6c 6cf2 6af2  ...k..(ll.[ll.j.
00000010: e129 6868 e15d 6868 f2cd ce              .)hh.]hh...
```
Explanation:
```
-> |abcdefg      (the input, where | is the cursor)
ò              ' recursively
 C()           ' (C)hange from the cursor to the end of the line to '()'
-> (|)    (where | is the cursor)
     P         ' (P)aste the changed bit (what was there) left of the cursor
-> (abcdef|g)
      é        ' nsert a newline
-> (abcdef
   |g)
%              ' Goto the previous matching parenthese
-> |(abcdef
   g)
 ll            ' Move two characters right
-> (a|bcdef
   g)
   ò           ' End recursive loop (it will break on ll when there are no characters left
-> (a(b(c
   d)
   e)
   f)
    Íî         ' Remove all newlines
-> (a(b(cd)e)f|)
ò              ' Recursively
 F)            ' Go backwards to the next )
-> (a(b(cd)e|)f)
   %r[         ' Go to the matching paren and (r)eplace it with [
-> (a|[b(cd)e)f)
               ' Go back to the previous cursor location
-> (a[b(cd)e|)f)
       r]      ' (r)eplace this paren with ]
-> (a[b(cd)e|]f)
         ;     ' repeat F)
-> (a[b(cd|)e]f)
               ' implicitly end recursion
```
[Answer]
# [Haskell](https://www.haskell.org/), 96 91 81 79 77 bytes
```
(cycle"()[]"!)
(l:r:a)!k|[x]<-k=[l,x,r]|x:y<-k=l:x:a!init y++[last y,r]|2>1=k
```
[Try it online!](https://tio.run/##FclBC4IwGIDhu7/ic14UNajjaIFIeLEQotOSGDZt@DlFJyjZb7e8vQ/vWwy1RFw/oQNpdE3uUXKGOMvACb@WYI/VLeYCJXE9nhPbs1ykPRWeXS98yo9hzTgGU9Dny0TnjUgnKmyllYHZ9zmK4R/bP5z2rF4boTQwaER3eYLbjeZm@lTDDoQHnERoZK/lYJSuQA1QjtomAZC4fcmwarEk@foD "Haskell – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 79 77 bytes
-2 bytes thanks to @Value Ink
```
->s{z=s.size
(z/2+z%2).times{|i|s.insert k=i*2,'(['[i%2]
s[~k]+=')]'[i%2]}
s}
```
[Try it online!](https://tio.run/##NcmxCsIwEADQPV8Rh3KttRGyRxA/I2QRL@VoTUsvGUxbfz0K4vreku6v4k3pLrxmw4opo6jzWbe50o2K9EReN9pYUWBcohwMHfUJaguWKu0E2/fgWgON@8EueC9ziiy9hesYcQnIkUIv6UspHMCJf9@mB3b9NHpw5QM "Ruby – Try It Online")
[Answer]
# Javascript(ES6) 110 105 bytes
Thanks to @powelles for reminding me about `x%y<1`.
Thanks @Luke for `a-b?y:x`
```
i=>'('+[...i].map((a,b,c,d=i.length/2-1,e=b%2<1)=>a+(d>b?e?'[':'(':d-b?(d%1==0?!e:e)?')':']'):'').join``
```
```
let f=i=>'('+[...i].map((a,b,c,d=i.length/2-1,e=b%2<1)=>a+(d>b?e?'[':'(':d==b?'':(d%1==0?!e:e)?')':']')).join``
```
```
<input onkeyup="result.textContent = f(this.value)"/>
<p id="result"></p>
```
---
The first thing in understanding this beast is ungolfing it:
```
function alternest(input) { //input is i in the original
  let inputArray = Array.from(input); //the [...i] section
  let result = inputArray.map((item, index, baseArray) => { //result is an added helper variable
    let middle = input.length / 2 - 1, //the middle of the string
        alternate = index % 2 == 0; //should you alternate from '(' and '[' or ')' and ']'
    let symbol; //the alternating symbol
    if(middle > index) { //if its opening braces
      symbol = alternate ? '[' : '(';
    } else if(middle < index) {
      if(middle % 1 === 0) //if middle is a whole number
        alternate = !alternate; //reverse alternate
      symbol = alternate ? ')' : ']';
    } else { //if middle === index
      symbol = ''; //there's no symbol in the center for even alternests
    }
    return item + symbol; //convert the array item into the item and symbol
  }).join('');
  return '(' + result; //add the first symbol.
}
```
Almost every line is a part of the golfed version, so stepping through:
**Line 1:** The function statement becomes an [arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions), renaming `input` to `i`. Becomes `i=>`.
**Line 2:** `Array.from` is the new, proper way of converting a string into an array, and what we use in on this line. However along with it, the [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator) is a cheaper way than the old `.split('')` way, to do it, which is what is used in the golfed version. Ends up as `[...i]`.
**Line 3:** [`.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) loops through an array, giving you three arguments: `item`(`a` in the golfed), `index`; golfed as `b`, and `baseArray` or `c`. While we only care about `item` and `index`, we kept `baseArray`(see line 4 for why). Golfs to `.map((a,b,c,...)=>...`.
**Line 4:** The variable `middle`, the or the argument `d` in the golfed version is created to save a few bytes when it is repeated. The argument `c` had to be kept for argument `d` to be created. Is converted to `(...,d=i.length/2-1,...)`.
**Line 5**: The variable `alternate`, or argument `e` is used to check what character it was on "(" or "[" or if it was past the middle, ")" and "]". `b%2<1` is equal to `b%2==0` because it can't be anything less than 1, but 0 in this case. Equals `(...,e=b%2<1)`.
**Line 6:** A helper variable to allow me to convert the [`ternary operators`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) to `if` statements. Isn't anything in the actual codegolf.
**Lines 7-8**: If the index is less than the middle of the string set the symbol to an alternation of "[" and "(". Equates to `d>b?e?'[':'(':...`.
**Lines 9-12**: Else (if index is greater than middle), check if middle is a whole number, if so switch the alternation. Then set the symbol to an alternation of ')' and ']'. Obfuscated to `(d%1==0?!e:e)?')':']'`.
**Lines 13-15**:If the in the middle set the symbol to an empty string. This doesn't apply to odd alternesters, because middle has a decimal. Becomes: `d==b?'':...`.
**Line 16**: Joins the character array back into a string. Equates to `.join```.
**Line 17**: Returns the starting symbol "(" and the result. Correlates to `'('+...`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~23~~ 21 bytes
```
LHĊRị
ç⁾)]żUFUż@ç⁾([$
```
[Try it online!](https://tio.run/##y0rNyan8/9/H40hX0MPd3VyHlz9q3KcZe3RPqFvo0T0OYK5GtMr///8dc0pSi/JSi0sy89IVMosV0krzFAE "Jelly – Try It Online")
```
LHĊRị           - helper function. Takes inputs of the input string and list of brace types
L                 - length of the input string
 HĊ               - number of parenthesis/brackets facing a single direction
   R              - range
    ị             - indexed into right argument: list of brace types ')]' or '(['
ç⁾)]żUFUż@ç⁾([$ - main function 
ç⁾)]              - get list of left-facing parentheses/brackets
    żU            - zip to the end (U) of the input string
      FU          - move the beginning of the string back to the beginning
        ż@        - zip with (to the start of the string):
          ç⁾([$   -the list of right-facing parentheses/brackets to the beginning
```
*-2 bytes thanks to @EricTheOutgolfer*
[Answer]
# SCALA, ~~140~~ 138 chars, ~~140~~ 138 bytes
I'm sorry I couldn't do better ... I'm sure there are many ways to improve it.
Still:
```
val n=s.length-1
var l=""
var r=""
for(i<-0 to n/2){l+=(if(i%2<1)"("else"[")
if(i!=n-i)l+=""+s(i)
r=""+s(n-i)+(if(i%2<1)")"else"]")+r}
l+r
```
[Try it online!](https://tio.run/##fY9BS8QwEIXP5lfMBoSEWt3WVUTMYdmDXoQFj4uHbDutkSEpSVyF0t9eW1fRSzzN473vwZtQadKj279iFeFRGwv4EdHWAdZd17OTGhvQFNFbDFGE26fojW3l91X9eNAEVoVzQtvGl7xgB@2BFOdfws@icV6Yu3wJ0YG9KGVPmRKmEea0VGopueBIAfmOSza7C2VzIyeG8ywII5k/qtnN/vbksffMZeYHRpkfB9ZNsyJZ8buZPyCRO4N356lecCmTzP/I@kdOf4MJ0LzZFLrdbu4T0cbVmLeOmkS@ghsorqC4hvISVmWC0il/nwyqORnGTw)
Thanks for this challenge, that was quite hard for me.
EDIT : -2 bytes thanks to Mar Dev.
PS : I will ask something though. I understand why [THIS CODE](https://tio.run/##VY4xa8MwEEbn6ldcBAUdrtvUY4mGbFkydSwdZPvsqBwnIwk3YPzbXbsJlE7fG94HLzWO3RLqL2oynJ0XoGsmaRMch2FSDy114DhTFErZpLf3HL30eF87LaNjEJuemaTPl/JVjS4CW61/IW7QhWj8odxDDiAvFU5suTC@M/6xsnaP2mjiRPpDY5GMR7W9VpLS4z8Pb97n6sVZcRGXWQ1rR2Yxf5H6RMzhCVz9HSK3O42o5uUH) keeps duplicating the central char of my string if I have an odd length (I just don't check and add it twice, in both `l` and `r` strings). But why do I get a pair of parenthesis when I try correcting it like [THAT](https://tio.run/##VY49C8IwFEVn8yueASGh1q9RzODm4uQoDtG@1sjjpSRBhdLfXlsVxOkeLpzLjRdLtvPnG14S7K1jwGdCLiJs67oRowJLsJQwMMak4vqQguNKf9M03d0SsIkzQq7SNV@Kuw1ARso3hAFKH5Tb5AtIHni@0g0ZypQrlZusjFloqSRSRHmU@lOPDedOR@W0FsNCFtVQ/Dn645x6J7SCstC1ou4/JWL1Oyx3SOSnYM8PH6gYy36x7V4)? I don't understand at all.
[Answer]
# Perl, ~~77~~ 74 (73 + 1) bytes
Regular expressions are glorious things. Run with the `-p` command line flag.
```
$x=qr/[^]()[]/;$z=qr/(^|$x)\K($x+)($|$x)/;s/$z/[$2]$3/ while s/$z/($2)$3/
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 31 bytes
```
2ä`Rð«„)]Ig©×øRJ®Èƒ¦}s„([®×søJì
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f6PCShKDDGw6tftQwTzPWM/3QysPTD@8I8jq07nDHsUmHltUWAyU0ooHc6cWHd3gdXvP/v2NOSWpRXmpxSWZeukJmsUJaaZ4iAA "05AB1E – Try It Online")
**Explanation**
With examples for input: `abcd` / `abcde` 
```
2ä`                              # split input to 2 separate parts on stack
                                 # RESULT: 'ab','cd' / 'abc', 'de'
   R                             # reverse the second part
    ð«                           # append a space
      „)]                        # push the string ")]"
         Ig©×                    # repeat it len(input) times
             ø                   # zip with the second part of the input string
              RJ                 # reverse and join to string
                                 # RESULT:  ' )c]d)' /  ' )d]e)'
                ®Èƒ¦}            # remove the first (1,2) chars for (odd,even) length input
                                 # RESULT: 'c]d)' / ')d]e)'
                     s           # swap the first part of the input string to top of stack
                      „([®×      # repeat the string "([" len(input) times
                           sø    # zip with first part of input string
                                 # RESULT: ['(a', '[b'] / ['(a', '[b', '(c']
                             Jì  # join to string and prepend to the second part
```
[Answer]
# C++ 14, ~~154~~ ~~145~~ 134 bytes
(Thanks to ideas by ceilingcat for extra bytes 145->134)
[Recursive]
```
#include <regex>
using S=std::string;S L(S i,int b=1){int l=i.size();return"(["[b]+(l<3?i:i[0]+L(i.substr(1,l-2),!b)+i[l-1])+"])"[b];}
```
# C++ 14, 177 bytes
[Iterative]
```
auto l(string s){int z=s.length();string r(z*2+z%2,'-');int i=0;for(;i<z;i+=2)r[i]=i/2%2?'[':'(',r[i+1]=s[i/2];for(i=z;i<2*z;i+=2)r[i]=s[i/2],r[i+1]=(i+1)/2%2?')':']';return r;}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 57 bytes
```
f=->s,i=0{a,*b,c=s;a ?["(["[i],a,*f[b,~i],*c,")]"[i]]:''}
```
[Try it online!](https://tio.run/##fZDBasMwDIbveQrVO9QOTlnatJSNdJQces1d6BCncWbInBIn0NFur545YzA2SgVCQny/9KNuUO/jqNNo56RJHy@FDJUsU/dcwAsyjgwNST/UqOSnb8NSMkHTlJ7m848RA7Zv@qqzleuNrcE40IOdMQD5EEU74HtseI8V79DyCp3vjaVaABnhCISmQViaiYDleXbwsv/xsybHPKODx7L2WEV122h2C8uw5Ud/LRI1taIh7RUJbCFeQ7yB5QqSJfurSBD41meMaw4Y08ZbW4qVt5b4GrDihqdfdTERit0j1DdSsjsIKipFQIu34nS5nq8n0HhelK9F5yicnvwF "Ruby – Try It Online")
Recursive function similar in spirit to ovs's [Python answer](https://codegolf.stackexchange.com/a/128899/78274). Inputs and outputs arrays of characters.
Note that we could shave off 3 more bytes, and in the test suite on TIO, where we join the arrays back to strings, the visible result would look unchanged:
```
f=->s,i=0{a,*b,c=s;a ?["(["[i],a,f[b,~i],c,")]"[i]]:p}
```
However, this would produce nested arrays and nils in the raw output, which is probably too weird for a "reasonable" output format.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 42 (!) bytes
```
M?!lHH+@,\[\(G++hHg!GPtH+?qlH1keH@,\]\)Gg1
```
[Test it online!](https://pyth.herokuapp.com/?code=M%3F%21lHH%2B%40%2C%5C%5B%5C%28G%2B%2BhHg%21GPtH%2B%3FqlH1keH%40%2C%5C%5D%5C%29Gg1&input=%22Code-Golf%22&debug=0) The input must be quoted.
**Explanations**
```
M                                             # Define a function g with arguments G and H
 ?!lHH                                        # If len(H) == 0, return H. Otherwise...
      +@,\[\(G                                # Concatenate [ or ( to...
               +hHg!GPtH                      # ...to H[0] concatenated to g(not(G), H[1:-1]), itself concatenated...
              +          ?qlH1keH             # ...to H[-1] if len(H) != 1, otherwise to "" (that's for odd length input strings)...
                        +        @,\]\)G      # ...and to that concatenate ] or ).
                                        g1    # Call g(True, Q). Q is implicit input
```
So basically I progressively remove the head and end of H (being the input string in the beginning) while concatenating the parentheses/brackets. G is just a boolean which remembers if I must use brackets or parentheses.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~49~~ 42 bytes
```
g;îD„([×s£©"s‚.Bøvy¬ðQi¦}}JR"DU.V®D∞sKRX.V
```
[Try it online!](https://tio.run/##AVAAr/8wNWFiMWX//2c7w65E4oCeKFvDl3PCo8KpInPigJouQsO4dnnCrMOwUWnCpn19SlIiRFUuVsKuROKInnNLUlguVv//SGVsbG8sIFdvcmxkIQ "05AB1E – Try It Online")
[Answer]
## PowerShell, 125 119 111 bytes
```
{param($s)for($p='()[]';($f,$s,$g=$s-split'(?<=.)(.+)(?=.)')[0]){$l+=$p[$i++]+$f;$r=$g+$p[$i++]+$r;$i%=4}$l+$r}
```
[Try it online!](https://tio.run/##RYoxa8MwGET/yle4VBJyTJO6oeAKEzJ0zW5MsVvJEai2kFwyuP7trpKlw909HufHqw7xop1b0al19m1ovzmiMGPg8IpxUTes5DAZYoZeIW6jd3ZivHpTueC5FLxKwET91IgZTir4GlbKRsKUCAq9/DehhN2oYkk/hGVlRzfpMOg42aEnG8n8DA8sY@fz6T3NafzS2350JnFBr7R7od2B9s9U7JNpb@nu9cl@N/MjoSN8LOsf)
Previous version\*
```
{for($s="($args)";$s-ne($t=$s-replace'(\(.)([^][]+)(.\))','$1[$2]$3'-replace'(\[.)([^)(]+)(.\])','$1($2)$3')){$s=$t}$s}
```
\*Thanks @Digital Trauma.
[Answer]
# [QuadR](https://github.com/abrudz/QuadRS), 82 bytes
(81 bytes +1 for `≡` flag)
```
(\(.)([^[])(.+?)([^\]])(.\))
(\(.)(..?)(.\))
^[^\(].*
\1[\2(\3)\4]\5
\1[\2]\3
(&)
```
[Try it online!](https://tio.run/##LYk7CoNAEED7OcWkCTMJWVBXSSfBIq29s8ImfhBkJX4OkWPkarnIRjHwivd4r8VWo/ckpJiKsjBM6pxuKmZzYYZ9KpX@u1wnGXUCCQoJSSIWbSTe00gEdGTvb/1cj66e5s612E3YLO4AeZ7dIRuq@tIOfQMarxjEGCQYRqhDsGAfK0//fX9@ "QuadR – Try It Online")
[Answer]
# AWK, 118 bytes
```
{b=")";for(j=l=length(c=$0);j>0;){x=substr(c,j--,1);b=(j>l/2?(((d=!d)?"]":")")x):j==l/2?x:((d=!d)?"(":"[")x)b}print b}
```
Tested with gawk, but it should work with any compliant awk interpreters
```
$ awk -f alternesting.awk <<< 'abc'
(a[b]c)
```
[Answer]
# JavaScript, 101 bytes
Not a winner, but it was interesting to try the `replace` approach. This could definitely be improved, but it got out of hand quick...
```
s=>"("+s.replace(/./g,(a,b)=>a+(l%2|b*2+2!=l?")][("[3*(c=l>(b+=l%2-1)*2+2)+(b-c*l)%2]:""),l=s.length)
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 124 bytes
```
c->{String s="";for(int l=c.length-1,a=l/2;a>=0;)s=(a%2<1?"(":"[")+(a<-~l/2?c[a]+s+c[l-a]:c[a])+(a--%2<1?")":"]");return s;}
```
[Try it online!](https://tio.run/##dZJRb9owEMff9ymulpBskWRLgKoiBISQ1odqK1IfLT8Y46Rhrp3ZTjVUsa/ODIR2o6ulKGf7d3f/v3wb/sxj00i9Wf/YN@1K1QKE4s7BN15rePkE4Dz34XQTyKT1tUrKVgtfG5187YKJeOSWsujB21pXUyih2It4@nLagysQyktjca09qEIkSurKP8ZpxAv1Ocv5tPiSE1dg3ssm6QxhNEYUkT7mk/h3AGaCctZ3fUFVzNn4sDtcxvEJJwFniORW@tZqcPluD2HlQXpnqHPwbOo1PAVb@CSMMuC2cuToEsBL5zGaKy@tDuFBee0gmL1CABHCc6qwpxJbqrGkLsS1ZhUBVhPHgJSsJZpdkaDkr3LL5eIWwbsVyi3pcsFuL/CFWcu4MqpEl/iCGrwO3WNSMUMUKy8yh3AD6QjSa8gGMMzQW@aQAr4JX0pHGGjKroPkjAyC5GH4/1uF/0frqQq/JFfoI3L1DhXoA5SumOjo3duoHR/qmHueIG8j6GL5q5HCy/X52bpjK12rPBRQJrxp1BaHnMSbRZjMubV8i0mn6WHrvHxKTOuTJmT6EqNenA3cGHrxcOSg53oaRaeW515RVz6RP1uuHH7VMEP3d2H8vhsP93eAUf9800evtnaHrvs/ "Java (OpenJDK 8) – Try It Online")
## Credits
* -2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 25 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ò≥◘■O║£/öτt≈K↔ì♂≈-⌂6=═°!b
```
[Run and debug it](https://staxlang.xyz/#p=95f208fe4fba9c2f94e774f74b1d8d0bf72d7f363dcdf82162&i=%22Hello+world%21%22%0A%22Hello,+world%21%22%0A%224+8+15+16+23+42%22&m=2)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 77 bytes
Not the best JS solution, but it could interest some people : this solution uses recursive calls with inversion of the 2 optional parameters at each step to alternate between `()` and `[]`
```
f=(s,a="()",b="[]")=>a[0]+(s[2]?s[0]+f(s.slice(1,-1),b,a)+s.slice(-1):s)+a[1]
```
[Try it online!](https://tio.run/##fczNCoMwEATge58i5rSLUWuPQtqr7xByiEkslsWIkdq3T3@gYKHtnIaB@S7maqKdh2kpxuB8Sr2EKIzkgFx0kivNUR6N2uscojroU3zWHmIZabAealHUKDphMH9Pj6GJmBtV62TDGAP5ksIZeuCtJwqCrWEml3FEVlX@Nnm7eMcaBq3yQIogKAEMVx1w1oROZ7j7Bm2cnxD7p5jXdZNPxWC6Aw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 28 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Initially inspired by [Arnauld's solution](https://codegolf.stackexchange.com/a/128920/58974).
```
V°g"()[]"ò)i1¢?UÌiUÎ+ßUs1J:U
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=VrBnIigpW10i8ilpMaI/VcxpVc4r31VzMUo6VQ&input=WwoiSGVsbG8gd29ybGQhIgoiSGVsbG8sIHdvcmxkISIKXS1tUg)
```
V°g"()[]"ò)i1¢?UÌiUÎ+ßUs1J:U     :Implicit input of string U
V                                :Second input variable, defaulting to 0
 °                               :Postfix increment
  g                              :Index, 0-based & modular, into
   "()[]"ò                       :  Length 2 partitions of string "()[]"
          )                      :End indexing
           i1                    :Insert at 0-based index 1
             ¢                   :  Slice first 2 characters off U
              ?                  :  If truthy (non-empty string) return
               UÌ                :    Last character of U
                 i               :    Prepend
                  UÎ             :      First character of U
                    +            :      Append
                     ß           :        Recursive call with argument (V is passed automatically)
                      Us1        :          U sliced from index 1 to index
                         J       :          -1
                          :U     :  Else return U
```
]