Appends or Prepends? Depends

DJMcMayhem 04/29/2017. 6 answers, 464 views
code-golf string balanced-string classification brain-flak

Brain-flak turns one year old tomorrow! In honor of it's birthday, we're having a PPCG style birthday party, where several users post brain-flak related questions! Help us celebrate! :)

Brain-flak is an esoteric language I wrote where all of the commands are brackets and all of the brackets must be fully matched. To borrow my own definition:

  • For the purpose of this challenge, a "bracket" is any of these characters: ()[]{}<>.

  • A pair of brackets is considered "matched" if the opening and closing brackets are in the right order and have no characters inside of them, such as


    Or if every subelement inside of it is also matched.


    Subelements can also be nested several layers deep.

  • A string is considered "Fully matched" if and only if:

    1. Every single character is a bracket,

    2. Each pair of brackets has the correct opening and closing bracket and in the right order

In celebration of brain-flak's first birthday, today's challenge is about taking an unbalanced set of brackets, and determining what types of operations are needed to make it valid brain-flak.

  • For example, (( is not valid brain-flak code, but if we append )) to it, it becomes (()), which is fully balanced, and therefore valid brain-flak. That makes this input appendable.

  • Similarly, >} is not valid, but we can prepend {< to it to make {<>}, which is valid. That makes this input prependable.

  • Some inputs are slightly more complicated. For example, )][({ cannot be made valid purely by appending or prepending. But it can be made valid by prepending [( and appending })]. Therefore, this input is both prependable and appendable.

  • Lastly, some inputs can never be made valid brain-flak code by any combination of appending or prepending. For example, (> can never be made valid. (Prepending < creates <(>, and appending ) creates (>), neither of which are valid) Therefore, this input is neither appendable or prependable.

For today's challenge, you must write a program or function that takes a string of brackets and determines if the string is


You may pick what values you use to represent for each case. For example, outputting 1, 2, 3, 4, or 'a', 'p', 'b', 'n', or 1, 'foo', 3.1415, -17, or whatever is fine. As long as each output is distinct and consistent, that's fine. You must however, clearly specify which output corresponds to which case.

You may return this value in whichever format is most convenient (for example, returning from a function, printing to STDOUT, modifying arguments, writing to a file, etc.).

You can assume that the input will never be valid brain-flak or empty.


The following inputs are all prependable:


These are all appendable:


These are all both:


And these are all neither:


As usual, this is , so standard loopholes apply, and the shortest answer in bytes wins!

This challenge is particularly difficult in brain-flak, so maximum brownie points to any and every answer written in brain-flak. :)

6 Answers

Jonathan Allan 04/29/2017.

Jelly, 33 32 37 35 34 bytes

bug found, horrible fix +5 bytes, better fix - 2 bytes, using a trick of Adnan's I saw here for -1 more.


Return values:

prepends [2]
 appends [0]
    both [2,0]
 neither 1

(Invalid input returns spurious results, although valid Brain-flack, returns [].)

Try it online! - a test suite (prints mushed representations, so 20 for [2,0], and ignores lines containing any -).

Cows quack 04/29/2017.

Retina, 41 40 41 bytes

1 byte saved thanks to @MartinEnder



Try it online!

  • Prependable is 1
  • Appendable is 0
  • Both is 10
  • None is 01


  • Gained 1 byte to fix bug noticed by @Neil

Neil 04/29/2017.

Batch, 337 bytes

@echo off
set "t=%s:<>=%
set "t=%t:()=%
set "t=%t:[]=%
set "t=%t:{}=%
if not "%t%"=="%s%" set "s=%t%"&goto g
set "s=%s:<=[%
set s=%s:>=]%
set s=%s:(=[%
set s=%s:)=]%
set s=%s:{=[%
set s=%s:}=]%
if %s:~,2%==]] set s=%s:~1%&goto l
if %s:~-2%==[[ set s=%s:~,-1%&goto l
if not _%s:~2%==_ set s=[]
echo %s%

Outputs ] for prepend, [ for append, ][ for both, [] for neither.

Ørjan Johansen 04/29/2017.

Haskell, 115 108 bytes


  • -7 bytes: Use more guards.
s#(c:d)|Just a<-lookup c$zip"([{<"")]}>"=(a:s)#d|(a:b)<-s=[1|a==c]>>b#d|0<1=take 1$s#d

Try it online!

Use like (""#) "))". Results are given as:

[False,True]: needs nothing
[False]: prependable
[True,True]: appendable
[True]: both
[]: neither

How it works

  • The output encoding is chosen such that a need to prepend is signaled by dropping the second element of the result for the remainder, if any, while a complete mismatch is signaled by dropping all of them.
  • s#d parses a remaining string d, given a string/stack s of expected closing brackets.
    • The s#"" line checks if all closing brackets have been found by the end of the string, otherwise appending is needed.
    • The first branch of s#(c:d) checks if the next character c is an opening bracket, and if so leaves the corresponding closing bracket on the stack for the recursion.
    • Otherwise, if the stack contains closing brackets, the second branch checks if the top one matches the next character, and if not, returns an empty list instead of recursing.
    • Lastly, in the last branch the stack is empty, and we have an unmatched closing bracket that may be fixed by prepending, before recursing.

ETHproductions 04/29/2017.

Japt, 44 bytes

=Ue"%(%)|%[]|\{}|<>" ®c -1&2|1})f31 |UfD |Ug

Outputs 1 for prependable, 3 for appendable, 13 for both, and 31 for neither.

Test it online! or Verify all test cases at once.

How it works

 =Ue"%(%)|%[]|\{}|<>" ®   c -1&2|1})f31 |UfD |Ug
