title: Telescopic Parentheses

text:
# Question
Title: Telescopic Parentheses
Consider a non-empty string of correctly balanced parentheses:

```
(()(()())()((())))(())

```

We can imagine that each pair of parentheses represents a ring in a collapsed telescopic construction. So let's extend the telescope:

```
(                )(  )
 ()(    )()(    )  ()
    ()()    (  )
             ()

```

Another way to look at it is that the parentheses at depth *n* are moved to line *n*, while keeping their horizontal position.

Your task is to take such a string of balanced parentheses and produce the extended version.

You may write a program or function, taking input via STDIN (or closest equivalent), command-line argument or function parameter, and producing output via STDOUT (or closest equivalent), return value or function (out) parameter.

You may assume that the input string is valid, i.e. consists only parentheses, which are correctly balanced.

You may print trailing spaces on each line, but not any more leading spaces than necessary. In total the lines must not be longer than twice the length of the input string. You may optionally print a single trailing newline.

## Examples

In addition to the above example, here are a few more test cases (input and output are separated by an empty line).

```
()

()

```

```
(((())))

(      )
 (    )
  (  )
   ()

```

```
()(())((()))(())()

()(  )(    )(  )()
   ()  (  )  ()
        ()

```

```
((()())()(()(())()))

(                  )
 (    )()(        )
  ()()    ()(  )()
             ()

```

**Related Challenges:**

