36
\$\begingroup\$

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 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)
\$\endgroup\$
  • \$\begingroup\$ Related \$\endgroup\$ – DJMcMayhem Jun 28 '17 at 17:44
  • \$\begingroup\$ Must we always start with parentheses (()) or can we start with brackets ([])? \$\endgroup\$ – totallyhuman Jun 28 '17 at 17:49
  • \$\begingroup\$ @totallyhuman It should always start with parentheses () \$\endgroup\$ – DJMcMayhem Jun 28 '17 at 17:50
  • \$\begingroup\$ Proposed testcase: HelloWorld. \$\endgroup\$ – Erik the Outgolfer Jun 29 '17 at 8:28
  • \$\begingroup\$ Also, are trailing spaces allowed? \$\endgroup\$ – Erik the Outgolfer Jun 29 '17 at 9:00

21 Answers 21

20
\$\begingroup\$

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

\$\endgroup\$
9
\$\begingroup\$

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!

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(")");}
\$\endgroup\$
  • \$\begingroup\$ If I remember C correctly, variables declared globally are initialised to 0. Thus, you shouldn't need the k=i=0,. I might be wrong. See this SO answer \$\endgroup\$ – Tas Jun 28 '17 at 21:29
  • \$\begingroup\$ @Tas You are indeed correct, but functions have to be reusable to be valid submissions, so the variables need to be initialized inside the function. \$\endgroup\$ – Steadybox Jun 28 '17 at 21:36
6
\$\begingroup\$

Retina, 52 bytes

+`(?<!\()[^()]+(?!\))
($&)
(\(.)\(
$1[
r`\)(.\))
]$1

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.

\$\endgroup\$
6
\$\begingroup\$

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.

\$\endgroup\$
6
\$\begingroup\$

JavaScript (ES6), 69 68 bytes

f=([c,...s],i,l=s.pop())=>'[('[i^=1]+c+(s[0]?f(s,i)+l:l||'')+'])'[i]

Test cases

f=([c,...s],i,l=s.pop())=>'[('[i^=1]+c+(s[0]?f(s,i)+l:l||'')+'])'[i]

console.log(f("Alternesting is fun!")) // (A[l(t[e(r[n(e[s(t[in]g) ]i)s] )f]u)n]!)
console.log(f("PPCG"                )) // (P[PC]G)
console.log(f("Code-golf"           )) // (C[o(d[e(-)g]o)l]f)
console.log(f("4 8 15 16 23 42"     )) // (4[ (8[ (1[5( [1]6) ]2)3] )4]2)
console.log(f("a"                   )) // (a)
console.log(f("ab"                  )) // (ab)
console.log(f("abc"                 )) // (a[b]c)

\$\endgroup\$
5
\$\begingroup\$

V, 25 26 25 bytes

1 2 bytes off thanks to @DJMcMayhem

òC()Pé
%llòÍî
òF)%r[r];

Try it online!