U=Ue"%(%)|%[]|\{}|<>" mZ{Zc -1&2|1})f31 |UfD |Ug

                    // "(((()()())))}"  "([({}{})"    ">()[(()){"  "((((<>()]"
Ue"%(%)|%[]|\{}|<>" // Recursively remove all instances of "()", "[]", "{}", and "<>" from U.
                    // "}"              "(["          ">[{"        "((((]"
mZ{Zc -1&2|1}       // Replace each char Z with (Z.charCodeAt() - 1) & 2 | 1.
                    // "1"              "33"          "133"        "33331"
U=                  // Save the result in U.
f31 |UfD |Ug        // Match all instances of "31" and "13" (D = 13) and bitwise-OR the results with the first char.
                    // null|null|1      null|null|3   null|13|1    31|null|3
                    // 1                3             13           31
                    // Implicit: output result of last expression

Jörg Hülsermann 06/04/2017.

PHP, 137 Bytes


1 =>appendable,

2 =>prependable,


0 =>neither

Testcases - Download Hi-Res Songs

1 Ariana Grande

7 Rings flac

Ariana Grande. 2019. Writer: Tayla Parx;Kimberly Krysiuk;Njomza Vitia;Scootie;Tommy Brown;Richard Rogers;Oscar Hammerstein II;Crazy Mike;Victoria Monét;Ariana Grande.
2 Alan Walker

Lily flac

Alan Walker. 2018. Writer: Alan Walker;Lars Kristian Rosness;Magnus Bertelsen;K-391;Didrik Handlykken;Marcus Arnbekk.
3 Skylar Grey

Everything I Need flac

Skylar Grey. 2018. Writer: Elliott Taylor;Rupert Gregson-Williams;Skylar Grey.
4 Alec Benjamin

Let Me Down Slowly flac

Alec Benjamin. 2019. Writer: Alec Benjamin;Sir Nolan;Michael Pollack.
5 Alan Walker

Lost Control flac

Alan Walker. 2018. Writer: Alan Walker;Thomas Troelsen;Mood Melodies;Sorana;Fredrik Borch Olsen;Magnus "Magnify" Martinsen.
6 Westlife

Hello My Love flac

Westlife. 2019. Writer: Steve Mac;Ed Sheeran.
7 Sam Smith

Fire On Fire flac

Sam Smith. 2018. Writer: Steve Mac;Sam Smith.
8 Post Malone

Sunflower flac

Post Malone. 2018. Writer: Carl Rosen;Louis Bell;Billy Walsh;Carter Lang;Swae Lee;Post Malone.
9 Conor Maynard

Way Back Home (Sam Feldt Edit) flac

Conor Maynard. 2018. Writer: Ji Hye Lee;Shaun.
10 Alan Walker

Different World flac

Alan Walker. 2018. Writer: Shy Nodi;Alan Walker;Fredrik Borch Olsen;James Njie;Marcus Arnbekk;Gunnar Greve Pettersen;K-391;Corsak;Shy Martin;Magnus Bertelsen.
11 The Chainsmokers

Hope flac

The Chainsmokers. 2018. Writer: Kate Morgan;Chris Lyon;Alex Pall;Andrew Taggart.
12 Normani

Dancing With A Stranger flac

Normani. 2019. Writer: Mikkel S. Eriksen;Tor Hermansen;Jimmy Napes;Normani;Sam Smith.
13 Imagine Dragons

Believer flac

Imagine Dragons. 2019. Writer: Dan Reynolds;Lil Wayne;Wayne Sermon;Ben McKee;Daniel Platzman;Robin Fredriksson;Mattias Larsson;Justin Tranter.
14 Alan Walker

I Don't Wanna Go flac

Alan Walker. 2018.
15 Slushii

Never Let You Go flac

Slushii. 2019. Writer: Sofía Reyes;Slushii;Aviella Winder.
16 Mike Perry

Runaway flac

Mike Perry. 2019. Writer: Andreas Wiman;Dimitri Vangelis;Richard Müller;Sasha Rangas;Stefan Van Leijsen;Mike Perry.
17 Hozier

Almost (Sweet Music) flac

Hozier. 2019. Writer: Hozier.
18 Gesaffelstein

Lost In The Fire flac

Gesaffelstein. 2019. Writer: Ahmad Balshe;Nate Donmoyer;Gesaffelstein;DaHeala;The Weeknd.
19 Backstreet Boys

No Place flac

Backstreet Boys. 2019.
20 Maren Morris

Girl flac

Maren Morris. 2019. Writer: Maren Morris;Sarah Aarons;Greg Kurstin.

Related questions

Hot questions


Popular Tags