* **Topographic Strings**, which asks you to produce what is essentially the complement of the output in this challenge.
* **Code Explanation Formatter**, a broad generalisation of the ideas in this challenge, posted recently by PhiNotPi. (In fact, PhiNotPi's original description of his idea was what inspired this challenge.)

## Leaderboards

Huh, this got quite a lot of participation, so here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

```
function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;var n=e.body_markdown.split("\n");try{t|=/^#/.test(e.body_markdown);t|=["-","="].indexOf(n[1][0])>-1;t&=LANGUAGE_REG.test(e.body_markdown)}catch(r){}return t}function shouldHaveScore(e){var t=false;try{t|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading);answers.sort(function(e,t){var n=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0],r=+(t.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0];return n-r});var e={};var t=0,c=0,p=-1;answers.forEach(function(n){var r=n.body_markdown.split("\n")[0];var i=$("#answer-template").html();var s=r.match(NUMBER_REG)[0];var o=(r.match(SIZE_REG)||[0])[0];var u=r.match(LANGUAGE_REG)[1];var a=getAuthorName(n);t++;c=p==o?c:t;i=i.replace("{{PLACE}}",c+".").replace("{{NAME}}",a).replace("{{LANGUAGE}}",u).replace("{{SIZE}}",o).replace("{{LINK}}",n.share_link);i=$(i);p=o;$("#answers").append(i);e[u]=e[u]||{lang:u,user:a,size:o,link:n.share_link}});var n=[];for(var r in e)if(e.hasOwnProperty(r))n.push(e[r]);n.sort(function(e,t){if(e.lang>t.lang)return 1;if(e.lang<t.lang)return-1;return 0});for(var i=0;i<n.length;++i){var s=$("#language-template").html();var r=n[i];s=s.replace("{{LANGUAGE}}",r.lang).replace("{{NAME}}",r.user).replace("{{SIZE}}",r.size).replace("{{LINK}}",r.link);s=$(s);$("#languages").append(s)}}var QUESTION_ID=49042;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/;var NUMBER_REG=/\d+/;var LANGUAGE_REG=/^#*\s*([^,]+)/
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script><link rel=stylesheet type=text/css href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id=answer-list><h2>Leaderboard</h2><table class=answer-list><thead><tr><td></td><td>Author<td>Language<td>Size<tbody id=answers></table></div><div id=language-list><h2>Winners by Language</h2><table class=language-list><thead><tr><td>Language<td>User<td>Score<tbody id=languages></table></div><table style=display:none><tbody id=answer-template><tr><td>{{PLACE}}</td><td>{{NAME}}<td>{{LANGUAGE}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table><table style=display:none><tbody id=language-template><tr><td>{{LANGUAGE}}<td>{{NAME}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table>
```

# Answer
> 10 votes
# CJam, ~~17~~ ~~16~~ 15 bytes

```
0000000: 72 3a 69 22 28 0b 20 9b 41 29 22 53 2f 66 3d     r:i"(. .A)"S/f=

```

The above is a reversible xxd dump, since the source code contains the unprintable characters VT (0x0b) and CSI (0x9b).

Like this answer, it uses ANSI escape sequences, but it also uses vertical tabs and it prints the control characters directly to avoid using **printf**.

This requires a supporting video text terminal, which includes most non-Windows terminal emulators.

### Test run

We have to set the shell variable *LANG* and the terminal emulator's encoding to ISO 8859-1. The former is achieved by executing

```
$ LANGsave="$LANG"
$ LANG=en_US

```

Also, before executing the actual code, we'll disable the prompt and clear the screen.

```
$ PS1save="$PS1"
$ unset PS1
$ clear

```

This makes sure the output is shown properly.

```
echo -n '()(())((()))(())()' | cjam <(base64 -d <<< cjppIigLIJtBKSJTL2Y9)
()(  )(    )(  )()
   ()  (  )  ()
        ()

```

To restore *LANG* and the prompt, execute this:

```
$ LANG="$LANGsave"
$ PS1="$PS1save"

```

### How it works

We insert a vertical tab after each **(** to move the cursor down and the byte sequence **9b 41** (`"\x9bA"`) before each **)** to move the cursor up.

```
r         e# Read a whitespace-separated token from STDIN.
:i        e# Replace each character by its code point.
          e#   '(' -> 40, ')' -> 41
"(. .A)"  e# Push the string "(\v \x9bA)".
S/        e# Split at spaces into ["(\v" "\x9bA)"].
f=        e# Select the corresponding chunks.
          e# Since arrays wrap around in CJam, ["(\v" "\x9bA)"]40= and
          e# ["(\v" "\x9bA)"]41= select the first and second chunk, respectively.

```

# Answer
> 53 votes
# x86 machine code, ~~39~~ ~~34~~ ~~33~~ ~~30~~ 29 bytes

```
00000000  68 c3 b8 07 31 ff be 82  00 b3 a0 ad 4e 3c 28 7c  |h...1.......N<(||
00000010  f0 77 05 ab 01 df eb f3  29 df ab eb ee           |.w......)....|
0000001d

```

x86 assembly for DOS, with some tricks:

```
    org 100h

section .text

start:
    ; point the segment ES to video memory
    ; (c3 is chosen so that it doubles as a "ret")
    push 0b8c3h
    pop es
    ; di: output pointer to video memory
    xor di,di
    ; si: input pointer from the command line
    mov si,82h
    ; one row=160 bytes (assume bh=0, as should be)
    mov bl,160
lop:
    ; read & increment si (assume direction flag clean)
    ; we read a whole word, so that later we have something nonzero to
    ; put into character attributes
    lodsw
    ; we read 2 bytes, go back 1
    dec si
    ; check what we read
    cmp al,'('
    ; less than `(`: we got the final `\n` - quit
    ; (we jump mid-instruction to get a c3 i.e. a ret)
    jl start+1
    ; more than `(`: assume we got a `)`
    ja closed
    ; write a whole word (char+attrs), so we end
    ; one position on the right
    stosw
    ; move down
    add di,bx
    ; rinse & repeat
    jmp lop
closed:
    ; move up
    sub di,bx
    ; as above
    stosw
    jmp lop

```

*Limitations*:

* it always prints starting at the bottom of the screen, without erasing first; a `cls` before running is almost mandatory;
* the colors are ugly; that's the consequence of recycling the next character as color attributes to save two bytes here and there;
* the code assumes `bh=0` and the direction flag clear on start, both undocumented; OTOH, `bx` is explicitly set to zero in all DOS variants I saw (DosBox, MS-DOS 2, FreeDOS), and everywhere I tested the flags were already OK.

# Answer
> 29 votes
## J, ~~32~~ 28 bytes

This was a fun one.

```
0|:')(('&(i.-<:@+/\@i:){."0]

```

### Explanation

This is how this solution works, including an explanation of how it has been golfed.

```
   NB. Let a be a test case
   a =. '((()())()(()(())()))'

   NB. level alterations
   _1 + ').(' i. a
1 1 1 _1 1 _1 _1 1 _1 1 1 _1 1 1 _1 _1 1 _1 _1 _1

   NB. absolute levels
   +/\ _1 + ').(' i. a
1 2 3 2 3 2 1 2 1 2 3 2 3 4 3 2 3 2 1 0

   NB. adjusted levels
   (+/\ _1 + ').(' i. a) - ')(' i. a
0 1 2 2 2 2 1 1 1 1 2 2 2 3 3 2 2 2 1 0

   NB. take level from end of each item of a and transpose
   |: a {."0~ _1 - (+/\ _1 + ').(' i. a) - ')(' i. a
(                  )
 (    )()(        )
  ()()    ()(  )()
             ()

   NB. code as a tacit verb
   [: |: ] {."0~ _1 - ([: +/\ _1 + ').(' i. ]) - ')(' i. ]

   NB. subtractions pulled into the prefix insert
   [: |: ] {."0~ (')(' i. ]) - [: <:@+/\ ').(' i. ]

   NB. i: instead of i. so we can use the same string constant
   [: |: ] {."0~ (')((' i. ]) - [: <:@+/\ ')((' i: ]

   NB. get rid of the caps
   0 |: ] {."0~ (')((' i. ]) - ')((' <:@+/\@i: ]

   NB. join the two usages of ')((' into a single dyadic phrase
   0 |: ] {."0~ ')((' (i. - <:@+/\@i:) ]

   NB. bond ')((' and flip arguments to {."0
   0 |: ')(('&(i. - <:@+/\@i:) {."0 ]

```

# Answer
> 17 votes
# C, 150 bytes

```
t;f(char*c){char l=strlen(c)+1,o[l*l],*A=o,m=0;for(t=1;t<l*l;t++)o[t-1]=t%l?32:10;for(t=-1;*c;c++)A++[l*(*c-41?++t>m?m=t:t:t--)]=*c;A[m*l]=0;puts(o);}

```

This was *crazy* fun to golf. I'm still not convinced I'm done with it.

We define a single function, `f`, that takes the string as input and outputs to stdout.

Let's go through the code, line by line:

```
/* t will represent the current depth of a parentheses. It must be an int. */
t;
f(char*c){
    //Our variables:
    char l=strlen(c)+1,    //The length of each row of output, including newlines
         o[l*l],           //The output string. It's way larger than it needs to be.
         *A=o,             //We need another pointer to keep track of things.
         m=0;              //The maximum depth recorded thus far.

    for(t=1;t<l*l;t++)     //For each character in our output...
        o[t-1]=t%l?32:10;  //If it's at the end of a line, make it '\n'. Else, ' '.
    for(t=-1;*c;c++)       //While we have an input string...
        //Perhaps a personal record for ugliest warning-less line...
        A++[l*(*c-41?++t>m?m=t:t:t--)]=*c;
    /*
        A breakdown:
        A++        --> Go to the next *column* of output, after writing.
                   --> There will only ever be one parentheses per output column.
        [l*(...)]  --> A[l*X] is the character in the current column at depth X.
        (*c-41?    --> If the character is a '('...
        ++t>m?     --> Increment t *before* we write it. If this is a new highest depth
        m=t:       --> Set m to t, and set the whole expression to t.
        t:         --> If it's not a new highest depth, don't set m.
        t--)       --> If the character was a ')', decrement t *after* we write it.
        =*c        --> Write our output character to whatever the input read.
    */

    A[m*l]=0; //The last character of the maximum-depth line should be null terminated.
    puts(o);  //Output!
}

```

I'll answer any questions you may have!

Try a test program online!

# Answer
> 17 votes
# Retina + Bash, 27 bytes (14 + 10 + 3 = 27)

This makes use of ANSI Escapes:

```
\(
(\e[B
\)
\e[A)

```

Equivalent to `sed -e "s/(/(\\\e[B/g;s/)/\\\e[A)/g"`. The `\e[B` escape code means move cursor down one row, and the `\e[A` means move cursor up one row, so this solution simply inserts those codes after and before the start and end of each nested pair of parentheses. Input is passed through STDIN.

You'll have to call it as `printf $(Retina ...)` to see the output correctly.

## Output

```
(((())))
(\e[B(\e[B(\e[B(\e[B\e[A)\e[A)\e[A)\e[A)
^C
amans:~ a$ printf "(\e[B(\e[B(\e[B(\e[B\e[A)\e[A)\e[A)\e[A)"
(      )amans:~ a$
 (    )
  (  )
   ()

((()())()(()(())()))
(\e[B(\e[B(\e[B\e[A)(\e[B\e[A)\e[A)(\e[B\e[A)(\e[B(\e[B\e[A)(\e[B(\e[B\e[A)\e[A)(\e[B\e[A)\e[A)\e[A)
^C
amans:~ a$ printf "(\e[B(\e[B(\e[B\e[A)(\e[B\e[A)\e[A)(\e[B\e[A)(\e[B(\e[B\e[A)(\e[B(\e[B\e[A)\e[A)(\e[B\e[A)\e[A)\e[A)"
(                  )amans:~ a$
 (    )()(        )
  ()()    ()(  )()
             ()

```

# Answer
> 16 votes
# TI-BASIC, ~~69 60 56~~ 55 bytes

This is for the TI-83+/84+ family of calculators, although it was written on an 84+ C Silver Edition.

The program shows up as larger on-calc due to VAT+size info being included. Also, there are more than 56 characters here; the reason it's 56 bytes is because all commands that are more than one character are compressed down to tokens that are either one or two bytes in size.

```
Input Str1
1→B
For(A,1,length(Str1
sub(Str1,A,1→Str2
Ans="(
Output(B+Ans,A,Str2
B-1+2Ans→B
End

```

Shaved off another byte thanks to thomas-kwa! (also from him was the jump from 60 to 56.)

# Answer
> 10 votes
# Python 2, 115 bytes

```
def f(L,n=0,O=()):
 for c in L:n-=c>"(";O+=" "*n+c,;n+=c<")"
 for r in map(None,*O):print"".join(c or" "for c in r)

```

Call like `f("((()())()(()(())()))")`, and output is to STDOUT.

## Explanation

We start with `n = 0`. For each char in the input line:

* If the char is `(`, we prepend `n` spaces then increment `n`
* If the char is `)`, we decrement `n` then prepend `n` spaces

The result is then zipped and printed. Note that Python's `zip` zips to match the length of the *shortest* element, e.g.

```
>>> zip([1, 2], [3, 4], [5, 6, 7])
[(1, 3, 5), (2, 4, 6)]

```

Usually one would use `itertools.zip_longest` (`izip_longest`) if they wanted `zip` to pad to the length of the *longest* element.

```
>>> import itertools
>>> list(itertools.izip_longest([1, 2], [3, 4], [5, 6, 7]))
[(1, 3, 5), (2, 4, 6), (None, None, 7)]

```

But in Python 2, this behaviour can be simulated by mapping `None`:

```
>>> map(None, [1, 2], [3, 4], [5, 6, 7])
[(1, 3, 5), (2, 4, 6), (None, None, 7)]

```

---

## Python 3, 115 bytes

```
L,d,*O=input(),0
for i,c in enumerate(L):b=c>"(";O+="",;O[d-b]=O[d-b].ljust(i)+c;d-=b*2-1
for l in O:l and print(l)

```

No zipping, just padding appropriately with `ljust`. This one seems to have some golfing potential.

# Answer
> 10 votes
# C, ~~58 53 52 51~~ 49 bytes

Makes use of ANSI escape sequences to move the cursor position.

```
f(char*s){while(*s)printf(*s++&1?"\e[A)":"(\v");}

```

If not using gcc or another compiler that supports `\e` then it can be replaced with `\x1B` for a total of 2 extra bytes. `\e[A` moves the cursor up one row and `\e[B` moves the cursor down one row. It's not necessary to use `\e[B` to move down one row as it's two bytes shorter to use the ASCII vertical tab character `0xB` or `\v`.

The input string is assumed, from the question, to consist of only (balanced) parentheses, so checking the parity of the character, with `&1`, is enough to distinguish between `(` and `)`.

# Answer
> 9 votes
# R, ~~151~~ 127 characters

```
S=strsplit(scan(,""),"")[[1]];C=cumsum;D=c(C(S=="("),0)-c(0,C(S==")"));for(j in 1:max(D)){X=S;X[D!=j]=' ';cat(X,sep='',fill=T)}

```

With indents and newlines:

```
S=strsplit(scan(,""),"")[[1]]
C=cumsum
D=c(C(S=="("),0)-c(0,C(S==")"))
for(j in 1:max(D)){
    X=S
    X[D!=j]=' '
    cat(X,sep='',fill=T)
    }

```

Usage:

```
> S=strsplit(scan(,""),"")[[1]];C=cumsum;D=c(C(S=="("),0)-c(0,C(S==")"));for(j in 1:max(D)){X=S;X[D!=j]=' ';cat(X,sep='',fill=T)}
1: ()(())((()))(())()
2:
Read 1 item
()(  )(    )(  )()
   ()  (  )  ()
        ()
> S=strsplit(scan(,""),"")[[1]];C=cumsum;D=c(C(S=="("),0)-c(0,C(S==")"));for(j in 1:max(D)){X=S;X[D!=j]=' ';cat(X,sep='',fill=T)}
1: ((()())()(()(())()))
2:
Read 1 item
(                  )
 (    )()(        )
  ()()    ()(  )()
             ()

```

It reads the string as stdin, splits it as a vector of single characters, computes the cumulative sum of `(` and `)`, substracts the former with the latter (with a lag) thus computing the "level" of each parentheses. It then prints to stdout, for each level, either the corresponding parentheses or a space.

Thanks to @MickyT for helping me shortening it considerably!

# Answer
> 9 votes
# Pip, 53 bytes

**Pip** is a code-golf language of my invention. The first version was published on Saturday, so I can officially take it for a spin! The solution below isn't terribly competitive as golfing languages go, but that's partly because I haven't implemented things like zip and max yet.

```
z:{aEQ'(?++v--v+1}MaW(o:{z@++v=i?as}Ma)RMs{Pov:-1++i}

```

Expects the string of parentheses as a command-line argument.

"Ungolfed" version:

```
z:{
   a EQ '( ?
    ++v
    --v+1
  } M a
W (o:{
      z @ ++v = i ?
       a
       s
     } M a
  ) RM s
{
 P o
 v:-1
 ++i
}

```

**Explanation:**

Unlike most golfing languages, Pip is imperative with infix operators, so the syntax is somewhat closer to C and its derivatives. It also borrows ideas from functional and array-based programming. See the repository for further documentation.

The program first generates a list of depths (storing it in `z`) by mapping a function to the input string `a`. The global variable `v` tracks the current level. (Variables `a-g` in Pip are function-local variables, but `h-z` are global. `v` is handy because it's preinitialized to -1.)

Next, we use a `W`hile loop to generate and print each line, until the line generated would consist of all spaces. `v` is now used for columns, and `i` for rows. The `{z@++v=i?as}` function, repeatedly mapped to the original input string, tests whether the current line `i` matches the line the current parenthesis is supposed to be on (as stored in the `z` list). If so, use the parenthesis (`a`); if not, use `s` (preinitialized to space). The end result is that on each iteration, `o` gets assigned a list of characters equivalent to the next line of the output.

To test whether we should continue looping, we check if `o` with all the spaces `RM`'d is empty. If not, print it (which by default concatenates everything together as in CJam), reset the column number to -1, and increment the row number.

(Fun fact: I had a 51-byte solution at first... which didn't work because it turned up a bug in the interpreter.)

# Answer
> 8 votes
# Pyth, 31 bytes

```
VzJs.e?YqN-/<zk\(/<zhk\)dzI-JdJ

```

Try it online.

`-/<zk\(/<zhk\)`: Finds the appropriate level for the current character position.

`?YqN-/<zk\(/<zhk\)d`: A space if the appropriate level is not the current level, current character otherwise.

`Js.e?YqN-/<zk\(/<zhk\)dz`: Generate the string, save it to `J`.

`I-JdJ`: If `J` is not all spaces, print it out.

`Vz`: Loop `z` times.

# Answer
> 7 votes
# GNU Bash + coreutils + indent, 135

```
eval paste "`tr '()' {}|indent -nut -i1 -nbap|sed 's/.*/<(fold -1<<<"&")/'|tr '
' \ `"|expand -t2|sed 'y/{}/()/;s/\(.\) /\1/g;s/ \+$//'

```

Input/output via STDIN/STDOUT:

```
$ ./telescopic.sh <<< "(()(()())()((())))(())"
(                )(  )
 ()(    )()(    )  ()
    ()()    (  )
             ()
$

```

`indent` does most of the heavy lifting, but needs to work with braces instead of parens. The rest is modification of this answer to transpose the output of `indent`.

# Answer
> 6 votes
# Python 2, 92

```
def f(s,i=0,z=''):
 for x in s:b=x>'(';z+=[' ',x][i==b];i-=2*b-1
 if'('in z:print z;f(s,i-1)

```

Prints line by line. For a given line number `i` (actually, its negation), goes through the input string `s`, and makes a new string `z` that only contains the characters of `s` at depth `i`. This is done by incrementing or decrementing `i` to track the current depth, and adding the current characters when `i` is `0` adjusted for paren type, and otherwise adding a space.

Then, prints and recurses to the next `i` unless the current line was all spaces. Note that since the parens are balanced, the `i` after a loop is the same as at the start.

Python 3 would be same except for a character for `print(z)`.

# Answer
> 5 votes
# Java, 232 226 224 222 bytes

Golfed version:

```
int i,j,k,l,m,a[];void f(String s){a=new int[s.length()];j=a.length;for(k=0;k<j;){a[k]=s.charAt(k++)<41?i++:--i;m=m<i?i:m;}for(k=0;k<m;k++)for(l=0;l<j;)System.out.print(k==a[l++]?i++%2<1?'(':l==j?")\n":')':l==j?'\n':' ');}

```

Long version:

```
int i, j, k, l, m, a[];
void f(String s) {
    a = new int[s.length()];
    j = a.length;
    for (k = 0; k < j;) {
        a[k] = s.charAt(k++) < 41 ? i++ : --i;
        m = m < i ? i : m;
    }
    for (k = 0; k < m; k++)
        for (l = 0; l < j;)
            System.out.print(k == a[l++] ? (i++ % 2 < 1 ? '(' : (l == j ? ")\n" : ')')) : (l == j ? '\n':' '));
}

```

The input string is analyzed first, looking for "(" and ")" to add/subtract a counter and store its value determining how far down the parentheses should go in an array while also keeping track of how deep the deepest one goes. Then the array is analyzed; the parentheses with lesser values are printed first, and will continue printing line by line until the maximum is reached.

I'll probably find ways to golf this further later.

# Answer
> 5 votes
# Javascript/ES6, 97 chars

```
f=s=>{for(n in s){m=o=d='';for(c of s)o+=n==(c<')'?d++:--d)?c:' ',m=m<d?d:m;n<m&&console.log(o)}}

```

## Usage

```
f("(()(()())()((())))(())")

```

## Explanation

```
fn=str=>{                          // accepts string of parenthesis
  for(line in str){                // repeat process n times where n = str.length
    max=output=depth='';           // max: max depth, output: what to print, depth: current depth
    for(char of str)               // iterate over chars of str
      output+=
        line==(char<')'?depth++:--depth)? // update depth, if line is equal to current depth
        char:' ',                  // append either '(', ')', or ' '
        max=max<depth?depth:max;   // update max depth
    line<max&&console.log(output)  // print if current line is less than max depth
  }
}

```

# Answer
> 5 votes
# cheating :(  ~~Retina + TeX, N bytes~~ cheating :(

This only works if you render(?) the output using MathJax or some other TeX, which is currently disabled for this SE :(

```
\(
({
\)
})
\{\(
_{(

```

Each line should be in a different file, but you can test it by using `Retina -e "\(" -e "({" -e "\)" -e "})" -e "\{\(" -e "_{("` (or the equivalent sed command `sed -e "s/(/({/g;s/)/})/g;s/{(/_{(/g"`). Input is passed through STDIN.

This works by enclosing the contents of each pair of parentheses in braces, and then subscripting all the items inside them.

## Output

```
(((())))
(_{(_{(_{({})})})})

()(())((()))(())()
({})(_{({})})(_{(_{({})})})(_{({})})({})

((()())()(()(())()))
(_{(_{({})({})})({})(_{({})(_{({})})({})})})

```

# Answer
> 4 votes
# CJam, ~~43 41~~ 36 bytes

Not too golfed (I think), but here goes my first attempt:

```
l:L,{)L<)_')=@~zS*\+}%_$0=,f{Se]}zN*

```

**How it works**

I am using the very handy fact that `)` and `(` in CJam mean increment and decrement respectively. Thus, I simply evaluate the brackets to get the depth.

```
l:L,{)L<)_')=@~zS*\+}%_$0=,f{Se]}zN*
l:L,{                    }%                "Store input line in L and iterate over [0,L)";
     )L<                                   "substr(L, 0, iterator + 1)";
        )                                  "Slice off the last character to stack";
         _')=                              "Put 0 on stack if the sliced character is (,
                                            else 1 if sliced character is )";
             @~                            "bring forth the remaining
                                            brackets after slicing and evaluate them";
               zS*                         "Stack has negative depth number, take absolute
                                            value and get that many spaces";
                  \+                       "Prepend to the sliced character";
                      _$0=,                "Get the maximum depth of brackets";
                           f{Se]}          "Pad enough spaces after each string to match
                                            the length of each part";
                                 zN*       "Transpose and join with new lines";

```

Try it online here

# Answer
> 4 votes
# Octave, 85 chars

```
function r=p(s)i=j=0;for b=s k=b==40;k&&++j;t(j,++i)=9-k;k||--j;r=char(t+32);end;end

```

It's an optimization of the naïve approach, which is actually pretty natural for Matlab and Octave:

```
function r=p(s)
i=j=1;
for b=s
 if b=='(' t(++j,i++)='(' else t(j--,i++)=')' end; end; t(~t)=' '; r=char(t);
end;

```

The table `t` may even not yet exist, and we may assign to any element right away, and it reshapes to the smallest dimension that is required for this element to exist which is quite convenient.

# Answer
> 4 votes
# Perl, ~~91~~ ~~89~~ ~~88~~ ~~84~~ ~~80~~ 79 bytes

```
$t=<>;{$_=$t;s/\((?{$l++})|.(?{--$l})/$^R==$c?$&:$"/ge;print,++$c,redo if/\S/}

```
* $t is the input string.
* $c is the depth we want to print on the current line.
* $l is the depth we are at after encountering a paren.
* $l is updated in regex embedded code blocks.
* $^R is the result of the most recent code block.

# Answer
> 4 votes
# Haskell, 154 bytes

```
f h('(':s)=h:f(h+1)s;f h(')':s)=(h-1):f(h-1)s;f _ _=[]
main=interact$ \s->unlines[[if i==h then c else ' '|(c,i)<-zip s l]|let l=f 0 s,h<-[0..maximum l]]

```

same idea as the other Haskell solution, but somewhat shorter. - Usage:

```
echo  '(((())())(()))' | runghc Golf.hs

```

# Answer
> 4 votes
# Japt, 13 bytes

```
y_ùZ<')?°T:T´

```

Try it

---

## Explanation

```
y_                :Transpose, pass each column Z through a function and transpose back
   Z<')           :  Is Z less than ")", i.e., is Z equal to "("?
       ?          :  If so
        °T        :   Prefix increment variable T (initially 0)
          :       :  Else
           T´     :   Postfix decrement T
  ù               :  Left pad Z with spaces to length T

```

# Answer
> 4 votes
# Brain-Flak, 338 bytes

```
([]){(({})[()]<([{}][])([][()]){({}[()]<(({}<(({})(())){({}[()]<([{}]())>)}>{})<({}{})((){[()](<{}<>((((()()()()){}){}){})<>>)}{}){{}(({})<>)(<>)}{}(({})(())){({}[()]<([{}])>)}{}>{}<({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<>>)>)}{}{}<>((()()()()()){})<>>)}{}{{}}<>{{}{}(({})[((((()()()){}())){}{}){}]())}{}{({}<>)<>}<>

```

Try it online!

## Idea

The idea for this program is that we make a number of passes over the string. Each time we make a pass we keep track of a counter, we decrement the counter if we encounter a `(` and increment it if we encounter a `)`. If `(` brings it to -1 we copy it to the offstack and if `)` brings it to zero we copy it to the offstack. Otherwise we just copy a space. We do this as many times as the length of the string starting the counter at 0 the first time and decreasing it each loop. This way we catch the different layers in order. When we are done we just trim characters until we reach a `)`.

# Answer
> 4 votes
# 05AB1E, ~~14~~ 11 bytes

```
2IDÇÉü+>4αΛ

```

Try it online.

**Explanation:**

```
2        # Push 2
I        # Push the input-string
D        # Create a copy of the input-string,
 Ç       # and convert it to a list of codepoint integers: ")"→41; "("→40
  É      # Check for each if it's odd: ")"→1; "("→0
   ü     # For each overlapping pair:
    +    #  Add them together: "(("→0; "()"→1; ")("→1; "))"→2
     >   # Increase each by 1: "(("→1; "()"→2; ")("→2; "))"→3
      4α # Take the absolute difference with 4: "(("→3; "()"→2; ")("→2; "))"→1
Λ        # Use the Canvas builtin with the given three arguments:
         #  - Directions: the list of 123 we created, for ↗→↘ respectively
         #  - What to draw: the third remaining copy of the input-string
         #  - Line-lengths per step: the 2

```

Here a step-by-step explanation of the output for input `(()(()())()((())))(())`:

Preparation step: the overlapping pairs are `["((","()",")(","((","()",")(","()","))",")(","()",")(","((","((","()","))","))","))",")(","((","()","))"]`, which are mapped with `DÇÉü+>4α` to `[3,2,2,3,2,2,2,1,2,2,2,3,3,2,1,1,1,2,3,2,1]`, which indicate the directions `[↘,→,→,↘,→,→,→,↗,→,→,→,↘,↘,→,↗,↗,↗,→,↘,→,↗]`:

```
7   0   1
  ↖ ↑ ↗
6 ← X → 2
  ↙ ↓ ↘
5   4   3

```

When we use the Canvas builtin, it then draws like this:

Step 1: draw `2` characters (`((`) in direction `3` ():

```
(
 (

```

Step 2: draw `2-1` characters (`)`) in direction `2` ():

```
(
 ()

```

Step 3: draw `2-1` characters (`(`) in direction `2` ():

```
(
 ()(

```

Step 4: draw `2-1` characters (`(`) in direction `3` ():

```
(
 ()(
    (

```

Etc.

For an in-depth explanation of the Canvas builtin I can refer to this 05AB1E tip of mine.

# Answer
> 4 votes
# Pip `-l`, ~~23~~ ~~22~~ 21 bytes

```
ZJ:sX{%Aa?DiUi-1}._Ma

```

Attempt This Online! Or, here's a 25-byte equivalent in Pip Classic: Try it online!

### Reminiscence

Pip, old chap, how far we've come.

This clunky 53-byter was my first Pip answer on this site, over six years ago. I'd like to leave that answer untouched as a historical artifact, so I'm posting my modern Pip solution here separately. It's pretty clear that the two are different languages anyway. The old solution doesn't even work in modern Pip (though it still does on the TIO version).

### Explanation

```
ZJ:sX{%Aa?DiUi-1}._Ma
                      ; s is space; i is 0; a is command-line arg (implicit)
                   Ma ; Map this function to each character in the argument:
     { Aa       }     ;   The ASCII code of the character
      %               ;   Mod 2
         ?            ;   Is that truthy (1, close paren) or falsey (0, open paren)?
          Di          ;    If truthy, decrement i and return it
            Ui        ;    If falsey, increment i
              -1      ;    and return i-1 (i.e. the previous value of i)
   sX                 ;   Make a string of that many spaces
                 ._   ;   Concatenate the parenthesis to it
ZJ:                   ; Zip the list of strings to transpose it, padding to
                      ; a rectangle using spaces
                      ; Autoprint (implicit), each sublist on its own line (-l flag)

```

# Answer
> 3 votes
# Ruby, ~~119~~ ~~115~~ 114

```
->s{r=[""]*s.size
d=0
s.chars.map{|l|r.map!{|s|s+" "}
b=l>"("?1:0
d-=b
r[d][-1]=l
d+=1-b}.max.times{|i|puts r[i]}}

```

Explanation:

```
->s{r=[""]*s.size  # Take an array of strings big enough
d=0                # This will contain the current depth
s.chars.map{|l|r.map!{|s|s+" "}  # Add a new space to every array
b=l>"("?1:0       # Inc/Dec value of the depth
d-=b               # Decrement depth if we are at a closing paren
r[d][-1]=l         # Set the corresponding space to the actual open/close paren
d+=1-b             # Increment the depth if we are at a opening paren
}.max.times{|i|puts r[i]}}  # Print only the lines up to the max depth

```

# Answer
> 3 votes
# J, 46

Not as great as the other 'golfing languages', but in my defence: J is terrible with strings.

```
[:|:(((,~(' '#~]))"0)(0,2%~[:+/\2+/\1-'(('i.]))~

```

Takes the string as input for a function. There's also probably a better way to do it in J.

## Usage:

```
   f=:[:|:(((,~(' '#~]))"0)(0,2%~[:+/\2+/\1-'(('i.]))~
   f '(()(()())()((())))(())'
(                )(  )
 ()(    )()(    )  ()
    ()()    (  )
             ()

```

# Answer
> 3 votes
# Java, ~~233~~ 214 bytes

```
void f(String s){int p,x,d,l=s.length();char c,m[]=new char[l*l];java.util.Arrays.fill(m,' ');p=x=0;while(x<l){d=(c=s.charAt(x))==40?p++:--p;m[d*l+x++]=c;}for(x=0;x<l*l;x++)System.out.print((x%l==0?"\n":"")+m[x]);}

```

Indented:

```
void f(String s){
    int p, x, d, l = s.length();
    char c, m[] = new char[l * l];
    java.util.Arrays.fill(m, ' ');
    p = x = 0;
    while (x < l){
        d = (c = s.charAt(x)) == 40
                ? p++
                : --p;
        m[d * l + x++] = c;
    }
    for (x = 0; x < l * l; x++)
        System.out.print((x % l == 0 ? "\n" : "") + m[x]);
}

```

I guess the final loop could be shortened, but I'll leave it as an exercise to the reader. ;-)

---

Old, 233 bytes answer:

```
void f(String s){int y=s.length(),x=0;char[][]m=new char[y][y];for(char[]q:m)java.util.Arrays.fill(q,' ');y=0;for(char c:s.toCharArray())if(c=='(')m[y++][x++]=c;else m[--y][x++]=c;for(char[]q:m)System.out.println(String.valueOf(q));}

```

Indented:

```
static void f(String s) {
    int y = s.length(), x = 0;
    char[][] m = new char[y][y];
    for(char[] q : m)
        java.util.Arrays.fill(q, ' ');
    y = 0;
    for(char c : s.toCharArray())
        if(c == '(')
            m[y++][x++] = c;
        else
            m[--y][x++] = c;
    for(char[] q : m)
        System.out.println(String.valueOf(q));
}

```

# Answer
> 3 votes
# C, 118 117 Bytes

Another answer in C, but mine is shorter.

```
c;d;main(m,v)int**v;{while(d++<m){char*p=v[1];while(*p)c+=*p==40,putchar(c-d?*p:32),m=c>m?c:m,c-=*p++==41;puts("");}}

```

Ungolfed version:

```
c; /* current depth */
d; /* depth to print in current row */
main(m,v)int**v;{
    while(d++<m) {
        char*p=v[1];
        while(*p){
            c+=*p==40;           /* 40 = '(' */
            putchar(c-d?*p:32); /* 32 = ' ' (space) */
            m=c>m?c:m;           /* search maximum depth */
            c-=*p++==41;         /* 41 = ')' */
        }
        puts("");
    }
}

```

And it works!

```
% ./telescope '()(())((()))(())()'
()(  )(    )(  )()
   ()  (  )  ()
        ()
% ./telescope '((()())()(()(())()))'
(                  )
 (    )()(        )
  ()()    ()(  )()
             ()

```

# Answer
> 3 votes
# Batch, 424 bytes

```
@echo off
setLocal enableDelayedExpansion
set s=%1
set a=1
:c
if defined s (set/ac+=1
set "z="
if "%s:~0,1%"=="(" (set "1=(")else (set/aa-=1
set "1=)")
for %%a in (!a!)do for /f usebackq %%b in (`powershell "'!l%%a!'".Length`)do (set/ay=!c!-%%b
for /l %%a in (1,1,!y!)do set z= !z!
set "l%%a=!l%%a!!z!!1!")
if "%s:~0,1%"=="(" set/aa+=1
if !a! GTR !l! set/al=!a!-1
set "s=%s:~1%"
goto c)
for /l %%a in (1,1,!l!)do echo !l%%a!

```

## Un-golfed:

```
@echo off
setLocal enableDelayedExpansion

set s=%1
set a=1
set c=0
set l=0

:c
if defined s (
    set /a c+=1
    set "z="
    if "%s:~0,1%"=="(" (
        set "1=("
    ) else (
        set /a a-=1
        set "1=)"
    )
    for %%a in (!a!) do for /f usebackq %%b in (`powershell "'!l%%a!'".Length`) do (
        set /a y=!c!-%%b
        for /l %%a in (1,1,!y!) do set z= !z!
        set "l%%a=!l%%a!!z!!1!"
    )
    if "%s:~0,1%"=="(" set /a a+=1
    if !a! GTR !l! set /a l=!a!-1
    set "s=%s:~1%"
    goto c
)

for /l %%a in (1,1,!l!) do echo !l%%a!

```

Example:

```
h:\>par.bat (((())())(()))
 (            )
  (      )(  )
   (  )()  ()
    ()

```

# Answer
> 3 votes
# C#, 195 bytes

First try at golf - yell if I did something wrong.

Alternative C# version using SetCursorPosition and working left to right taking the input as a commandline arg.

```
using System;class P{static void Main(string[] a){Action<int,int>p=Console.SetCursorPosition;int r=0,c=0;foreach(var x in a[0]){r+=x==')'?-1:0;p(c,r);Console.Write(x);r+=x=='('?1:0;p(c,r);c++;}}}

```

I thought it would be fun to adjust the write position based on the open/close paren and not full lines. Close paren moves the position up before writing; open paren moves it down after writing. Actioning SetCursorPosition saves five bytes. Moving the cursor to the next line after the output would take quite a bit extra.

```
using System;
class P
{
    static void Main(string[] a)
    {
        Action<int, int> p = Console.SetCursorPosition;
        int r = 0, c = 0;
        foreach (var x in a[0])
        {
            r += x == ')' ? -1 : 0;
            p(c, r);
            Console.Write(x);
            r += x == '(' ? 1 : 0;
            p(c, r);
            c++;
        }
    }
}

```

# Answer
> 3 votes
# Batch, ~~356~~ 335 bytes

I know that there already exists a Batch solution for this challenge, but this one is golfed significantly more and seems to take a different approach. Most importantly, the other batch solution contains at least one powershell command; this solution does not.

```
@echo off
setlocal enabledelayedexpansion
set p=%1
set p=%p:(="(",%
set p=%p:)=")",%
set c=0
for %%a in (%p%)do (if ")"==%%a set/ac-=1
set d=!d!,!c!%%~a
if "("==%%a set/ac+=1&if !c! GTR !m! set m=!c!)
set/am-=1
for /l %%a in (0,1,!m!)do (for %%b in (!d!)do (set t=%%b
if "%%a"=="!t:~0,-1!" (cd|set/p=!t:~-1!)else (cd|set/p=. ))
echo.)

```

There is a backspace character (`U+0008`) on the second to last line following the dot (line 12, column 57). This isn't visible in the code posted here but is included in the byte count.

# Answer
> 3 votes
# Haskell, 107 bytes

```
h#('(':s)=h:(h+1)#s
h#(_:s)|k<-h-1=k:k#s
_#_=[]
g s=[do(c,i)<-zip s$0#s;max" "[c|i==h]|h<-[0..maximum$0#s]]

```

Try it online!

Based on d8d0d65b3f7cf42's Haskell answer.

# Answer
> 2 votes
# Haskell, 227 bytes

```
n _ []=[]
n h ('(':r)=('(',h):n(h+1)r
n d (')':r)=let h=d-1 in(')',h):n h r
m n []=n
m n ((_,h):r)=m(max h n)r
p s=let v=n 0 s;h=m 0 v;in map(\d->map(\(b,l)->if l==d then b else ' ')v)[0..h]
main=fmap p getLine>>=mapM_ putStrLn

```

# Answer
> 2 votes
# Perl, 76 bytes

```
$a[/\(/?$l++:--$l][$i++]=$_ for split//,<>;print map{$_||' '}@$_,"\n"for@a

```

No `use strict` here :)

# Answer
> 2 votes
# Lex, 94 bytes

Depends on Linux console codes. With gcc, you can cut out four bytes by replacing both instances of `\33` with an actual escape character.

```
%%
 int p[2]={0};
\( printf("(\33D");++p[!*p];
\) printf("\33M)");--*p;
\n while(p[1]--)ECHO;

```

To compile and run:

```
$ flex -o telescopic.c telescopic.l
$ gcc -o telecopic telescopic.c -lfl
$ ./telescopic
(()(()())()((())))(())
(                )(  )
 ()(    )()(    )  ()
    ()()    (  )
             ()
--- type ctrl-D ---

```

# Answer
> 2 votes
# Python 2, 166 bytes

Not much to be said:

```
m,c,l=list(input()),0,[]
for j in m:c+=1if j=='('else-1;l+=[c-1if j=='('else c]
for i in range(max(l)+1):
 t,p='',0
 for q in m:t+=q if l[p]==i else' ';p+=1
 print t

```

# Answer
> 2 votes
# Jelly, 15 bytes

```
OḂ-*Ä+ƲṬ€z0ao⁶Y

```

Try it online!

Went through quite  few 16-byters before arriving at this...

```
O                  Codepoints
 Ḃ                 mod 2. ('(' -> 0, ')' -> 1)
    Ä              Cumulative sums of
  -*               -1 to the power of each,
     +Ʋ            plus the corresponding original residues.
       Ṭ€          For each, an array with 1 at that index and 0 elsewhere.
         z0        Zip filling with zeroes,
           a       replace ones with corresponding elements of the input string,
            o⁶     replace zeroes with spaces,
              Y    join on newlines.

```

# Answer
> 2 votes
# K (ngn/k), 29 bytes

```
{+(|/i)$(-i:m-+\m-~m:2!x)$'x}

```

Try it online!

* `(...)$'x` left-pad each character of the input by the corresponding number of spaces
    + `m:2!x` take the input string mod 2 and store in `m`; translates `"("` into `0` and `")"` into `1`
    + `m-~m` convert `0`s to `-1`s (leaving `1`s as-is)
    + `i:m-+\` calculate the "depth" of each character, storing in `i`
    + `-i` negate to left-pad (positive numbers will right-pad)
* `+(|/i)$` right-pad each string with spaces to the same length, then transpose the result

# Answer
> 1 votes
# IDL 8.4, ~~173~~ 177 bytes

This is similar enough to the formatter challenge that I had half a solution already. IDL is still a terrible golfing language, but I'm pretty happy with how this worked out.

```
read,(p='')&a=[0:strlen(p)-1]&c=strmid(p,a,1)&e=c.map(lambda(x,d:'('eq x:d++:d---1)))&print,[0:max(e)].map(lambda(x,y,z:y.reduce(lambda(t,u,v,w,:t+(w eq v?u:' ')),x,z),c,a))&end

```

Un-golfed:

```
read,(p='') ;read a string from input
a=[0:strlen(p)-1] ;index array to the input
c=strmid(p,a,1) ;split the input into an array of 1-char substrings
e=c.map(lambda(x,d:'('eq x:d++:d---1))) ;for each substring, increment depth if ( and decrement otherwise, saving depth each time
print,[0:max(e)].map(lambda(x,y,z:y.reduce(lambda(t,u,v,w,:t+(w eq v?u:' ')),x,z),c,a)) ;print an array of strings, each one including the parens in that depth level.
end ;end the script

```

# Answer
> 1 votes
# C#, 196 bytes

Very simple complete program that takes input via STDIN, and outputs to STDOUT. I should like to get rid of the `S.Length`, but haven't found a way that pays.

```
using Q=System.Console;class P{static void Main(){var S=Q.ReadLine();for(int i=0,c;++i<S.Length;){var r="";c=0;foreach(var k in S)r+=(c+=81-k*2)+k-40==i?k:' ';if(r.Contains("("))Q.WriteLine(r);}}}

```

It simply iterates over the input a number of times (input length - 1), keeping track of the parentheses "depth", and comparing it to the current iteration count (`i`) - if they match, then it adds the current parenthesis to a string, to be printed at the end of the iteration. Because more iterations may be done than necessary, it only prints the iteration result (`r`) if it contains a parenthesis.

```
using Q=System.Console;

class P
{
    static void Main()
    {
        var S=Q.ReadLine(); // read input

        for(int i=0,c;
            ++i<S.Length; // can't be more than S.Length - 1 lines of output
            )
        {
            var r=""; // reset result
            c=0; // current paren depth
            foreach(var k in S) // for each char in input
                r+= // append something...
                    (c+=81-k*2) // move c
                    +k-40==i? // check if we should output the current char
                        k:
                        ' '; // otherwise a space
            if(r.Contains("(")) // only print if there is some content
                Q.WriteLine(r);
        }
    }
}

```

# Answer
> 1 votes
# MATL, ~~42~~ 41 bytes

Uses current version (4.0.0) of the language, which is *newer* than this challenge (but the challenge was so attractive...)

```
j32-t8=2*1-TTo3X53$X+ZSYsP0hP1+wtn:wZ?32+c

```

*EDIT (May 20, 2016): Try it online! with `X+` replaced by `Y+`, according to version 18.0.0 of the language.*

### Example

```
>> matl j32-t8=2*1-TTo3X53$X+ZSYs0wh1+wtn:wZ?32+c
> ()(())((()))(())()
()(  )(    )(  )()
   ()  (  )  ()
        ()

```

### Explanation

The general idea is to use convolution to analyze pairs of consecutive symbols. There are four possible pairs:

* `((`: the second symbol should be on a lower line than the first
* `))`: the second symbol should be on a higher line than the first
* `()` or `)(`: the second symbol should be on the same line as the first

When analyzing each pair, the line of the first symbol is already known, and the analysis tells the line of the second. Then the nex pair is analyzed, obtained by advancing one symbol, that is, with overlapping.

```
j           % input string
32          % ASCII code of space character
-           % subtraction. Will give 8 or 9 for '(' and ')'
t8=         % 1 for '(' symbols, 0 for ')'
2*1-        % convert into 1 / -1
TTo         % array [1 1] (for convolution)
3X5         % 'valid' flag for convolution
3$          % specify three inputs for convolution
X+          % convolution
ZS          % sign function
Ys          % cumulative sum
0wh         % prepend a 0
1+          % add 1. This gives line number of each symbol
wtn:w       % Vector [1 2 ... n] where n is string length. Rearrange
Z?          % create (sparse) matrix with three inputs: row, col, val
32+c        % add space code and convert to chat

```

# Answer
> 1 votes
# JavaScript (Node.js), 71 bytes

```
x=>[...x].map((_,n,s)=>s.map(c=>(c=='('?n--:++n)?' ':c).join``).join`
`

```

Try it online!

# JavaScript (Node.js), 85 bytes, just enough lines

```
x=>[...x].map((_,n,s)=>(Q=s.map(c=>(c=='('?n--:++n)?' ':c).join``)<1?'':Q+`
`).join``

```

Try it online!

# Answer
> 1 votes
# Charcoal, 12 bytes

```
ＦＳ¿⁼(ι↘(«Ｍ↑)

```

Try it online!

### Explanation

```
ＦＳ             For each character in next input as string
    ¿⁼(ι         If character is "("
        ↘(       Print "(" down and to the right - this is equivalent to printing "(" and moving down
          «Ｍ↑)  Else move up and print ")"

```

# Answer
> 1 votes
# Haskell, ~~117~~ 114 bytes

```
f(y:b)|a<-sum[1|y=='(']=a:map(+(2*a-1))(f b)
f[]=[]
p s=[[last$' ':[a|b==i]|(b,a)<-zip(f s)s]|i<-[1..maximum$f s]]

```

Try it online!

# Answer
> 1 votes
# C, ~~94~~ ~~99~~ ~~97~~ 96

```
i,j,k,l;f(char*s){for(l=0;!i--;l-=puts(""))for(j=0;k=s[j++];putchar((k&1?--l:l++)?32:k))i&=l<2;}

```

Pure C version that doesn't use the consoles escape codes. Ungolfed:

```
i,j,k,l;                 // stop,iterator,current char,level
f(char*s){
  for(l=0;               // reset level
      !i--;              // stop ? return : stop = 1;
      l-=puts(""))      // new line + next level
    for(j=0;
        k=s[j++];        // for each char
        putchar(
          (k&1?--l:l++)  // char == 41 ? prev level : next level
          ?32:k))        // only print brackets at level 0
      i&=l<2;            // if level > 1 then don't stop
}

```

Try it online!

Changelog:

* *+5 Byte* Temporary fix to match rules
* *-2 Byte* Switch `!i++` to `!i--` drops the need to reset `i`
* *-1 Byte* Switch `puts(""),--l` to `l-=puts("")` Thanks to @ceilingcat

# Answer
> 1 votes
# VIM, 101 bytes

= Enter

```
qwlmto<esc>`t@wq@w:s/()/(*)/g↵:set ve=all↵:set nows:↵set nosol↵qqvi)ygvr jPk/(↵@qq@qjjdGqeGl?*↵<C-V>ggoGr|@eq@e:%s/|//↵

```

# Answer
> 1 votes
# Retina, 65 bytes

```
./\S/{*\`\(((?<-2>(\()*\))*)\)
($.1* )
\(((?<-2>(\()*\))*)\)
 $1

```

Try it online! Note: Trailing space. Link includes test cases. Explanation:

```
.

```

Don't print the spaces left over at the end.

```
/\S/{

```

Repeat until there are only spaces left.

```
*\`

```

Print the result of this substitution without changing the current value.

```
\(((?<-2>(\()*\))*)\)
($.1* )

```

Match pairs of balanced parentheses and replace their content with a run of spaces of the same length.

```
\(((?<-2>(\()*\))*)\)
 $1

```

Match balanced parentheses and replace the outer pairs with spaces.

For Retina 0.8.2 you have the choice of this 60 byte code:

```
{*`\(((?<-2>(\()*\))*)\)
($.1$* )
\(((?<-2>(\()*\))*)\)
 $1

```

Try it online! Note: Trailing space. Link includes test cases. Explanation: The differences are as follows:

* Retina 0.8.2 doesn't have a while loop, only a convergence loop. However, this ends up printing blank lines while waiting for the loop to converge.
* Retina 0.8.2 uses `*` for much the same effect as `.*\`.
* Retina 0.8.2 uses `$*` instead of `*` in the replacement.

Alternatively, if the blank lines are a problem, you can use this 92 byte code:

```
{`.+$
$&¶$&
\(((?<-2>(\()*\))*)\)(?=.*¶.*$)
($.1$* )
\(((?<-2>(\()*\))*)\)(?=.*$)
 $1
¶ +$

```

Try it online! Link includes test cases. Explanation:

```
{`

```

Repeat until the value converges.

```
.+$
$&¶$&

```

Duplicate the last line.

```
\(((?<-2>(\()*\))*)\)(?=.*¶.*$)
($.1$* )

```

Match pairs of balanced parentheses on what used to be the last line and replace their content with a run of spaces of the same length.

```
\(((?<-2>(\()*\))*)\)(?=.*$)
 $1

```

Match pairs of balanced parentheses on the last line and replace the outer pairs with spaces.

```
¶ +$

```

Delete the last line if it's only spaces. This allows the loop to terminate.

# Answer
> 1 votes
# Haskell, 96 bytes

```
f s=fst$span(any(>' '))[do
c:d<-scanr(:)[]s
max" "[c|sum[1|')'<-d]-sum[1|'('<-c:d]==i]|i<-[0..]]

```

Try it online!

# Answer
> 0 votes
# Japt `-Rx`, 17 bytes

```
¬£®¥'(?Y´:°Y ?S:Z

```

Try it online!

### Unpacked & How it works

```
Uq mXYZ{UmZ{Z=='(?Y--:++Y ?S:Z

Uq      Convert the input string into array of chars
mXYZ{   Map with the function...
          Here, Y (index) is used as the desired level of "telescoping"
UmZ{      Map on the original input string with the function...
Z=='(?      If this char is "("...
Y--:          Decrement Y
++Y           Otherwise, increment Y
?           If Y is nonzero (i.e. this char is *not* at desired level)...
S:            Replace with a space
Z             Otherwise, use the char as-is

Flags:
-R      Join the resulting array with newline
-x      Trim the resulting string on both ends

```

Ported from @l4m2's JS solution. It actually fits into Japt's built-ins quite nicely, and trailing whitespaces can be conveniently removed with the use of `-x` flag.

# Answer
> 0 votes
# Vyxal `j`, 27 bytes

```
ƛC∷&-¥n꘍nC₂&+;:vLG£ƛ¥↲;ÞTv∑

```

Try it Online!

A mess that I'm proud of. Thanks to lyxal for fixing a bug.

# Answer
> -1 votes
# Swift 5.9, 149 bytes

```
var c=0,d=[0],t={i in(i+"",d=i.map{$0<")" ?(c,c+=1).0:(c-=1,c).1},{(0...d.max()!).map{e in.init(zip(i,d).map{$0.1==e ?$0.0:" "})}.joined}()("\n")).2}

```

I love it when I can shove everything into a single line of code (i.e. without using semicolons; I prefer to use newlines instead since they don't incur a byte penalty in Swift). `map(_:)` FTW! (Although, to be fair, tuple shenanigans make this relatively easy too...)

Here's the original, with an explanation (and a JDoodle link):

```
func telescope(_ input: String) -> String {
    // As an example, we'll pretend that `input` is
    // this string: "((()())()(()(())()))"

    // MARK: - Depth Calculation

    var currentDepth = 0
    let depths = input.map { character in
        switch character {
        // This is essentially equivalent to `currentDepth++`,
        // if that operator still existed in Swift (remember,
        // that one returns the value *before* incrementing).
        case "(": (currentDepth, currentDepth += 1).0

        // Likewise, this would be the same as `--currentDepth`
        // (the one that returns the value *after* decrementing).
        case ")": (currentDepth -= 1, currentDepth).1

        // If it isn't a parenthesis, we have some invalid input.
        default: fatalError("wtf?!?! that ain't a valid string!")
        }
    }

    // Now, for our example, `depths` is:
    // [0, 1, 2, 2, 2, 2, 1, 1, 1, 1, 2, 2, 2, 3, 3, 2, 2, 2, 1, 0]
    // (note that a depth of 0 is the topmost/outermost level)

    // Here's an alternative representation:
    // ((()())()(()(())()))
    // 01222211112223322210

    // MARK: - Tier Generation

    let depthRange = 0...depths.max()!
    let tiers = depthRange.map { depth in
        let inputWithDepths = zip(input, depths)
        let charactersOnThisTier = inputWithDepths.map { (character, otherDepth) in
            // If this character is on this tier, show it; otherwise, add a space.
            otherDepth == depth ? character : " "
        }
        return charactersOnThisTier
    }

    // MARK: - Joining

    let joinedTiers = tiers.map { String($0) }.joined(separator: "\n")
    return joinedTiers
}

```

---
Tags: code-golf, ascii-art, whitespace, balanced-string
---


title: Non-discriminating Programming

text:
# Question
Title: Non-discriminating Programming
We say a string is *non-discriminating* if each of the string's characters appears the same number of times and at least twice.

### Examples

* `"aa!1 1 !a !1"` is *non-discriminating* because each of the characters , `!`, `a` and `1` appear three times.
* `"abbaabb"` is **not** *non-discriminating* because `b` appears more often than `a`.
* `"abc"` is also **not** *non-discriminating* because the characters don't appear at least twice.

### Task

Write a ***non-discriminating*** program or function which returns a *truthy* value if a given string is *non-discriminating*, and a *falsy* value otherwise.

That is, the program run on its own source code should return a truthy value.

Each submission must be able to handle non-empty strings containing printable ASCII, as well as all characters appearing in the source code of the submission.

### Test Cases

Truthy:

```
<your program's source code>
"aaaa"
"aa!1 1 !a !1"
"aabbccddeeffgg"
"1Q!V_fSiA6Bri{|}tkDM]VjNJ=^_4(a&=?5oYa,1wh|R4YKU #9c!#Q T&f`:sm$@Xv-ugW<P)l}WP>F'jl3xmd'9Ie$MN;TrCBC/tZIL*G27byEn.g0kKhbR%>G-.5pHcL0)JZ`s:*[x2Sz68%v^Ho8+[e,{OAqn?3E<OFwX(;@yu]+z7/pdqUD"

```

Falsy:

```
"a"
"abbaabb"
"abc"
"bQf6ScA5d:4_aJ)D]2*^Mv(E}Kb7o@]krevW?eT0FW;I|J:ix %9!3Fwm;*UZGH`8tV>gy1xX<S/OA7NtB'}c u'V$L,YlYp{#[..j&gTk8jp-6RlGUL#_<^0CCZKPQfD2%s)he-BMRu1n?qdi/!5q=wn$ora+X,POzzHNh=(4{m`39I|s[+E@&y>"

```

# Answer
> 40 votes
# Brachylog, 10 bytes

```
=ᵍbᵐbᵐlᵍ=l

```

Try it online!

### Explanation

```
=ᵍ                Group all equal elements together
  bᵐbᵐ            Remove the first element of each group twice. This fails if
                  there are fewer than 2 elements
      lᵍ          Group elements together that have the same length
        =         Are all elements of that list equal? This only succeeds if the
                  list has one element
         l        Length. This will always succeed

```

# Answer
> 27 votes
# Java 8, ~~198~~ ~~192~~ ~~186~~ ~~174~~ ~~168~~ ~~165~~ 160 bytes (char-count ~~6~~ 5)

```
o->{byte x[]=new byte[+333-3|2],u=-0,i,fe,fi,w; s:w:no0r3sswwyyy:for(int s:o){{u=++x[s];}};for(int b:x){if(!!!(2>b||u==b)|2>u|2>2){x[0]++;}}return!!(0>--x[0]);}

```

Try it online.
Code used to verify the occurrences of the characters, which was my answer for this challenge.

-5 bytes thanks to *@OlivierGrégoire* again by getting rid of the comment and making a mess. ;)

Old **168 bytes (char-count 6) answer**:

```
o->{int w[]=new int[2222],u=0,f=0;for(int r:o)u=++w[r];for(int e:w)if(!(2>e|u==e)|2>u)f++;return!(f>0);}//[[[]]]  !!!!e(i)++,,,,-----oo////000tuww::::{{{{{;;||||}}}}}>>

```

Try it online.
Code used to verify the occurrences of the characters excluding comment, which was my answer for this challenge.

-6 bytes thanks to *@OliverGrégoire* removing `<` by swapping the checks to `>`.

**Explanation of the base golfed program (98 bytes):**
Try it online.

```
s->{                     // Method with character-array parameter and boolean return-type
  int a[]=new int[256],  //  Occurrences integer-array containing 256 zeroes
      t=0,               //  Temp integer, starting at 0
      f=0;               //  Flag integer, starting at 0
  for(int c:s)           //  Loop over the input
    t=++a[c];            //   Increase the occurrence-counter of the current character
                         //   And set the temp integer to this value
  for(int i:a)           //  Loop over the integer-array
    if(i>1               //   If the value is filled (not 0) and at least 2,
       &i!=t             //   and it's not equal to the temp integer
       |t<2)             //   Or the temp integer is lower than 2
      f++;               //    Increase the flag-integer by 1
  return f<1;}           //  Return whether the flag integer is still 0

```

**Some things I did to reduce the amount of characters used:**

* Variable names `o`, `w`, `u`, `f`, `r`, and `e` were chosen on purpose to re-use characters we already had (but not exceeding 6).
* `2222` is used instead of `256`.
* Changed the if-check `e>0&u!=e|u<2` to `!(e<2|u==e)|u<2` to remove 6x `&`.
* Removed the two separated returns and used a flag `f`, and we return whether it is still 0 in the end (this meant I could remove the 6x `by` from `byte` now that we only use `n` in `int` 6 times instead of 8).
* `e<2` and `u<2` changed to `2>e` and `2>u` to remove 6x `<`.

**What I did to reduce the char-count 6 to 5:**

* 2x `int` to `byte` so the amount of `n` used is 4 instead of 6.
* Used `x[0]` instead of a new variable `f=0` so the amount of `=` used is 5 instead of 6.
* Changed `2222` to `3333` so the amount of `2` used is 2 instead of 6.
* Changed variables `f` and `r` again so they aren't 6 anymore either.

**What @OlivierGrégoire did to get rid of the comment, and therefore the 5x `/`:**

* Adding unused variables `,i,fe,fi,w;`.
* Adding unused labels: `s:w:no0r3sswwyyy:`.
* Adding unused `|2>2`
* Adding `{}` around the for-loops and ifs, and added an unused `{}`-block.
* Changing `!` to `!!!`.
* Changing `|` to `||`.
* Changing `333` to `+333-3|2`to get rid of leftover arithmetic operators `+-|` and the `2`.
* Changing `!(x[0]>0)` to `!!(0>--x[0])`.

# Answer
> 17 votes
# Jelly, ~~18~~ ~~16~~ ~~12~~ 10 bytes

```
Ġ¬zḊḊ¬zĠȦȦ

```

Try it online!

### How it works

```
Ġ¬zḊḊ¬zĠȦȦ  Main link. Argument: s (string)

Ġ           Group the indices of s by their corresponding elements.
            "abcba" -> [[1, 5], [2, 4], [3]]

 ¬          Take the logical NOT of each 1-based(!) index.
            [[1, 5], [2, 4], [3]] -> [[0, 0], [0, 0], [0]]

   Ḋ        Dequeue; yield s without its fist element.
            "abcba" -> "bcba"

  z         Zip-longest; zip the elements of the array to the left, using the
            string to the right as filler.
            ([[0, 0], [0, 0], [0]], "bcba") -> [[0, 0, 0], [0, 0, "bcba"]]

    Ḋ       Dequeue; remove the first array of the result.
            This yields an empty array if s does not contain duplicates.
            [[0, 0, 0], [0, 0, "bcba"]] -> [[0, 0, "bcba"]]

    ¬       Take the logical NOT of all zeros and characters.
            [[0, 0, "bcba"]] -> [[1, 1, [0, 0, 0, 0]]]

      Ġ     Group.

     z      Zip-longest. Since all arrays in the result to the left have the same
            number of elements, this is just a regular zip.
            [[1, 1, [0, 0, 0, 0]]] -> [[1], [1], [[0, 0, 0, 0]]

       Ȧ    Any and all; test if the result is non-empty and contains no zeroes,
            at any depth. Yield 1 if so, 0 if not.
            [[1], [1], [[0, 0, 0, 0]] -> 0

        Ȧ   Any and all.
            0 -> 0

```

# Answer
> 15 votes
## Brachylog, ~~14~~ 12 bytes

```
ọtᵐℕ₂ᵐ==tℕ₂ọ

```

Try it online!

### Explanation

```
ọ   Occurrences. Gives a list of [char, count] pairs for the entire input.
tᵐ  Map "tail" over this list, giving each character count.
ℕ₂ᵐ Make sure that each count is at least 2.
=   Make sure that all counts are equal.
    At this point we're done with the actual code, but we need another copy
    of each character (except ᵐ). We can just put them after this, as long as
    we make sure that they can never cause the predicate to fail.
=   Make sure that all counts are equal, again...
t   Extract the last count.
ℕ₂  Make sure that it's at least 2, again...
ọ   Get the digit occurrences in that count, this can't fail.

```

Alternative 12-byte solution that reuses `t` instead of :

```
ọtᵐ==tℕ₂ℕ₂ọᵐ

```

# Answer
> 14 votes
# T-SQL, 320 bytes (32 chars x 10 each)

Input is via pre-existing table `FILL` with varchar field `STEW`, per our IO standards.

```
WITH BUMPF AS(SeLeCT GYP=1
UNION ALL
SeLeCT GYP+1FROM BUMPF
WHeRe GYP<=1000)SeLeCT
IIF(MIN(WAXBY)<MAX(WAXBY)OR
MAX(WAXBY)<=1,+0,+1)FROM(SeLeCT
WAXBY=COUNT(1),WHICH=+1+0,HEXCHANGE=+01,HUNG=+0+1,CHLUB=+0,GEFF=+0FROM
BUMPF,FILL WHERE
GYP<=LEN(STEW)GROUP BY
SUBSTRING(STEW,GYP,1))CHEXX
OPTION(MAXRECURSION 0)----------<<<<<<

```

I have never been more pleased, yet horrified, by a piece of code.

Must be run on a server or database set to a case-sensitive collation. There are 10 each of 32 different characters, including upper and lowercase `E` (SQL commands are case-insensitive, so flipped a few as needed), spaces and tabs (tabs are shown as line breaks in the code above, for readability).

I found ways to include 10 each of the other symbols `+ = ,` in the code, but unfortunately couldn't find a way to do that with `<`, so I had to add the comment character `-`.

Here is the formatted code before I crammed in all the extra filler:

```
WITH b AS (SELECT g=1 UNION ALL SELECT g+1 FROM b WHERE g<1000)
SELECT IIF(MIN(w)<MAX(w) OR MAX(w)<1+1,0,1)
FROM(
    SELECT w=COUNT(1), --extra constant fields here are ignored
    FROM b, fill
    WHERE g < 1+LEN(stew)
    GROUP BY SUBSTRING(stew,g,1)
)a OPTION(MAXRECURSION 0)

```

The top line is a recursive CTE that generates a number table `b`, which we join to the source string to separate by character. Those characters are grouped and counted, and the `IIF` statement returns 0 or 1 depending on whether the input string is non-discriminating.

# Answer
> 13 votes
# C (gcc),  ~~333~~  168 bytes

*Thanks to @Kevin Cruijssen for saving 9 bytes and thanks to @Laikoni for saving 45 bytes!*

```
f(r,h,a){char*o=r,c[222]={!o};for(a=!o;*o;)++c[*o++];for(h=!o;222/++h;c[h]&&c[h]!=a&&(a=!*c))!a&&c[h]&&(a=c[h]);r=!(2/2/a);}/////!(())****++,,,,,[[]]fffffrr{{{{{{}}}}}}

```

Try it online!

# C, 333 bytes

```
i,v;f(S){char*s=S,L[128]={0};for(v=0;*s;)++L[*s++];for(i=-1;++i<128;L[i]&&L[i]-v?v=-1:0)!v&&L[i]?v=L[i]:0;return-v<-1;}/////////!!!!!!!!&&&&&(((((())))))******+++,,,,,,,----00000111122222228888888:::::::<<<<<<<===???????LLLSSSSSSS[[[]]]aaaaaaaacccccccceeeeeeeeffffffhhhhhhhhiinnnnnnnnooooooorrrrssssssttttttttuuuuuuuuvv{{{{{{{}}}}}}}

```

Even the bytecount is non-discriminating!

Try it online!

# Answer
> 12 votes
# 05AB1E, ~~20~~ ~~18~~ ~~16~~ 14 bytes

```
S¢Z≠sË*sZ¢≠SË*

```

Try it online!

The program is essentially divided into 2 parts where the goal of the first part is to do the actual task and the goal of the second part is to use the same functions as the first part without altering the result.

**Explanation (first part)**

```
S          # push input split into list of chars
 ¢         # count the occurrence of each char in input
  Z≠       # check that the max count is not 1
    sË     # check if all counts are equal
      *    # multiply

```

**Explanation (second part)**

```
s          # swap input to top of stack
 Z¢        # count the number of occurrences of the largest element
   ≠       # check that the count isn't 1
    SË     # split into list and check that each element are equal (always true)
      *    # multiply (as it is with 1, the original result is left unchanged)

```

# Answer
> 11 votes
# Husk, 14 bytes

```
§<ε#εu§m#u
m
<

```

Try it online!

## Explanation

The two short lines are no-ops, since the main function never calls them.

```
§<ε#εu§m#u  Implicit input, say S = "asasdd"
         u  Remove duplicates: "asd"
      §m#   For each, get number of occurrences in S: [2,2,2]
     u      Remove duplicates: L = [2]
   #ε       Number of elements in L that are at most 1: 0
  ε         1 if L is a singleton, 0 otherwise: 1
§<          Is the former value smaller than the latter?

```

# Answer
> 11 votes
# Python 2, ~~75~~ 69 bytes

```
def f(s):len({2<<s.count(c)-2for c,in s})<2or{{e.dil:-tu,r.dil:-tu,}}

```

Output is via presence or absence of an error. The error is either a *ValueError* (one or more characters occur only once) or a *NameError* (the character counts are unequal).

Try it online!

# Answer
> 9 votes
# Brachylog v2, 8 bytes (in Brachylog's character set)

```
oḅ\k\koḅ

```

Try it online!

Looks like there's been a golfing war going on on this question in Brachylog, so I thought I'd join in, saving a couple of bytes over the next best answer.

This is a full program that takes input as a list of character codes. (This is partly because Brachylog appears to have some very bizarre bugs related to backslashes in strings, and partly because the `\` command doesn't work on lists of strings.)

## Explanation

```
oḅ\k\koḅ
o          Sort {standard input}
 ḅ         Group identical adjacent values
  \        Assert rectangular; if it is, swap rows and columns
   k       Delete last element
    \      Assert rectangular; (rest of the program is irrelevant)

```

The `koḅ` at the end is irrelevant; `k` will always have an element to act on and `o` and  cannot fail if given a list as input.

The reason for the starting `oḅ` should be clear; it partitions the input list by value, e.g. `[1,2,1,2,4,1]` would become `[[1,1,1],[2,2],[4]]`. In order for each character to appear the same number of times, each of these lists must be the same length, i.e. the resulting list is a rectangle. We can assert this rectangularity using `\`, which also transposes the rows and columns as a side effect.

We now have a current value consisting of multiple copies of the character set, e.g. if the input was `[4,2,1,2,4,1]` the current value would be `[[1,2,4],[1,2,4]]`. If we delete a copy, the resulting matrix is still rectangular, so we can turn it back using `\`. However, if the reason the matrix was rectangular was that all the input characters were distinct, the resulting matrix will have no elements left, and `\` does *not* treat a "0×0" matrix as rectangular (rather, it fails). So `oḅ\k\` effectively asserts that each character that appears in the input appears the same number of times, and that number of times is not 1.

That's the entire functionality of our program (as a full program, we get `true` if no assertion failures occurred, `false` if some did). We do have to obey the source layout restriction, though, so I added an additional `koḅ` that has no purpose but which cannot fail (unlike `\`, `o` and  are happy to act on empty lists).

# Answer
> 8 votes
# JavaScript (Node.js), ~~144~~ ... ~~100~~ 96 bytes

```
o=>!(a=o.split``.map(i=>o.split(i||aeehhhlmmnnnpst)[`length`]-1)).some(g=>![g>1][-!1]||a[-!1]-g)

```

Try it online!

~~24 different characters * 6 times each~~

~~28 different characters * 5 times each~~

~~27 different characters * 5 times each~~

~~27 different characters * 4 times each~~

~~26 different characters * 4 times each~~

~~25 different characters * 4 times each~~

24 different characters * 4 times each

**Explanation**

```
o=>!(
 a=o.split``.map(                            // Split the input into character array and
  i=>o.split(i||aeehhhlmmnnnpst)[`length`]-1 // count the occurrences of each character.
 )
).some(                                      // Then check
 g=>![g>1][-!1]                              // If each character appears at least twice
 ||a[-!1]-g                                  // and the counts are all the same number.
)

More to add:
1. Using {s.split``} instead of {[...s]} is to reduce the number of {.} that dominates
   the count.
2. Using {!c.some} instead of {c.every} to reduce the number of inefficient characters
   (v,r,y in every)
3. Still one unavoidable inefficient character left ({h}).

Update:
1. Got rid of one {.} by replacing {.length} by {["length"]}.
2. Got rid of one {=} by replacing {c[-!1]!=g} by {c[-!1]-g}.
3. Got rid of one {()} by replacing {!(g>1)} by {![g>1][-!1]}.
4. Finally, because count per character is now 4, the backslashes can be taken out.

Update:
1. Got rid of all {"} by replacing {"length"} by {`length`} and exploiting shortcut
   evaluation.
   {aaaeehhhlmmnnnpst} is not defined but is not evaluated either because of {c} which
   must be evaluated to true.

Update:
1. Got rid of all {c} by shortcutting the undefined variable at {split(i)} and replacing
   all {c} by {a}.
   Since {i} is never an empty string, it is always evaluated true (except compared
   directly to true).

Update:
1. Got rid of all {,} by moving the assignment after the argument list. The {()} at the
   front can therefore be moved to the assignment, retaining same number of {()}s.

```

# Answer
> 8 votes
# Python 2, ~~84~~ 80 bytes

```
x=input()
c=map(x.count,x)
print max(c)==min(c)>1
1. or our>ram>>utopia,
1., 1.,

```

Try it online!

# Answer
> 6 votes
# Brachylog, 18 bytes

```
oḅlᵐ=h≥2
oḅlᵐ=h≥2

```

Try it online!

Unfortunately, I can't remove the linefeeds, since  on a number triggers a fail.

# Answer
> 6 votes
# Python 2, ~~108~~ ~~104~~ ~~92~~ 88 bytes

-12 bytes thanks to Rod
-4 bytes thanks to Kevin Cruijssen

```
s=input();c=s.count;print[all(c(s[[]>[1]])==c(o)>1. for o in s)];aaafffillpprrtuu>1.>1.;

```

Try it online!

# Answer
> 6 votes
# PowerShell, 104 bytes

```
($qe=$args[0]| group |sort count|% count)[0]-eq$qe[-1]-and$qe[0]-gt1####((()))%%%pppddd===aaccss11nu|0gr

```

Try it online!

This was great fun to golf. The limitation was `$`, which we need four of at minimum (one for the input `$args`, one for assigning the computation result `$qe`, one for checking the last character `$qe[-1]` and one for checking the first character `$qe[0]`, so that was the working maximum number of characters.

From there, it was a matter of golfing (and not-golfing, like having a two-letter variable name) to get the program nicely divisible by four. Note that we have a small comment (everything following the `#`) to account for some missing elements, but I tried to keep the comment as small as possible.

# Answer
> 6 votes
## Haskell, ~~90~~ ~~75~~ 72 bytes

```
a[i]|d:n<-[[i|n<-i,n==a]|a<-i]=and[[i]<d,[d|i<-n]==n]--aadd,,,,:::::<=||

```

Each character appears 6 times. The input string is taken as a singleton list.

Try it online!

For reference, old versions:

75 bytes, each char 5 times

```
n(l)|d<-[[0|n<-l,n==a]|a<-l]=and[[0]<d!!0,all(==d!!0)d]--an!((())),,,0<[]||

```

Try it online!

90 bytes, each char 3 times:

```
a x|h:u<-[sum[1|d<-x,not(d/=c)]|c<-x],"  \"\\&,../1::>acdlmmnosst">[]=h>1&&all(not.(/=h))u

```

Try it online!

# Answer
> 6 votes
# MATL, 12 bytes

```
q&=sqt&=tsvv

```

The input is a string enclosed in single quotes. Single quotes in the string are escaped by duplicating.

The output is a non-empty matrix, which is truthy if it doesn't contains zeros, and is falsy if it contains at least a zero.

Try it online! Or verify all test cases, including the standard truthiness/falsiness test for convenience.

### How it works

Statements marked with `(*)` are neither necessary nor harmful, and have been included only to make the source code non-discriminating.

```
q     % Implicit input. Convert chars to code points and subtract 1 from each (*)
&=    % Square matrix of all pairwise equality comparisons
s     % Sum of each column. Gives a row vector
q     % Subtract 1 from each value. An entry equal to 0 indicates the input string
      % is discriminating because some character appears only once
t     % Duplicate
&=    % Square matrix of all pairwise equality comparisons. An entry equal to 0
      % indicates the input string is discriminating because some character is
      % more repeated than some other
t     % Duplicate (*)
s     % Sum of each column (*) (all those sums will be positive if the previous
      % matrix doesn't contain zeros)
v     % Vertically concatenate the matrix and the vector of its column sums
v     % Vertically concatenate the resulting matrix with nothing (*)
      % Implicit display

```

# Answer
> 5 votes
# Ruby, ~~87~~ 78 bytes

```
c=->m{y=m.chars;x=y.map{|d|y.count d}|[];x[-1]>1and not x[1]};->{pushrortpush}

```

26 characters repeated 3 times each

Try it online!

# Answer
> 5 votes
# Perl 5, `-p` 57 bytes

Each character appears 3 times. Only a single `1` doesn't do anything

12 bytes added to a basic 45 character solution to make in non-discriminating

```
s{.}[@m[@1{$&}+=$.].=g]eg;$\=s()(e@m;1)&&m[e(\sg+)\1+;]}{

```

Try it online!

# Answer
> 5 votes
# , 90 bytes

```
"?"=`u\164f8ToI\x6Et`;'!'=prod;!{y<-xtabs(~?readLines())}%in%{z<-y[1]}&z>T##&[]>~48bEfILpu

```

Try it online!

Outputs `TRUE` for a non-discriminating string, and `FALSE` for a discriminating string. I have written a lot of ugly code for challenges on this site, but I think this is the ugliest so far.

45 characters, used twice each (including a few in a comment). The previous best R answer was 116 bytes, with 29 characters used 4 times each; I am posting this separately since it is substantially different.

The code is equivalent to

```
y = table(utf8ToInt(readLines()))
z = y[1]
all(y == z) & (z > 1)

```

which converts the input to a vector of integers, computes a contingency table `y` of the values, then checks that all counts in that table are equal to the first count, and that the first count is greater than 1.

The initial difficulty was in using only 2 pairs of brackets. This is achieved by redefining the unary functions `!` and `?` to be `utf8ToInt` and `prod` respectively. (I can't use `all` because I need the `a`). There are four assignments: two with `=` and two with `<-`. This means that the equality test between `y` and `z` cannot use `y==z` nor `y-z`; `y%in%z` comes to the rescue.

Defining these functions uses up all the possible quotes: two double quotes, two single quotes, and I'll need the two backticks in the next paragraph, so I had to resort to `readLines()` instead of `scan(,"")`. (The other options, such as `scan(,letters)` or `scan(,month.abb)` all used a precious `t` which I couldn't spare.)

At this point, I had most of the building blocks: `utf8ToInt`, `prod`, `table`, `readLines`, `%in%`. Three characters appear three times in those names: `ent`. First, I discovered that `table(foo)` is equivalent to `xtabs(~foo)`, saving the `e`. I can rescue the `n` and the `t` with the hex/octal code trick; the golfiest solution is to use `u\164f8ToI\x6Et` (in backticks) for `utf8ToInt`.

# Answer
> 4 votes
## R, ~~132~~ 116 bytes

```
crudcardounenforceableuploads<-function(b){{pi&&pi[[1-!1]];;;"";{1<{f<<-table(strsplit(b,"",,,)[[1]])}}&&!!!sd(-f)}}

```

It doesn't contain any comments or superfluous strings, either, though this will probably be my only time in code golf calling a function `crudcardounenforceableuploads`. ~~There's probably a great anagram in there somewhere for the function name!~~Thanks to John Dvorak for pointing out a nice anagram solver, which I used for the name.

Character table:

```
- , ; ! " ( ) [ ] { } & < 1 a b c d e f i l n o p r s t u
4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4

```

examples:

```
> crudcardounenforceableuploads("aaabbbccc")
[1] TRUE
> crudcardounenforceableuploads("aaabbbcc")
[1] FALSE
> crudcardounenforceableuploads("abc")
[1] FALSE
> crudcardounenforceableuploads("crudcardounenforceableuploads<-function(b){{pi&&pi[[1-!1]];;;\"\";{1<{f<<-table(strsplit(b,\"\",,,)[[1]])}}&&!!!sd(-f)}}")
[1] TRUE

```

# Answer
> 4 votes
# C (gcc), 153 bytes

```
f(h,a,c,f){{{{{{{char*o=f=h,*r;for(a=!h;*o;o++){for(c=!h,r=h;*r;c+=!(*r++^*o)){}f*=!!(c^!!h)*(!a+!(a^c));a=c;}(a^c^c^f^f^h)+o,a+r,o,o,+h^*r;(a=f);}}}}}}}

```

Try it online!

Returns address of string as truthy value, and zero as falsy.

```
f(
h,                              Address of string.
a,                              # instances of previous character
c,                              # instances of current character
f                               Return value
){{{{{{{
char*o=f=h,*r;                  Point o to string, while giving f a non-zero value.
for(a=!h;*o;o++){               Set previous char count to 0, and then traverse the string.
for(c=!h,r=h;*r;                Set current char count to 0 and r to string,
                                and start counting instances of current character.
c+=!(*r++^*o))                  Add to counter if current character matches.
{}                              Lower the amount of semi-colons
f*=                             Multiply (AND) return value with:
   !!(c^!!h)                    Is current count not 1? (Must be 2 or above.)
            *(!a+!(a^c));       AND, is previous count valid (meaning this is not the first
                                character counted), and matches current count?
a=c;}                           Previous count = current count.
(a^c^c^f^f^h)+o,a+r,o,o,+h^*r;  Spend surplus characters to make source code valid.
(a=f);}}}}}}}                   Return value.

```

# Answer
> 2 votes
# Stax, ~~26~~ ~~24~~ 18 bytes

```
:u{m*_{y#m:u_hy#h*

```

Try it online!

~~Shortest solution so far that only uses printable ASCIIs~~ Beaten by MATL.

Guess I was approaching the problem the wrong way. Repeating a working block is neither golfy nor interesting. Now at least it looks better ...

## Explanation

`:u{m*` produces some garbage that does not affect the output.

```
_{y#m:u_hy#h*
_{y#m           map each character to its number of occurences in the string
     :u         all counts are equal (result 1)
       _hy#     get the count of appearance for the first character
           h    halve it and take the floor, so that 1 becomes 0(result 2)
            *   multiply the two results

```

# Answer
> 2 votes
# BASH 144 bytes

```
grep -o .|sort|uniq -c|awk '{s=$1}{e[s]=1}END{print((s>1)*(length(e)==1))}##>>>#|'#wwwuuutrqqqppooNNNnlllkkkiihhhggEEEDDDcccaaa1***{}[[[]]]...--''

```

This line of code takes an stdin string as input. "grep -o ." puts each character on a new line. "uniq -c" counts each chacter's usage. The awk script creates an array with each usage as a different element, and outputs true when there is only 1 array index and the value is at least 2. Each character is used 4 times, so this source returns true

# Answer
> 2 votes
# Pip, ~~22~~ 18 bytes

```
^1>=Y^aNaYMNy=My>1

```

Attempt This Online!

### Explanation

Each character occurs twice.

```
^1>=Y^aNaYMNy=My>1
      a             First command-line argument (a string)
     ^              Split into a list of characters
       Na           Count occurrences of each character in a
    Y               Yank the result into y
^1>=                No-op: compare with [1]
          MNy       Minimum of y
             =      is equal to
              My    Maximum of y
                >1  which is also greater than one
         Y          No-op: yank that result
                    Autoprint the result of the last expression

```

---

Alternate 18-byters:

```
Y^!1Y^aNaMNy=My!=1
Y_<=1Y_NaMa1<Ny=My

```

# Answer
> 1 votes
# SmileBASIC, ~~164~~ ~~152~~ ~~148~~ 140 bytes

```
DeF M(X)DIM W[#R]WHILE""<X
INC w[ASC(x)]X[n]=""wEND
FOR F=e#TO--nOT-LEN(W)U=w[F]H=H||U&&U<MAx(W)neXT-!!!AASSS#&&Oxx||CCLL<<wIM#
RETURN!H
enD

```

35 different characters, repeated 4 times each.

No comments were used (but the expression after `neXT` is never actually evaluated)

Script to check answers:

```
//javascript is a convenient language that I love using!
var input=document.getElementById("input");
var button=document.getElementById("button");
var output=document.getElementById("output");

button.onclick=function(){
  var text=input.value;
  var freqs={};
  for(var i=0;i<text.length;i++){
    var letter=text.charAt(i);
    if (freqs[letter]==undefined) freqs[letter]=0
    freqs[letter]++
  }
  sorted=Object.keys(freqs).sort(function(a,b){return freqs[b]-freqs[a]})
  var out="";
  var min=Infinity,max=0;
  for (var i in sorted) {
    var letter=sorted[i];
    var count=freqs[letter];
    if(count<min)min=count;
    if(count>max)max=count;
    out+="\n"+letter+":"+count;
  }
  output.textContent="min:"+min+"\nmax:"+max+"\nunique:"+sorted.length+"\nlength:"+text.length+out;
}
```

```
<textarea id="input" placeholder="code here"></textarea>
<button id="button"butt>count</button>
<pre id="output">...</pre>
```

# Answer
> 1 votes
# Retina 0.8.2, ~~168~~ 90 bytes

The output will be empty if false, or non-empty if true.

<pre><code>***???;;;;```!!$$$$MMMMOOOO..1111ssss222{{{{\^^^^

s;{O`.
M!*\`^((.)\2(?!\2))*$
(.)(?!\1)

</code></pre>

**Try it online**

### Core program (39 bytes)

```
s;{O`.
M!*\`^((.)\2(?!\2))*$
(.)(?!\1)

```

### Explanation

The entire core program is in a silent loop. The first stage sorts the input. The second stage will print the current string if it consists of successive pairs of different characters. The third stage removes the last occurrence of every character (removing one of each character in the string).

About the junk at the top: the order is important. In addition to needing to be syntactically valid, a semicolon must be after the asterisks and before the backticks, so long as `*` is in the config string, in order for it to not print.

# Answer
> 1 votes
# CoffeeScript 1, ~~96~~ ~~93~~ 90 bytes

```
(q,a=q.split(h).length-1for h in[q][0])->a.every (w,s,pplitnggffoorsvvyy)->w>1&&a[0&10]==w

```

Try it online!

Started from my ES6 answer but walked back to using `Array.every`. ~~32~~ ~~31~~ 30 tokens @ 3 each

# Answer
> 1 votes
# Whispers v2, ~~1750~~<sup>*</sup> 1305 bytes

```
> 1
> InputAll
>> ∪2
>> #2
>> #3
>> 4÷5
>> ⌊6⌋
>> L⋅7
>> Each 8 3
>> 9ᴺ
>> 2ᴺ
>> 10=11
>> 6>1
>> 12⋅13
>> Output 14

           ###########################00000000000000000000000000001111111111111111111112222222222222222222222222333333333333333333333333334444444444444444444444444445555555555555555555555555555666666666666666666666666666777777777777777777777777777788888888888888888888888888889999999999999999999999999999============================AAAAAAAAAAAAAAAAAAAAAAAAAAAAEEEEEEEEEEEEEEEEEEEEEEEEEEEEIIIIIIIIIIIIIIIIIIIIIIIIIIIILLLLLLLLLLLLLLLLLLLLLLLLLLLLOOOOOOOOOOOOOOOOOOOOOOOOOOOOaaaaaaaaaaaaaaaaaaaaaaaaaaaacccccccccccccccccccccccccccchhhhhhhhhhhhhhhhhhhhhhhhhhhhlllllllllllllllllllllllllllnnnnnnnnnnnnnnnnnnnnnnnnnnnnpppppppppppppppppppppppppppttttttttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuuuuuu÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷ᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺ∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋

```

Try it online!

<sub>* Golfs made while explaining it. You can see the original here</sub>

Interesting task, fairly boring restriction.

Unfortunately, due to the fact that every line must start with either `>>` or `>`, this forces the number of each character to be disproportionately large. Luckily, Whispers ignores every line that doesn't match one of its regexes, all of which require the line to begin with `>`. Therefore we just have a large character dump at the end of the program. In addition to this, Whispers, being designed for mathematical operations, struggles when applied to a question. Overall, this means that the task is interesting to attempt, but the source code requirements are a bit boring.

If we strip all the unnecessary characters from the program, we end up with

```
> 1
> InputAll
>> ∪2
>> #2
>> #3
>> 4÷5
>> ⌊6⌋
>> L⋅7
>> Each 8 3
>> 9ᴺ
>> 2ᴺ
>> 10=11
>> 6>1
>> 12⋅13
>> Output 14

```

Try it online!

which is the part of the code we're actually interested in.

## How *that* works

Here we conduct two key tests: the count of each is the same and the counts are greater than **1**. However, the code for these two tests are shared between them, so a complete walkthrough of the program is a more effective method of explaining this.

We start with the shared code:

```
> InputAll
>> ∪2
>> #2
>> #3
>> 4÷5

```

Here, we take the input and store it on line **2** (`> InputAll`). We then create a nique version of that string (i.e. the input without duplicate characters). With our next two lines, we take the length of the untouched input (`>> #2`) and the number of unique characters in the input (`>> #3`). Finally, we divide the former by the latter.

Why? Let's have a look at the two inputs of `aabbcc` and `abbaabb`. With the first string, the division becomes **6÷3 = 2**, and the second results in **7÷2 = 3.5**. For non-discriminating strings, the result of this division is **a)** An integer and **b)** Greater than **1**. Unfortunately, this also applies to some non-discriminating strings, such as `abbccc`, so we have to perform one more test.

```
>> ⌊6⌋
>> L⋅7
>> Each 8 3
>> 9ᴺ
>> 2ᴺ
>> 10=11

```

Note: line **6** is the result of the division.

First, we take the floor of the division, because Python strings cannot be repeated a float number of times. Then we reach our `Each` statement:

```
>> L⋅7
>> Each 8 3

```

**3** is a reference to line **3**, which contains our deduplicated input characters, so we map line **8** (`>> L⋅7`) over this list. Line **8** multiplies the character being iterated over by the floor of our division (`>> ⌊6⌋`). This creates an array of the deduplicated characters, repeated **n** times.

The results from our two previous strings, `aabbcc` and `abbaabb`, along with `abcabc`, would be `aabbcc`, `aaabbb` and `aabbcc` respectively. We can see that the first and last two are identical to their inputs, just with the letters shuffled around, whereas the middle one isn't (it has one less `b`). Therefore, we simply sort both the input and this new string, before comparing for equality:

```
>> 9ᴺ
>> 2ᴺ
>> 10=11

```

Finally, we need to check that the number of characters in the string is **2** or greater. Luckily, the division we performed earlier will always result in a value greater than **1** if a character repeats more than once, meaning we just need to assert that line **6** is greater than 1:

```
>> 6>1

```

Now we have two booleans, one for each test. They both need to be true, so we perform a logical AND (boolean multiplication) with `>> 12⋅13`, before finally outputting the final result.

# Answer
> 1 votes
# Pyth, 30 bytes

```
  "&8<MQSlqr{"&q1lJ{hMrSz8<1hJ

```

Leading spaces necessary.

Try it online!

The actual program is just `&q1lJ{hMrSz8<1hJ`. I just prepended the string `"&8<MQSlqr{"` to make it non-discriminating. But to make the string not print itself, I had to add a space, so I added 2 spaces.

```
&q1lJ{hMrSz8<1hJ

 q1l                (1 == len(
    J{                  J = deduplicate(
      hM                  map(lambda a: a[0],
        r  8                length_encode(
         Sz                   sorted(input())
                            )
                          )
                        )
                    )
&                     and
            <1hJ    (1 < J[0])

```

`length_encode` here (`r <any> 8`) takes a sequence and outputs the length of each run of the same character, ex. `"aaabbcc"` becomes `[[3, "a"], [2, "b"], [2, "c"]]`.

So this takes the input, sorts it to put in length encode, and takes the first element of each list in the resulting list (e.g. the earlier example would become `[3, 2, 2]`). This gives a count of how many times characters occur. Then it's deduplicated (the earlier example would become `[3, 2]`), and J is set to that.

Then it checks if the length is 1, i.e. there is only 1 unique number of times a character occurs, and if that is \> 1, i.e. \>= 2.

There might be a built-in to replace `rSz8` or `hMrSz8` but I can't find one.

# Answer
> 1 votes
# Perl 6, ~~58~~ 57 bytes

```
{.max==.min>()**()}o{(bag .comb){*}}###=>>abccggiinnoxx

```

Try it online!

Turns out the three character version is slightly shorter than the two character one.

# Answer
> 1 votes
# Julia 1.7, 88 bytes

```
x->(n=-[-all([])][];t=count.(x∪x,x);all(c->c==t[n]>n,t))####,,...;;>aacooouuu∪∪∪

```

Attempt This Online!

Ungolfed and unrestricted version:

```
x -> ( chars=count.(unique(x),x); all(c->c==chars[1]>1,chars) )

```

The logic ensures that each character's count is equal to the count of the first character and greater than 1. Julia 1.8 includes the relevant function `allequal`.

Golfing in Julia:

* `unique(x)` is usually substituted with `x∪x` to save bytes. Here, it is done to reduce the number of `(` and `)` used.
* Generally, `Int` and `Bool` are not converted automatically and need to be specified. It was a challenge to conjure up a `1` from the leftover characters, but I came up with `-[-all([])][]`, which relies on `-true == -1` and `-[-1][] == 1`.

# Answer
> 1 votes
# Vyxal, 16 bytes

```
≈?Ċfy‹≈ß?Ċfy‹AßA

```

Try it Online!

Non-commented 16 byter

# Answer
> 1 votes
# Go, ~~444~~ 420 bytes

```
func(s string)bool{m,c:=make(map[rune]int),make(map[int][]rune)
for _,d:=range s{m[d]++}
for o,a:=range m{if a<1+1{return 1<000000000000}
c[a]=append(c[a],o)}

//abbbbbbbbbbbcccccccdddddddddeeffffffff
//gggggggggiiiiiiiikkkkkkkkkkllllllllllmmmmmoooooo
//pppppppprssssssssstttttttuuuuuuu
//    11111111<<<<<<<<<<:::::::::
//___________+++++++++,,,,,,,======
//{{{{{{{{}}}}}}}}((((((()))))))[[[[[[]]]]]]
return len(c)==1}

```

Attempt This Online!

Adds characters as comments and whitespace to make it non-discriminating.

### Discriminated version, ~~165~~ 163 bytes

```
func(s string)bool{m,c:=make(map[rune]int),make(map[int][]rune)
for _,d:=range s{m[d]++}
for o,a:=range m{if a<2{return 1<0}
c[a]=append(c[a],o)}
return len(c)==1}

```

Attempt This Online!

# Answer
> 0 votes
## Perl 6, ~~132~~ 100 bytes

```
my &f={{$_[0]>1&&[==] $_}(.comb.categorize({$_}).values)}#myy ff[]00>>11()cobbattggrriizzvvlluuss##

```

# Answer
> 0 votes
## Pyth, 66 bytes

```
 " &&))//0<<==??@@IIJNNVVaallqq{"zJ.{zVJ=aY/zN)I&q1l.{Y<1@Y01.?0 "

```

Try it online!

Pyth (indented) | Python 3 (translation)
```
                                  | def a(A,B):
                                  |     c=list(A)
                                  |     c.append(B)
                                  |     return c
                                  | Y=[]
                                  | z=input()
 " &&))//0<<==??@@IIJNNVVaallqq{" | " &&))//0<<==??@@IIJNNVVaallqq{"
z                                 | print(z)
J.{z                              | J=set(z)
VJ                                | for N in J:
    =aY/zN)                       |     Y=a(Y,z.count(N))
I&q1l.{Y<1@Y0                     | if 1==len(set(Y)) and 1<Y[0]:
    1                             |     print(1)
.?                                | else:
    0                             |     print(0)
     "                            |     ""

```

# Answer
> 0 votes
# APL, ~~19~~ 72 bytes

This is my second attempt at golfing and also second program in APL. I cant figure out if I can do an unnamed lambda within a named function. If I can do that I can shave some bytes and make it more readable. Was happy to land on a solution so quick #I♥APL

~~`i ← ⍞ ◊ 2 ≤ ∨ / { ⍴ i ∩ ⍵ } ¨ ∪ i[⍋i]`~~

```
i←{⍞}◊{}◊{}◊◊2≤∨/∨/∨/∨/{∪⍴i∩∪⍵}¨∪i[∪⍋i]⍝⍝⍝⍝⍞⍞⍞←←←222≤≤≤¨¨¨∩∩∩⍴⍴⍴⍵⍵⍵[[[]]]⍋⍋⍋

```

Try Apl Online *Note you will need to change ⍞ to your string as character input is not supported in the online platform*

### Explination

Basically it gets character input and saves as i then sorts i and makes a list of the number of occurances of each unique element in i then it reduces the list with a logical or to check that there are the same number of each unique element and finally checks if there are at least 2 of each unique element.

Feel free to tear into my solution! I need to learn and I am still very new to APL and golfing.

## Edit!!!

I am an idiot (as was kindly pointed out in the comments) and forgot to make my program non-deterministic. **FAIL**.

quack!

# Answer
> 0 votes
# Jotlin, 116 bytes

```
{c(it).map({(_,ebb)->ebb}).l{a.none({icmp_2->icmp_2<2||icmp_2!=a[0]||",,,-->>llnnoooaettt<<<!!=[[[000!]]]".l==""})}}

```

Full program code:

```
val f: (String)->Boolean =

{c(it).map({(_,ebb)->ebb}).l{a.none({icmp_2->icmp_2<2||icmp_2!=a[0]||",,,-->>llnnoooaettt<<<!!=[[[000!]]]".l==""})}}

val trues = listOf(
        "aaaa",
        "aa!1 1 !a !1",
        "aabbccddeeffgg",
        "1Q!V_fSiA6Bri{|}tkDM]VjNJ=^_4(a&=?5oYa,1wh|R4YKU #9c!#Q T&f`:sm$@Xv-ugW<P)l}WP>F'jl3xmd'9Ie\$MN;TrCBC/tZIL*G27byEn.g0kKhbR%>G-.5pHcL0)JZ`s:*[x2Sz68%v^Ho8+[e,{OAqn?3E<OFwX(;@yu]+z7/pdqUD",
        "{c(it).map({(_,ebb)->ebb}).l{a.none({icmp_2->icmp_2<2||icmp_2!=a[0]||\",,,-->>llnnoooaettt<<<!!=[[[000!]]]\".l==\"\"})}}"
)

val falses = listOf(
        "a",
        "abbaabb",
        "abc",
        "bQf6ScA5d:4_aJ)D]2*^Mv(E}Kb7o@]krevW?eT0FW;I|J:ix %9!3Fwm;*UZGH`8tV>gy1xX<S/OA7NtB'}c u'V\$L,YlYp{#[..j&gTk8jp-6RlGUL#_<^0CCZKPQfD2%s)he-BMRu1n?qdi/!5q=wn\$ora+X,POzzHNh=(4{m`39I|s[+E@&y>"
)

for (t in trues) {
    val r1 = f(t)
    if (!r1) throw AssertionError("'$t' gave the wrong value, ($r1 != true)")
}
for (t in falses) {
    val r1 = f(t)
    if (r1) throw AssertionError("'$t' gave the wrong value ($r1 != false)")
}

```

Uses a check for lowercase equaling an empty string to get rid of extra characters.

# Answer
> 0 votes
# Pascal (FPC), ~~288~~ 280 bytes

35 distinct characters * 8 times

```
var c:char;g:array[0..222]of byte;w,v:byte;begin;repeat read(c);inc(g[ord(c)]);v:=g[ord(c)]until eof;foR w:=0to 222do if(g[w]>=2)and(g[w]<>v)oR(v<2)then v:=0;wRitE(v>0)End.,,,,,,,.....0000::<<<<<<====>>>>>[[[]]]abbbbbccddffffgghhhhhhiiilllllllnnppppppptuuuuuuuvwwwyyyyyEEEEEERRRRR

```

Try it online!

-8 bytes by kicking out `y` from the program! (See below)
Now for the reduced range of characters, but still covering printable ASCII.

This is the basic program:

```
var c:char;g:array[0..255]of byte;w,v,y:byte;begin;repeat read(c);inc(g[ord(c)]);v:=g[ord(c)]until eof;for w:=0to 255do if(g[w]>=2)and(g[w]<>v)or(v<2)then y:=2;write(y=0)end.

```

The task was juggling between number of spaces, `;`s and `()`s and it seems that less than 8 characters on all of them is impossible.
There are more than 8 of `e`s and `r`s in the basic program, so I introduced some capital letters or I would need to increase number of occurences of other characters.

# Answer
> 0 votes
# Wolfram Language (Mathematica), ~~57~~ 54 bytes

```
(Apply[Equal]@#)~And~(1<Last[#])&@*Counts

yEqd1<L*Co&

```

Try it online!

# Answer
> 0 votes
# PowerShell Core, 75 bytes

```
-!(($ps=$args| group |% co*|gu).count-1)*!($ps-le1)###1alnn*%=.raclette!.=%

```

Try it online!

Takes the input as a splatted string

# Answer
> 0 votes
# Swift 5.9, 156 bytes (39 unique chars, 4 of each char)

```
var vrum$vuv={!(!false)},
y=[+0],////&&||!>>
lomrocfacefilm$={sS in [y=(sS+"").map{p in
sS.filter{!($0<p||$0>p)}.count},
Set(y).count<1<<1&&y[+0]>1,""][+1]}

```

The function you want is `lomrocfacefilm$(_:)`. (Because apparently dollar signs are valid in identifiers as long as they're not the first character.)

I managed to get *most* of the extras shoved into the code without a comment, at the cost of creating an unmaintainable nightmare. I had fun with the names, though.

---
Tags: code-golf, string, decision-problem, restricted-source, self-validating
---