Borrowed some of @udioca's ideas. Also finally used the surround plugin 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
\$\endgroup\$
  • \$\begingroup\$ Wow, nice job! I was stuck at 29 bytes but missing a bunch of edge cases. This is a pretty sweet answer. You can save one byte by using ; instead of the last f) Try it online! \$\endgroup\$ – DJMcMayhem Jun 28 '17 at 19:03
  • \$\begingroup\$ It's actually broken right now because of spaces, I'm going to delete and fix \$\endgroup\$ – nmjcman101 Jun 28 '17 at 19:04
  • \$\begingroup\$ @DJMcMayhem Can I see your 29 byte one? Unless you plan to golf it under me and compete, which I wouldn't be surprised about :) \$\endgroup\$ – nmjcman101 Jun 28 '17 at 19:13
  • \$\begingroup\$ It doesn't work, so I don't mind showing you it: tio.run/##K/v///… Oh, and BTW: chat.stackexchange.com/transcript/message/38434285#38434285 :) \$\endgroup\$ – DJMcMayhem Jun 28 '17 at 19:17
  • \$\begingroup\$ :( doing alternating () and [] is a byte shorter but way less cool \$\endgroup\$ – nmjcman101 Jun 29 '17 at 1:51
5
\$\begingroup\$

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

\$\endgroup\$
  • 1
    \$\begingroup\$ You can drop the parents around (x:y) and (init y). k==""="" is shorter as k==""=k. \$\endgroup\$ – Laikoni Jun 28 '17 at 23:00
  • 1
    \$\begingroup\$ Save some more bytes by changing cycle["()","[]"] to just "()[]": Try it online! \$\endgroup\$ – Laikoni Jun 28 '17 at 23:02
  • \$\begingroup\$ @Laikoni great suggestions,thanks \$\endgroup\$ – bartavelle Jun 29 '17 at 5:12
  • 1
    \$\begingroup\$ Good catch that keeping cycle is even shorter. You can still remove the parenthesis around (init y). \$\endgroup\$ – Laikoni Jun 29 '17 at 6:40
  • 1
    \$\begingroup\$ You can move the case k==""=k to the end and change it to 0<1=k. \$\endgroup\$ – Zgarb Jun 29 '17 at 13:35
2
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ s.insert k=i*2,'(['[i%2];s[~k]+=')]'[i%2] to save 2 bytes. Try it online! \$\endgroup\$ – Value Ink Jun 28 '17 at 22:00
2
\$\begingroup\$

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, 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 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 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 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 '('+....

\$\endgroup\$
  • \$\begingroup\$ For some simple wins you could change %2==0 to %2<1 and use [...i] instead of i.split \$\endgroup\$ – powelles Jun 28 '17 at 19:21
  • 1
    \$\begingroup\$ Thanks @powelles I've been working on an explanation more than a fully golfed answer, so that hasn't made it into an edit yet. I already had the [..i] idea, but I forgot about %2<1 thanks. \$\endgroup\$ – David Archibald Jun 28 '17 at 19:24
  • \$\begingroup\$ b%2<1 could be replaced by !b%2 \$\endgroup\$ – Luke Jun 28 '17 at 21:55
  • \$\begingroup\$ Also, d==b?x:y could become d-b?y:x and d%1==0 could become !d%1. \$\endgroup\$ – Luke Jun 28 '17 at 22:01
  • \$\begingroup\$ Unfortunately because of order of operations !d%1 only works with parentheses: !(d%1), and it doesn't shave off any bytes. I forgot that 0 was the only falsy number, for some reason I thought -1 was the falsy one. Correct me if I'm getting something wrong about the second one. \$\endgroup\$ – David Archibald Jun 28 '17 at 22:38
2
\$\begingroup\$

Jelly, 23 21 bytes

LHĊRị
ç⁾)]żUFUż@ç⁾([$

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

\$\endgroup\$
1
\$\begingroup\$

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!

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 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? I don't understand at all.

\$\endgroup\$
  • 1
    \$\begingroup\$ You can change the i%2==0 to i%2<1 to save two bytes. \$\endgroup\$ – Mar Dev Jun 29 '17 at 1:47
1
\$\begingroup\$

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/
\$\endgroup\$
1
\$\begingroup\$

05AB1E, 31 bytes

2ä`Rð«„)]Ig©×øRJ®Èƒ¦}s„([®×søJì

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
\$\endgroup\$
1
\$\begingroup\$

C++ 14, 154 145 bytes

[Recursive]

auto L(string i,bool b=1){int l=i.length();string o=b?"(":"[";auto c=b?")":"]";if(l<3)return o+i+c;return o+i[0]+L(i.substr(1,l-2),!b)+i[l-1]+c;}

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;}
\$\endgroup\$
0
\$\begingroup\$

Pyth, 42 (!) bytes

M?!lHH+@,\[\(G++hHg!GPtH+?qlH1keH@,\]\)Gg1

Test it online! 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.

\$\endgroup\$
0
\$\begingroup\$

05AB1E, 49 42 bytes

g;îD„([×s£©"s‚.Bøvy¬ðQi¦}}JR"DU.V®D∞sKRX.V

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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!

Previous version*

{for($s="($args)";$s-ne($t=$s-replace'(\(.)([^][]+)(.\))','$1[$2]$3'-replace'(\[.)([^)(]+)(.\])','$1($2)$3')){$s=$t}$s}

*Thanks @Digital Trauma.

\$\endgroup\$
0
\$\begingroup\$

QuadR, 82 bytes

(81 bytes +1 for flag)

(\(.)([^[])(.+?)([^\]])(.\))
(\(.)(..?)(.\))
^[^\(].*
\1[\2(\3)\4]\5
\1[\2]\3
(&)

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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)
\$\endgroup\$
0
\$\begingroup\$

Java (OpenJDK 8), 126 bytes

c->{String s="";for(int l=c.length-1,a=l/2;a>=0;)s=(a%2<1?"(":"[")+(a<(l+1)/2?c[a]+s+c[l-a]:c[a])+(a--%2<1?")":"]");return s;}

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.