title: How many instances are running?

text:
# Question
Title: How many instances are running?
Write an indefinitely-running program that reports how many instances of itself are currently running. Each instance of the program should also report the order in which it was opened out of all other currently-running instances.

## Example

The user launches the program for the first time - we'll call this Instance 1. Instance 1 displays `1/1`, because it is the **first** instance to be launched out of a total of **1** currently-running instances.

While Instance 1 is running, the user launches the program a second time to become Instance 2. Instance 1 now displays `1/2`, being the **first** instance out of a total of **2** currently-running instances. Instance 2 displays `2/2`, because it is the **second** instance out of a total of **2** currently-running instances.

Let's say the user continues to spawn more instances until there are **5** of them. In order of launch, their outputs are: `1/5` `2/5` `3/5` `4/5` `5/5`.

Now, let's say the user decides to terminate Instance 3. Instance 4 then becomes the new Instance 3 and Instance 5 the new Instance 4, because they are respectively the **third** and **fourth** instances to have been launched out of what is now a total of **4** instances. So each instance's change in output would be as follows:

* `1/5``1/4`
* `2/5``2/4`
* `3/5` → (Terminated)
* `4/5``3/4`
* `5/5``4/4`

## Rules

* You may output the two numbers (instance number, total instances) in any reasonable format.
* Whenever an instance is launched or terminated, all other instances must update their respective outputs within 100 milliseconds.
* If you choose to update output by printing to a new line (or other "appending" output format; as opposed to replacement), you must print only when the number of instances changes, and not at any other time.
* This is code golf. Shortest program in bytes wins.
* In your answer, you are encouraged to specify what the user must do to open more than one instance, and/or record a screencast to demonstrate.

# Answer
# APL (Dyalog Unicode), 39 bytesSBCS

Anonymous prefix function. Call by spawning on the dummy argument  (empty numeric vector), i.e. `f&⍬`. Query currently running threads with `⎕TNUMS` and kill one or more threads with `⎕TKILL n`. Threads output changes in \[own number, total number\] as soon as they get processor time, i.e. pretty much instantly.

```
{⍵≡n←n[⍋n←⎕TNUMS~0]:∇n⋄∇n⊣⎕←n⍳⎕TID,⊢/n}

```

Try it online!

`{``}` anonymous lambda where  is the argument (initially , the empty numeric vector)

`n[``]` index `n` (to be defined) with:

`⎕TNUMS~0` all **T**hread **Num**bers except number `0` (the REPL)

`n←` store as `n`

permutation which would sort ascending

now we have the active threads in order

`⍵≡` if the argument is identical to that…

`:` then:

`∇⍵` tail recurse on the argument

else:

`⊢/n` the rightmost thread number

`⎕TID,` this **T**hread's **ID** (thread number) prepended to that

`n⍳` find the **ɩ**ndices of those two

`⎕←` print that to STDOUT

`n⊣` discard that in favour of `n`

recurse on that
> 4 votes

# Answer
# Python 3, ~~694~~ 691 bytes

# main.py

```
from requests import post as u
from _thread import*
import os
os.system("start cmd /C python s")
def l():
 def p(q):
  while 1:print(u(*q).text,end="\r")
 q=['http://localhost']
 q+=[u(q[0],'*').text]
 start_new_thread(p,(q,))
 input()
 u(q[0],'-'+q[1])
while 1:
 try:l();break
 except:0

```

# s (short for server.py)

```
from bottle import*
from requests import post as q
try:
 q("http://localhost")
except:
 ids=["0"]
 @post('/')
 def _():
  content = request.body.read().decode('utf-8')
  if len(content)==0:return""
  if content[0]=="*":ids.append(str(int(ids[-1])+1));return str(ids[-1])
  elif content[0]=="-":del ids[ids.index(content[1:])]
  else:return str(ids.index(content)) + "/" + str(len(ids)-1)
 run(port="80")

```

# Why is it so long?

Unfortunately, this functionality doesn't seem to be built into Python. I was tempted to use multiprocessing, but that didn't quite seem to be the right fit for what we're doing (letting a user open a program from anywhere).

So, I took the advice of a StackOverflow post I saw (I misplaced the link) and I implemented it using `bottle`. (I am open to new suggestions).

I used the Bottle library to run my own mini http server so all the different instances can communicate with each other. I suppose I could have used a socket, although I'm not convinced that would have reduced the byte count.

I have two seperate files, `s` and `main.py`. `s` is short of server and because it appears in the code, I figured I should make the name as short as possible.

# Communication Web Server's API

The web server only accepts POST requests and only responds to input inside the POST's body.

All requests go through `/` (or `localhost/`).

Valid input:

* `*` in the post body will request for the server to return a new id to assign the client.
* `-<id>` in the post body will remove the id from the active list of id's, decreasing all relevant id's and the total count.
* An empty request in the post body will simply return an empty string. This is what is used for testing to see if the server is online.

# Closing the program

I implemented multi-threading so closing the program is as simple as pressing enter.

# Opening the program

If you do not have Python setup correctly inside your environmental variables simply create a `.bat` file and put it in the same folder as `main.py` and `s` with the following code (if you installed Python for all users, it may be at a different location):

```
set PATH=%userprofile%\AppData\Local\Programs\Python\Python36
python main.py

```

# Credits

From 694 to 691 bytes Adám.
> 2 votes

# Answer
# sh + linux/unix tools, 128 bytes

if sleep supports floating point numbers

```
trap '(flock 9;grep -vw $$ p>t;mv t p)9>l' exit;(flock 9;echo $$>>p)9>l;f(){ echo $(sed -n /^$$\$/= p)/$(wc -l<p);sleep .1;f;};f

```

otherwise, 159 bytes

```
trap '(flock 9;grep -vw $$ p>t;mv t p)9>l' exit;(flock 9;echo $$>>p)9>l;perl -MTime::HiRes=usleep -nE/^$$'$/&&say("$./",$.+(@a=<>)),usleep 1e5,$.=-(@ARGV=p)' p

```

or sleep can be replaced with `:` (no-op), but it will make active waiting.
> 1 votes

# Answer
# Java 8, (199+301=) 500 bytes

**M.jar: (the main program)**

```
import javafx.collections.*;class M{static ObservableList o=FXCollections.observableArrayList();static int j,F;int i,f;{F=0;ListChangeListener e=(ListChangeListener.Change c)->{if(f<1)System.out.println((F>0&i>F?--i:i)+"/"+j);};o.addListener(e);o.add(i=++j);}public void f(){F=f=i;j--;o.remove(--i);}}

```

**S.jar: (the server to control the program-flow)**

```
import java.util.*;interface S{static void main(String[]a){List<M>l=new Stack();for(Scanner s=new Scanner(System.in);;){Float n=s.nextFloat();if(n%1==0)l.add(new M());else{int t=(int)(n*10-1);l.get(t).f();l.remove(t);}}}}

```

**Explanation of the code:**

```
import javafx.collections.*;
                  // Required import for ObservableList, FXCollections, and ListChangeListener
class M{          // Program-class
  static ObservableList o=FXCollections.observableArrayList();
                  //  Static list to keep record of all instances
  static int j,   //  Static integer (total number of instances)
             F;   //  Static flag (remove occurred?)
  int i,          //  Non-static integer (id of this instance)
      f;          //  Non-static flag (has been removed)
  {               //  Non-static initializer-block (shorter than constructor)
    F=0;          //   Reset the static flag remove_occurred, because we add a new instance
    o.addListener((ListChangeListener.Change c)->{
                  //   Add a change listener for the ObservableList
                  //   This will monitor any additions or removes on the List
       if(f<1)    //    If this instance is not removed yet:
         System.out.println(
                  //     Print:
           (F>0&i>F?
                  //      If a removed occurred and this id is larger than the removed instance
             --i  //       Decrease its id by 1 before printing it
            :     //      Else:
             i)   //       Just print its id
           +"/"+j);
                  //      Plus the total number of instances left
    });
    o.add(        //   Add anything to the Observable list to trigger the listener
     i=++j);      //    Increase the total amount of instances, and set the id of this instance to the last one
  }               //  End of non-static initializer-block
  public void f(){//  Finalize-method
    F=f=i;        //   Set both flags to the current id
    j--;          //   Decrease the total amount of instances
    o.remove(--i);//   Remove the current instance from the list to trigger the listener
  }               //  End of Finalize-method
}                 // End of Program-class

import java.util.*;
                  // Required import for List, Stack and Scanner
interface S{      // Server-class
  static void main(String[]a){
                  //  Mandatory main-method
    List<M>l=new Stack();
                  //   List of programs
    for(Scanner s=new Scanner(System.in);
                  //   Create a STDIN-listener for user input
        ;){       //   Loop indefinitely
      int t=s.nextInt();
                  //    Get the next integer inputted
      if(t<1)     //    If it's 0:
        l.add(new M());
                  //     Startup a new program, and add its instance to the list
      else{       //    Else:
        l.get(t).f();
                  //     Close the program with this integer as id
        l.remove(t);}
                  //     And remove it from the list of programs
    }             //   End of loop
  }               //  End of main-method
}                 // End of Server-class

```

**General explanation:**

All programs will keep a record of their own id; the total number of instances left; whether a remove occurred; and which programs have closed.

The server is just a wrapper-class to start and stop programs. When a user inputs `0`, it will startup a new program. When the used inputs a positive integer (i.e. `2`), it will close the program with that id. (Note: S.jar has M.jar as library to access it.)

**Gif to see it in action:**

***Thoughts to golf it further:***

I just noticed while writing the explanation that I only use the `ObservableList` for it's add/remove-`ListChangeListener`, and don't use its content at all. Removing this and using another type of static Listener might be shorter.
> 0 votes

---
Tags: code-golf, stateful
---


title: Convert exponents into ASCII art

text:
# Question
Title: Convert exponents into ASCII art
# Task

Your task is to convert strings like this:

```
abc^d+ef^g + hijk^l - M^NO^P (Ag^+)

```

To strings like this:

```
   d   g       l    N P    +
abc +ef  + hijk  - M O  (Ag )

```

Which is an approximation to abcd+efg \+ hijkl \- MNOP (Ag+)

In words, raise the characters directly next to carets to the upper line, one character for one caret.

# Specs

* Extra trailing whitespaces in the output are allowed.
* No chained carets like `m^n^o` will be given as input.
* A caret will not be followed immediately by a space or by another caret.
* A caret will not be preceded immediately by a space.
* All carets will be preceded by at least one character and followed by at least one character.
* The input string will only contain printable ASCII characters (U+0020 - U+007E)
* Instead of two lines of output, you are allowed to output an array of two strings.

To those who speak regex: the input string will match this regex:

```
/^(?!.*(\^.\^|\^\^|\^ | \^))(?!\^)[ -~]*(?<!\^)$/

```

### Leaderboard

```
var QUESTION_ID=86647,OVERRIDE_USER=48934;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 commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
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><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
# , ~~15~~ 14 bytes

```
ÄÒ +òf^xxé kPj

```

Try it online!

A fairly straightforward solution. The *perfect* challenge for V!

Explanation:

```
Ä                "Duplicate this current line
 Ò               "Replace this line with spaces
   +             "Move to the beginning of the next line
    ò         ò  "Recursively (The second ò is implicit):
     f^          "  Find a caret
       xx        "  Delete two characters. The second will be saved into the main register
         é       "  Insert a space
           k     "  Move up
            P    "  Paste from the main register
             j   "  Move down

```

Conveniently, based on how the recursion works, this will run once for every single caret.
> 19 votes

# Answer
# Cheddar, ~~77~~ ~~72~~ 67 bytes

```
l->l.chars.vfuse.replace("^\n"," ").lines.map(j->"%-2s"%j).turn(3)

```

No regex!

I love this answer as it is a wonderful demonstration of Cheddar's abilities. Mainly thanks to the replace function added by Conor. The PR to dev was never made so the replace function only exists on this branch (update: I made the PR and now it's on the latest beta branch which you can install with `npm install -g cheddar-lang`)

I have found a way to golf it but unfortunately an oversight results in this happening when item lengths are not the same:

```
["   denifednud   denifednug       denifednul    denifednuN denifednuP    denifednu+ ", "abcdenifednu +efdenifednu  + hijkdenifednu  - Mdenifednu Odenifednu  (Agdenifednu )"]

```

I could have saved a lot of bytes using regex, and in fact I *just* made regexes for Cheddar... the only problem is that there are no regex functions :/

## Explanation

```
l->                    // Function take input as `l`
   l.chars             // Get array of chars in input
   .vfuse              // Join with newlines
   .replace("^\n"," ") // Replace `^\n` with a space globally
   .lines              // Get the lines (see below for more details on what this returns)
   .map(j->            // Loop through each "line" `j` is arg
       "%-2s"          // C-like printf format.
                       // think of as: padRight(j, " ", 2)
                       // see below for more details
        % j            // Pass j as the string to insert
   ).turn(3)           // Turn the string 270 degrees (see below)
   .vfuse              // Vertically fuse to get result (this is not needed as we can output an array of the lines)

```

To get a better understanding. This is what `.lines` returns for `1^2`

```
["1", " 2"]

```

the `.turn` with rotate this:

```
1
 2

```

into:

```
 2
1

```

---

Another example which will make it more clear:

```
1
 2
2
 2

```

becomes:

```
 2 2
1 2

```

### Why format?

What the `%-2s` is doing is pretty simple. `%` specifies we are starting a "format", or that a variable will be inserted into this string at this point. `-` means to right-pad the string, and `2` is the max-length. By default it pads with spaces. `s` just specifies it's a string. To see what it does:

```
"%-2s" % "a"  == "a "
"%-2s" % " a" == " a"

```
> 18 votes

# Answer
# Perl, 21 + 1 = 22 bytes

```
say'';s/\^(.)/♥[A\1↓/

```

Run with the `-p` flag. Replace  with a raw `ESC` byte (`0x1b`), and  with a vertical tab (`0x0b`).

The vertical tab is Martin Ender’s idea. It saved two bytes! Thanks.
> 10 votes

# Answer
## JavaScript (ES6), ~~56~~ 55 bytes

```
s=>[/.(\^(.))?/g,/\^.(())/g].map(r=>s.replace(r,' $2'))

```

Regexps to the rescue of course. The first one replaces all characters with spaces, unless it finds a caret, in which case it deletes the caret and keeps the character after it. (These characters are guaranteed to exist.) The second is the obvious one to replace each caret and its following character with a space.

Edit: Saved 1 byte thanks to @Lynn who devised a way to reuse the replacement string for the second replace allowing the replace to be mapped over an array of regexps.
> 7 votes

# Answer
# Python 3, ~~157~~ ~~101~~ ~~98~~ ~~85~~ ~~83~~ 74 bytes

This solution keeps track of whether the previous character was `^`, then decides whether to output to the first or second line based on that.

Outputs as an array of `['firstline', 'secondline']`.

```
a=['']*2
l=0
for c in input():x=c=='^';a[l]+=c*x;a[~l]+=' '*x;l=x
print(a)

```

*Saved ~~13~~ 15 bytes thanks to @LeakyNun!*

*Saved 7 bytes thanks to @Joffan!*
> 6 votes

# Answer
## Python 2, 73 bytes

```
l=['']*2;p=1
for c in input():b=c!='^';l[p]+=c*b;l[~p]+=' '*b;p=b
print l

```

No regex. Remembers if the previous character was `^`, and put the current character in the top or bottom line based on that, and a space in the other one.
> 6 votes

# Answer
# Ruby, 47 + 1 (`-n` flag) = 48 bytes

```
puts$_.gsub(/\^(.)|./){$1||" "},gsub(/\^./," ")

```

Run it like so: `ruby -ne 'puts$_.gsub(/\^(.)|./){$1||" "},gsub(/\^./," ")'`
> 4 votes

# Answer
# Pyth, 17 bytes

```
CcsmX~Z1j;d;cQ\^2

             Q      input string
            c \^    split on '^'
   m                map for sections d:
    X      ;          insert a space at index:
     ~Z1                the old value of Z (initially 0), before setting Z to 1
                      into:
        j;d             the section joined on spaces
  s                 concatenate
 c              2   chop into groups of 2
C                   transpose

```

Returns an array of 2 strings. (Prepend `j` to join them with a newline.)

Try it online.
> 4 votes

# Answer
# MATL, 18 bytes

```
94=t1YSt~&vG*cw~Z)

```

**Try it online!**

```
94=    % Take input implicitly. Create logical array of the same size that contains
       % true for carets, false otherwise
t      % Push a copy of this array
1YS    % Circularly shift 1 unit to the right. This gives an array that contains true
       % for the elements right after a caret (superindices), and false for the rest
t~     % Push a copy and negate
&v     % Concatenate vertically. This gives a 2D, 2-row array
G*     % Push the input again, multiply with broadcast. This gives a 2D array in
       % which the first row contains the superindices (characters after a caret)
       % and 0 for the rest; and the second row contains the non-superindices and
       % 0 for the superindices
c      % Convert to char
w      % Swap. Brings to top the array containing true for carets and false otherwise
~      % Negate
Z)     % Use as logical index to remove rows that contain carets. Display implicitly

```
> 4 votes

# Answer
# Python (2), ~~76~~ ~~68~~ 67 Bytes

*-5 Bytes thanks to @LeakyNun*

*-3 Bytes thanks to @KevinLau-notKenny*

*-1 Byte thanks to @ValueInk*

*-0 bytes thanks to @DrGreenEggsandIronMan*

```
import re
lambda i,s=re.sub:[s("(?<!\^).\^?"," ",i),s("\^."," ",i)]

```

This anonymous Lambda function takes the input string as its only argument and returns the two output lines separated by a newline. To call it give it a name by writing "f=" before it.

Pretty straightforward regex: The first part replaces the following by a space: any character and a ~~carrot~~ caret or only a char, but only if there is no caret before them. The second part replaces any caret in the string and the char after it by a space.
> 3 votes

# Answer
## Convex, 24 bytes

```
®(?<!\^).\^?"SòNê®\^."Sò

```

Try it online!
> 2 votes

# Answer
# Retina, 16 bytes

```
S`^
\^(.)
♥[A$1↓

```

A port of my Perl answer, pointed out by Martin Ender. Replace  by a raw `ESC` byte (`0x1b`) and  with a vertical tab (`0x0b`).
> 2 votes

# Answer
## Haskell, ~~74~~ ~~56~~ 55 bytes

```
g('^':c:r)=(c,' '):g r
g(c:r)=(' ',c):g r
g x=x
unzip.g

```

Returns a pair of strings. Usage example: `unzip.g $ "abc^d+e:qf^g + hijk^l - M^NO^P: (Ag^+)"` -\> `(" d g l N P + ","abc +e:qf + hijk - M O : (Ag )")`

`g` makes a list of pairs, where the first element is the char in the upper line and the second element is the char in the lower line. `unzip` turns it into a pair of lists.

Edit: @xnor suggested `unzip` which saves 18 bytes. @Laikoni found one more byte to save. Thanks!
> 2 votes

# Answer
# shell+TeX+catdvi, ~~51~~ 43 bytes

```
tex '\empty$'$1'$\end'>n;catdvi *i|head -n2

```

Uses `tex` to typeset some beautiful mathematics, and then uses `catdvi` to make a text representation. The head command removes junk (page numbering, trailing newlines) that is otherwise present.

*Edit: Why do the long, proper, thing and redirect to `/dev/null` when you can ignore sideeffects and write to a single letter file?*

---

## Example

Input: `abc^d+ef^g + hijk^l - M^NO^P (Ag^+)`

TeX output (cropped to equation):  Final output:

```
   d   g     l  N P   +
abc +ef +hijk -M O (Ag )

```

---

Assumptions: Start in empty dir (or specifically a dir with no name ending in "i"). Input is a single argument to the shell script. Input is not an empty string.

Someone tell me if this is rule abuse, especially `catdvi`.
> 2 votes

# Answer
## Perl, 35 bytes

**34 bytes code + 1 for `-p`**

```
$_=s/\^(.)|./$1||$"/ger.s/\^./ /gr

```

### Usage

```
perl -pe '$_=s/\^(.)|./$1||$"/ger.s/\^./ /gr' <<< 'abc^d+ef^g + hijk^l - M^NO^P (Ag^+)'
   d   g       l    N P    +
abc +ef  + hijk  - M O  (Ag )

```

Note: This is exactly the same as Value Ink's answer which I spied afterwards. Will remove if needed as this doesn't really add to the Ruby solution.
> 1 votes

# Answer
## Java 8 lambda, ~~132~~ ~~128~~ 112 characters

```
i->{String[]r={"",""};for(char j=0,c;j<i.length();j++){c=i[j];r[0]+=c==94?i[++j]:32;r[1]+=c==94?32:c;}return r;}

```

The ungolfed version looks like this:

```
public class Q86647 {

    static String[] printExponents(char[] input) {
        String[] result = {"",""};
        for (char j = 0, c; j < input.length(); j++) {
            c = input[j];
            result[0] += c == 94 ? input[++j] : 32;
            result[1] += c == 94 ? 32 : c;
        }
        return result;
    }
}

```

Outputs as an array, simply checking whether there is a caret and if so the next character will be put in the upper row, else there will be a space.

---

**Updates**

Replaced characters with their ascii values to save 4 characters.

Thanks to @LeakyLun for pointing out to use a char array as input instead.

Also thanks to @KevinCruijssen for switching the `int` to `char` to save some more characters.
> 1 votes

# Answer
# Coconut, ~~122 114~~ 96 bytes

Edit: ~~8~~ 26 bytes down with help from Leaky Nun.

```
def e(s,l)=''==l and s or"^"==l[0]and l[1]+e(s+' ',l[2:])or' '+e(s+l[0],l[1:])
f=print..e$('\n')

```

So as I learned today python has a ternary conditional operator, or in fact two of them: `<true_expr> if <condition> else <false_expr>` and `<condition> and <true_expr> or <false_expr>` with last one coming with one char less.
A python conform version can be ideoned.

---

First attempt:

```
def e(s,l):
 case l:
  match['^',c]+r:return c+e(s+' ',r)
  match[c]+r:return' '+e(s+c,r)
 else:return s
f=print..e$('\n')

```

Calling with `f("abc^d+ef^g + hijk^l - M^NO^P (Ag^+)")` prints

```
   d   g       l    N P    +
abc +ef  + hijk  - M O  (Ag )

```

Anyone tried golfing in coconut yet? It enriches python with more functional programming concepts like the pattern matching and function concatenation (with `..`) used above. As this is my first try at coconut, any tips would be appreciated.

This could definitely be shortened as any valid python code is also valid coconut and shorter python answers have been posted, however I tried to find a purely functional solution.
> 1 votes

# Answer
# Gema, ~~42~~ 41 characters

```
\^?=?@set{s;$s }
?=\ @append{s;?}
\Z=\n$s

```

Gema processes input as stream, so you have to solve it in one pass: first line is written immediately as processed, second line is collected in variable $s, then output at the end.

Sample run:

```
bash-4.3$ gema '\^?=?@set{s;$s };?=\ @append{s;?};\Z=\n$s' <<< 'abc^d+ef^g + hijk^l - M^NO^P (Ag^+)'
   d   g       l    N P    +
abc +ef  + hijk  - M O  (Ag )

```
> 0 votes

# Answer
## Dyalog APL, 34 bytes

```
{(0 1=⊂b/¯1⌽b){⍺\⍺/⍵}¨⊂⍵/⍨b←⍵≠'∧'}

```

It returns a two-element vector with the two lines

Sample run (the uparrow in front is to format the two-el. vector for human consumption):

```
      ↑{(0 1=⊂b/¯1⌽b){⍺\⍺/⍵}¨⊂⍵/⍨b←⍵≠'∧'}'abc∧d+ef∧g + hijk∧l - M∧NO∧P (Ag∧+)'
   d   g       l    N P    +
abc +ef  + hijk  - M O  (Ag )

```
> 0 votes

# Answer
## PowerShell v2+, ~~88~~ 83 bytes

```
-join([char[]]$args[0]|%{if($c){$_;$b+=' '}elseif($_-94){$b+=$_;' '}$c=$_-eq94});$b

```

A little longer than the others, but showcases a little PowerShell magic and a little different logic.

Essentially the same concept as the Python answers -- we iterate over the input character-by-character, remember whether the previous one was a caret (`$c`), and put the current character into the appropriate spot. However, the logic and method for determining where to output is handled a little differently, and without a tuple or separate variables -- we test if the previous character was a caret, and if so output the character to the pipeline and concatenate a space onto `$b`. Otherwise we check if the current character is a caret `elseif($_-94)` and so long as it's not, we concatenate the current character onto `$b` and output a space to the pipeline. Finally, we set whether the current character is a caret for the next go-round.

We gather those characters from the pipeline together in parens, encapsulate them in a `-join` which turns them into a string, and leave that along with `$b` on the pipeline. Output at the end is implicit with a newline inbetween.

For comparison, here's a direct port of @xnor's Python answer, at **85 bytes**:

```
$a=,''*2;[char[]]$args[($l=0)]|%{$a[!$l]+="$_"*($c=$_-ne94);$a[$l]+=' '*$c;$l=!$c};$a

```
> 0 votes

# Answer
# Cinnamon Gum, 21 bytes

```
0000000: 5306 6533 bd92 d1db 8899 8381 a2f8 8f8c  S.e3............
0000010: 1230 249e a1                             .0$..

```

Non-competing. Try it online.

## Explanation

I'm not much of a regex golfer so there's probably a better way to do this.

The string decompresses to:

```
S(?<!\^)[^^]& &\^&`S\^.&

```

(note the trailing space)

The first `S` stage receives input and uses a negative lookbehind to replace all characters other than carets with no preceding caret with a space, then deletes all carets. Then it immediately outputs the modified input string with a newline and removes that `S` stage. Since STDIN is now exhausted and the previous stage didn't provide any input, the next `S` stage receives the last line of STDIN again and then replaces all carets followed by any character with a space and outputs that.

In Perl psuedo-code:

```
$first_stage_sub_1 = ($input =~ s/(?<!\^)[^^]/ /gr);
$first_stage_sub_2 = ($first_stage_sub_1 =~ s/\^//gr);
print $first_stage_sub_2, "\n";

$second_stage_sub = ($input =~ s/\^./ /gr);
print $second_stage_sub, "\n";

```
> 0 votes

# Answer
# , ~~28~~ 27 bytes

```
0|:t#]{."0~_1-_1|.t=.'^'~:]

```

Try it online!

```
                  t=.'^'~:]    0 for ^, 1 for the rest, define t
              _1|.             Shift right, now zeroes are for superscripts
     ]{."0~_1-                 Prepend that many spaces to each character
   t#                          Remove the rows with carets
0|:                            Transpose

```

There must be a better way...
> 0 votes

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


title: N-bit Variation on Subset-Sum

text:
# Question
Title: N-bit Variation on Subset-Sum
For another challenge I am writing, I need to verify that test cases are solveable with bounded integers. Specifically, I need to verify the following, for a non-empty array of integers `A` and an integer bit width `n`:

1. All integers `a` in `A` satisfy `-2**(n-1) <= a < 2**(n-1)` (representable with `n`-bit two's complement integers).
2. The length of `A` is less than `2**n`.
3. The sum of `A` satisfies `-2**(n-1) <= sum(A) < 2**(n-1)`.
4. All combinations of elements in `A` satisfy all of the above conditions.

Naturally, I've decided to outsource this problem to you!

Given an array of integers `A` and a positive integer bit width `n`, verify that `A` satisfies the conditions above.

## Test Cases

```
[0, 0, 0], 2: True
[0, 0, 0, 0], 2: False (violates #2)
[1, 2, 3, 4, 5], 8: True
[1, 2, 3, 4, 5], 2: False (violates all conditions)
[1, 2, 3, 4, 5], 5: True
[-3, 4, 1], 4: True
[10, 0, -10], 4: False (violates #1 and #4)
[27, -59, 20, 6, 10, 53, -21, 16], 8: False (violates #4)
[-34, 56, 41, -4, -14, -54, 30, 38], 16: True
[-38, -1, -11, 127, -35, -47, 28, 89, -8, -12, 77, 55, 75, 75, -80, -22], 7: False (violates #4)
[-123, -85, 6, 121, -5, 12, 52, 31, 64, 0, 6, 101, 128, -72, -123, 12], 12: True

```

## Reference Implementation (Python 3)

```
#!/usr/bin/env python3
from itertools import combinations
from ast import literal_eval

def check_sum(L, n):
  return -2**(n-1) <= sum(L) < 2**(n-1)

def check_len(L, n):
  return len(L) < 2**n

def check_elems(L, n):
  return all(-2**(n-1) <= a < 2**(n-1) for a in L)

A = literal_eval(input())
n = int(input())
OUTPUT_STR = "{}, {}: {}".format(A, n, "{}")

if not (check_elems(A, n) and check_len(A, n) and check_sum(A, n)):
  print(OUTPUT_STR.format(False))
  exit()

for k in range(1, len(A)):
  for b in combinations(A, k):
    if not check_sum(b, n):
      print(OUTPUT_STR.format(False))
      exit()

print(OUTPUT_STR.format(True))

```

Try it online!

# Answer
# Wolfram Language (Mathematica), 40 bytes

```
Max[x=2Tr/@Subsets@#,-x-1,Tr[1^#]]<2^#2&

```

Try it online!

Condition 1 is implied by checking condition 3 for all subsets, including the one-element ones. So we take the max of

* twice the sum of each subset,
* one less than twice the negative of the sum of each subset, and
* the length of the whole set

and check if that's less than `2^#2` (where `#2` is the bit-width input).

At the cost of only 6 more bytes, we can replace `Subsets@#` with `GatherBy[#,Arg]`, which is much more efficient because it computes only the two worst-case subsets: the subset of all nonnegative values, and the subset of all negative values. (This works because `Arg` has a value of `0` on the former and `π` on the latter.)
> 7 votes

# Answer
# Jelly, 19 bytes

```
ŒPS€;⁸L¤ḟ⁹’2*$ŒRṖ¤Ṇ

```

Try it online!

It suffices to check that `mapped sum of powerset + length of set` is in the required range.
> 3 votes

# Answer
# 05AB1E, ~~13~~ ~~12~~ 11 bytes

Saved 1 byte thanks to *Mr. Xcoder*

```
æO·D±¹gMIo‹

```

Try it online!

**Explanation**

```
æ             # powerset of first input
 O            # sum each subset
  ·           # multiply each element by 2
   D          # duplicate
    ±         # bitwise negation of each element in the copy
     ¹g       # push length of first input
       M      # get the maximum value on the stack
        Io    # push 2**<second input>
          ‹   # compare

```
> 3 votes

# Answer
## JavaScript (ES6), ~~75~~ ~~63~~ 58 bytes

```
a=>n=>!a.some(e=>(a.length|2*(e<0?l-=e:u+=e))>>n,u=0,l=-1)

```

The sum of any subset of `a` lies between the sums of the negative and nonnegative elements, so checking the two sums suffices for everything except case 2. Edit: Saved ~~12~~ 17 bytes thanks to @Arnauld.
> 2 votes

# Answer
# Jelly, ~~21~~ 20 bytes

```
»0,«0$S€~2¦Ḥ;LṀ<2*Ɠ¤

```

Try it online!

Linear time complexity solution. Turns out that I over-estimated the time complexity

> in The Nineteenth Byte, 2017-12-11 13-15-03Z, by user202729
>
> > @NewSandboxedPosts "Real" subset sum problem are much harder. This one can be done in linearithmic time...

because now I realize sorting the array is completely unnecessary.

---

Explanation:

```
»0,«0$S€~2¦Ḥ;LṀ<2*Ɠ¤    Main link. Example list: [-1, 0, 1]
»0                      Maximize with 0. Get [0, 0, 1]
  ,                     Pair with
   «0$                    minimize with 0. Get [-1, 0, 0]
      S€                Sum €ach. Get [1, -1]
        ~               Inverse
          ¦               at element
         2                2. (list[2] = ~list[2]) Get [-1, 2]
           Ḥ            Unhalve (double, ×2). Get [-2, 4]
            ;           Concatenate with
             L            Length (3). Get [-2, 4, 3]
              Ṁ         Maximum of the list (4).
               <   ¤    Still less than
                2         two
                 *        raise to the power of
                  Ɠ       eval(input())

```
> 1 votes

# Answer
# JavaScript (ES6), 114 bytes

Takes input in currying syntax `(A)(n)`. Returns a boolean.

```
A=>n=>!(A.reduce((a,x)=>[...a,...a.map(y=>[x,...y])],[[]]).some(a=>(s=eval(a.join`+`),s<0?~s:s)>>n-1)|A.length>>n)

```

### Test cases

```
let f =

A=>n=>!(A.reduce((a,x)=>[...a,...a.map(y=>[x,...y])],[[]]).some(a=>(s=eval(a.join`+`),s<0?~s:s)>>n-1)|A.length>>n)

console.log('[Truthy]')
console.log(f([0, 0, 0])(2))
console.log(f([1, 2, 3, 4, 5])(8))
console.log(f([1, 2, 3, 4, 5])(5))
console.log(f([-3, 4, 1])(4))
console.log(f([-34, 56, 41, -4, -14, -54, 30, 38])(16))
console.log(f([-123, -85, 6, 121, -5, 12, 52, 31, 64, 0, 6, 101, 128, -72, -123, 12])(12))

console.log('[Falsy]')
console.log(f([0, 0, 0, 0])(2)) // violates #2
console.log(f([1, 2, 3, 4, 5])(2)) // violates all conditions
console.log(f([10, 0, -10])(4)) // violates #1 and #4
console.log(f([27, -59, 20, 6, 10, 53, -21, 16])(8)) // violates #4
console.log(f([-38, -1, -11, 127, -35, -47, 28, 89, -8, -12, 77, 55, 75, 75, -80, -22])(7)) // violates #4
```
> 1 votes

# Answer
## Clojure, ~~121~~ 117 bytes

```
#(let[l(int(Math/pow 2(dec %2)))](every?(set(range(- l)l))(cons(count %)(for[i(vals(group-by pos? %))](apply + i)))))

```

Well that was a bit dumb, splitting into positive and negative values is a lot better than sorting. Original, but surprisingly not much longer:

```
#(let[l(int(Math/pow 2(dec %2)))S(sort %)R reductions](every?(set(range(- l)l))(concat[(count S)](R + S)(R +(into()S)))))

```

This works by checking prefix sums of the sequence in ascending and descending order, I think it isn't necessary to generate all combinations of elements in `A`.

`(into () S)` is in effect same as `(reverse S)`, as lists grow from the head. I couldn't figure out a way to use `cons` instead of `concat` when there are two lists to `cons` to. :/
> 1 votes

# Answer
# Jelly, 15 bytes

```
ŒPS€Ḥ;~$;LṀl2<Ɠ

```

Try it online!

### Explanation

```
ŒPS€Ḥ;~$;LṀl2<Ɠ ~ Monadic full program.

ŒP              ~ Powerset.
  S€            ~ The sum of each subset.
    Ḥ           ~ Double (element-wise).
     ;~$        ~ Append the list of their bitwise complements.
        ;L      ~ Append the length of the first input.
          Ṁ     ~ And get the maximum.
           l2   ~ Base-2 logarithm.
             <Ɠ ~ Is smaller than the second input (from stdin)?

```

Saved 1 byte thanks to caird coinheringaahing (reading the second input from STDIN instead of CLA).
> 1 votes

# Answer
# Pyth, 20 bytes

```
>EleS++KyMsMyQmt_dKl

```

**Try it here!**
> 1 votes

# Answer
# Husk, 14 bytes

```
≥Lḋ▲ṁ§eLöa→DΣṖ

```

Going with brute force by looping over all sublists, since splitting into positive and negative parts takes more bytes. Try it online!

## Explanation

```
≥Lḋ▲ṁ§eLöa→DΣṖ  Implicit inputs, say A=[1,2,3,4,5] and n=5
             Ṗ  Powerset of A: [[],[1],[2],[1,2],..,[1,2,3,4,5]]
    ṁ           Map and concatenate:
                  Argument: a sublist, say S=[1,3,4]
            Σ     Sum: 8
           D      Double: 16
          →       Increment: 17
        öa        Absolute value: 17
     §eL          Pair with length of S: [3,17]
                Result is [0,1,1,3,1,5,2,7,..,5,31]
   ▲            Maximum: 31
  ḋ             Convert to binary: [1,1,1,1,1]
 L              Length: 5
≥               Is it at most n: 1

```
> 0 votes

# Answer
# Python 2, ~~72~~ ~~71~~ 70 bytes

```
def f(x,n):t=2*sum(k*(k<0)for k in x);max(2*sum(x)-t,~t,len(x))>>n>0>_

```

Output is via presence/absence of an error.

Try it online!
> 0 votes

---
Tags: code-golf, array, integer, permutations
---


title: Best Yahtzee score

text:
# Question
Title: Best Yahtzee score
Yahtzee is a game played with five six-sided dice and a score sheet with thirteen different boxes to fill a score in. Each box has its own scoring rules:

* 1s, 2s, 3s, 4s, 5s, 6s all score points equal to the sum of the respective dice (that is, a roll of \[3, 2, 3, 1, 5\] scored as 3s would be awarded 6 points: 3 for each 3).
* 3-of-a-kind and 4-of-a-kind (as they sound, three or four dice rolled the same) score points equal to the sum of all five dice.
* Full house (two dice show one value, the other three show another) scores 25 points
* Small straight (four consecutive values) scores 30 points
* Large straight (all consecutive values) scores 40 points
* Yahtzee (all dice show the same value) scores 50 points

The thirteenth (chance) makes sense in-game, but not so much for this challenge; additionally the game has bonuses for extra Yahtzees which make no sense here. Because the challenge is...

Given five dice as input (five integers 1-6, input however is convenient, you can assume input is always valid), output the highest score possible for that 'hand'. For the purposes of this challenge, only the scoring methods in the list above are valid (specifically, chance is *not* a valid score box for this challenge). The score should be output as its decimal numeric value, whether that's an integer or a string representation thereof, whatever. It should be immediately recognizable as a number. Leading/trailing whitespace is fine, this is about getting the score and not presentation.

Code golf, so the answer with the fewest bytes in a given language wins. Standard loopholes forbidden.

## Test cases

(Note that these are all independent, the challenge is to score *one* 'hand' of dice):

```
in: 1 5 4 3 2
out: 40
in: 1 1 4 3 1
out: 10
in: 2 2 6 5 3
out: 6
in: 2 4 2 4 6
out: 8
in: 1 1 1 1 1
out: 50
in: 5 2 5 3 6
out: 10
in: 1 6 3 4 2
out: 30
in: 1 3 1 1 3
out: 25
in: 6 5 5 6 6
out: 28
in: 1 2 3 5 6
out: 6

```

# Answer
# , ~~146~~ 141 bytes

```
function(d)max(unique(d<-sort(d))*(g=table(d)),any(g>2)*sum(d),all(2:3%in%g)*25,(s=sum((R=diff(d))==1))<4&all(R<2)*30,(s>3)*40,(0==sd(d))*50)

```

Try it online!

*Outgolfed by plannapus*

Takes input as a list, and returns the score.

ungolfed a bit:

```
function(d){
 d <- sort(d)
 u <- unique(d)                  # unique dice
 g <- table(d)                   # table of counts
 Ns <- u*g                       # scores as 1s, 2s, ... etc.
 NKind <- any(g>2)*sum(d)        # 3 or 4 of a kind if any counts are at least 3
 FHouse <- all(2:3%in%g)*25      # full house is 25 if 2 & 3 are in counts
 R <- diff(d)                    # consecutive differences
 s <- sum(R==1)                  # sum of differences equal to 1
 sStraight <- s<4 &              # if the number of 1s is 3 and
               all(R<2)*30       # no consecutive numbers are 2 apart
 bStraight <- (s>3)*40           # all 1s means big straight
 Yahtzee <- sd(d)==0             # sd = 0 means all are equal
 max(Ns,NKind,FHouse,sStraight,bStraight,Yahtzee)
}
```
> 6 votes

# Answer
# Python 2, ~~187~~ ~~184~~ ~~167~~ 165 bytes

-17 bytes thanks to @mypetlion
-2 bytes thanks to @chrstphrchvz

```
def f(d):r=range(1,7);c=d.count;m=map(c,r);s=`m`[1::3];return max([i*c(i)for i in r]+[sum(d)*(max(m)>2),25*(set(m)>{2,3}),30*(4*'1'in s),40*(5*'1'in s),50*(5 in m)])

```

Try it online!
> 6 votes

# Answer
# R, ~~136~~ 134 bytes

```
function(n,y=table(factor(n,1:6)),z=sum(!diff(diff(sort(n)))))max(1:6*y,c(25,sum(n),10*3:5)[c(all(y<4&y-1),any(y>2),z>1,z>2,any(y>4))])

```

Golfed down 2 bytes thanks to @Giuseppe!

Indented,

```
function(n, #vector of die scores
         y=table(factor(n,1:6)), #Contingency table
         z=sum(!diff(diff(sort(n))))) #Diff of diff of ordered scores
    max(1:6*y,
        c(25,sum(n),10*3:5)*c(all(y<4&y-1), #Full house
                            any(y>2), #3 and 4 of a kind
                            z>1, #Small straight
                            z>2, #Long straight
                            any(y>4))] #Yahtzee

```

A few test cases:

```
> f=function(n,y=table(factor(n,1:6)),z=sum(!diff(diff(sort(n)))))max(1:6*y,c(25,sum(n),10*3:5)*c(all(y<4&y-1),any(y>2),z>1,z>2,any(y>4)))
> f(c(2,4,2,4,6))
[1] 8
> f(c(1,2,3,5,6))
[1] 6
> f(c(6,5,5,6,6))
[1] 28
> f(c(6,5,3,1,4))
[1] 30
> f(c(6,5,3,2,4))
[1] 40

```
> 4 votes

# Answer
## Batch, 359 bytes

```
@echo off
set/at=s=m=r1=r2=r3=r4=r5=r6=0
for %%r in (%*)do set/a"m+=!(m-r%%r),r%%r+=1,t+=%%r,p=s-r%%r*%%r,p&=p>>9,s-=p
goto %m%
:1
if %r1% neq %r6% set s=40&goto g
:2
set/at=r3*r4*(r2*(r1+r5)+r5*r6)
if %t% gtr 0 set s=30
goto g
:3
set/a"s=r1^r2^r3^r4^r5^r6"
if %s%==1 if %t% lss 25 set s=25&goto g
:4
set/as=t
goto g
:5
set s=50
:g
echo %s%

```

Explanation:

```
@echo off
set/at=s=m=r1=r2=r3=r4=r5=r6=0
for %%r in (%*)do set/a"m+=!(m-r%%r),r%%r+=1,t+=%%r,p=s-r%%r*%%r,p&=p>>9,s-=p
goto %m%

```

Calculate the number of dice for each number, plus the maximum, plus the total of all the dice, plus the highest total of dice of the same number.

```
:1
if %r1% neq %r6% set s=40&goto g

```

If all the dice are different, this might be a long straight, but that needs there to be either no `1` or no `6`.

```
:2
set/at=r3*r4*(r2*(r1+r5)+r5*r6)
if %t% gtr 0 set s=30
goto g

```

Otherwise, or if if at most two dice are the same, then this could still be a short straight. There must be at least a `3` and a `4` and also a combination of the other four numbers.

```
:3
set/a"s=r1^r2^r3^r4^r5^r6"
if %s%==1 set s=25&goto g

```

If there are three dice the same, check for a full house, since `3^2==1`. However, some full houses, such as 6s and 5s, score higher as 3-of-a-kind.

```
:4
set/as=t
goto g

```

Otherwise, or if there are four the same, then score the total.

```
:5
set s=50

```

And if there are five the same, then Yahtzee!

```
:g
echo %s%

```

Output the best score.
> 3 votes

# Answer
# Jelly, 58 bytes

```
ċÐ€`Ṁ>2ȧS
ṢI=1Ạµ-ƤẸ,E;ṢI$E$;⁸Lƙ`Ṣ⁼2,3¤a3,5,4,2.Ṁ×⁵»Ç»Sƙ`Ṁ$

```

Try it online!
> 3 votes

# Answer
# Perl 6, 159 bytes

```
->\b{max map {$_(b)},|(1..6).map({*{$_}*$_}),{.kxxv.sum*?.values.grep(*>2)},{25*(6==[*]
.values)},30*?*{3&4&(1&2|2&5|5&6)},40*?*{2&3&4&5&(1|6)},50*(*.keys==1)}

```

Try it online!

Since input may be accepted "however is convenient," my function takes it as an instance of the `Bag` class, which is a container with multiplicity. A `Bag` is also an associative container; `$bag{$key}` returns how many times `$key` occurs in the bag.

The bulk of the function is just a list of functions that evaluate each possible Yahtzee hand, returning the score for that hand or zero if the conditions for the hand are not met.

* `|(1..6).map({ *{$_} * $_ })` is a list of six functions that evaluate hands based on repeated runs of the numbers 1-6. The leading `|` flattens this list into the surrounding list.
* `{.kxxv.sum * ?.values.grep(* > 2) }` evaluates the 3- and 4-of-a-kind hands. `.kxxv` on a `Bag` returns the keys repeated with each's multiplicity, recovering the original list of die rolls, and `.sum` of course sums the dice. That sum is multiplied by a boolean value (`?`) which is true if the bag's `.values` (ie, the multiplicities) contain a value larger than 2.
* `{ 25 * (6 == [*] .values) }` evaluates the full house hand. 25 is multiplied by a boolean value which is true if the product of the multiplicities is 6, which for five dice can only happen if one is 3 and the other is 2.
* `30 * ?*{ 3 & 4 & (1 & 2 | 2 & 5 | 5 & 6) }` evaluates the small straight hand. It's a `WhateverCode` function; the second star `*` is the `Bag`. The expression between the braces is the junction of values 3 and 4, and either 1 and 2, or 2 and 5, or 5 and 6. Looking up this junction in the `Bag` results in a junction of the corresponding multiplicities. If the mulitplicities of 3 and 4, and at least one of 1 and 2, or 2 and 5, or 5 and 6, are nonzero, the junction is true when coerced to a boolean (with `?`), and this boolean is multiplied by 30 to get the score.
* `40 * ?*{ 2 & 3 & 4 & 5 & (1 | 6) }` similarly evaluates the large straight hand. It's simpler because the dice must include each of the numbers 2-5, and either 1 or 6.
* `50 * (*.keys == 1)` evaluates the Yahtzee hand. It's simply 50 times a boolean value which is true if the number of distinct dice is one.
> 2 votes

# Answer
# Pip, ~~65~~ 63 bytes

```
n:_NgM\,6MXn*\,6AL[2<MXn23=JSNn3<Y#MX Jn^0MXn=5]*[$+g25--y*t50]

```

Takes the dice as five command-line arguments. Try it online!

### Ungolfed + explanation

(This is the original version.)

```
                    g is list of cmdline args; t is 10 (implicit)

Y                   Yank into y:
  _Ng                function that counts occurrences of its argument in g
 M                   mapped to
  \,6                inclusive range from 1 to 6
                    This gives us how many dice are showing each number 1-6

s:                  Assign to s:
  # MX               length of max of
      Jy ^ 0         join y into string and split on zeros
                    This gives us the length of the longest straight

MX                  Max of
   y * \,6           each die frequency in y, times its value
 AL                  to which list append
   [                 this list:
                      3- and 4-of-a-kind:
    MXy > 2 & $+g      If max frequency is 3 or more, sum of g (else 0)
                      Full house:
    23 = J SNy & 25    Sort y and join into string; if it's 000023, 25 (else 0)
                      Straights:
    s > 3 & --s*t      If s is 4 or more, (s-1)*10 (else 0)
                      Yahtzee:
    MXy = 5 & 50       If max frequency is 5, 50 (else 0)
   ]
                    The result of the last expression is autoprinted

```
> 2 votes

# Answer
# Ruby, 184 bytes

Full program. To make it easier to test input, add `$/=' '` on top to read in the "digit separated by spaces" format. (191 chars)

```
a=$<.map &:to_i
b=a.|c=[]
d=(1..6).map{|x|e=a.count x
c<<x*e
e}
e=a.sum
p !b[1]?50:b[4]&&!(a&[1,6])[1]?40:(1..3).any?{|x|(a&[*x..x+3])[3]}?30:(d-[0,2,3])[0]?d.max>2?e:c.max: [25,e].max

```

I set out the break the 200 bytes barrier and I managed to destroy it with a dozen bytes left, with ease!

Try it online!

## Explanation

Not a very good one though. Hope you have some Ruby knowledge~

```
a=$<.map &:to_i # a: input as [number]*5
b=a.|c=[]       # c: [], b: a.uniq
d=(1..6).map{|x|
    e=a.count x # e: occurrence count in a
    c<<x*e      # add (number * occurrence count) to c
    e           # return value in d
}
e=a.sum         # e: sum of input
p !b[1] ? 50 :  #   condition to print 50 <= if a.uniq has length 0 (el 1 is nil)
  b[4] &&       #   condition to print 40 <= if a.uniq has length 5 (el 4 exists)
  !(a&[1,6])[1] ? 40 : # <- arr & [mask]  # and a does not have both 1 and 6
  (1..3).any?{|x| # condition to print 30 <= if any of 1..4, 2..5, 3..6
  (a&[*x..x+3])[3]} ? 30 : # [3] to assert entire mask is found in a
  (d-[0,2,3])[0] ? # if, after removing 0 (not found) 2 (a pair) 3 (a triple)
                   # and something is found, this is not full house
  d.max > 2 ?   # is triple / quadruple ?
     e :        # weakly dominating alternatives
     c.max      # choose best by-suit
  : [25,e].max  # choose best by-score

```
> 1 votes

---
Tags: code-golf, number
---


title: Generalized FiveThirtyEight Sequences

text:
# Question
Title: Generalized FiveThirtyEight Sequences
Adapted from this FiveThirtyEight riddle.

## Background

Examine the following infinite sequence:

```
3 3 3 2 3 3 3 2 3 3 3 2 3 3 2 3 3 3 2 ...

```

Let's say the sequence is 1-indexed. The `i`th number in the sequence determines how many `3`s there are before the `i`th `2` and following any previous `2`s. So since the sequence starts with a `3` the sequence must begin `3 3 3 2` and since there are three `3`s at the beginning of the sequence the subsequence `3 3 3 2` must repeat itself three times. After that you reach `3 3 2` because the fourth number in the sequence is `2`.

The FiveThirtyEight riddle asks for the limit of the ratios of threes to twos (which I won't spoil here) but you can also ask what the cumulative ratio is after index `i`. For example the ratio at `i=4` is `3/1 = 3` and at `i=15` it's `11/4 = 2.75`.

**Let's get general**

Given numbers `n` and `k` we can make a similar sequence that starts with `n` and just like the original sequence described the number at index `i` determines how many `n`s show up before the `i`th `k` and following any previous `k`s.

Examples:

`n=2, k=5` gives the sequence `2 2 5 2 2 5 2 2 2 2 2 5 2 2 5 ...`

`n=3, k=0` gives `3 3 3 0 3 3 3 0 3 3 3 0 0 3 3 3 0 ...`

`n=1, k=3` gives `1 3 1 1 1 3 1 3 1 3 1 3 1 1 1 3 1 ...`

## The Challenge

Write a function/program and with it do the following. Take as input:

* a positive integer `n`
* a nonnegative integer `k ≠ n`
* a positive integer `i > n`

The first two inputs `n` and `k` determine a sequence as described above and `i` is an index. I am using 1-indexing in the examples but you have the freedom to use 0- or 1-indexing. If 0-indexed then the restriction on `i` is `i ≥ n`.

With the three numbers output the ratio of `n`s to `k`s in the sequence up to and including the number at the index `i`. The format of the output can either be a decimal value with at least 5 digits of precision or an exact value as a ratio like `3524/837` or `3524:837`.

In decimal form, the last digit can be rounded however you like. Trailing zeros and whitespace are allowed.

In either of the string forms the two numbers need to be normalized so that they are coprime. For example if the ratio was 22/4, `11/2` and `11:2` are acceptable but `22/4` is not.

**Examples**

```
n   k   i      output
2   4   15     2.75     or   11/4
6   0   666    5.1101   or   557:109
50  89  64     63       or   63:1
3   2   1000   2.7453   or   733/267
9   12  345    9.4545   or   104/11

```

This is code golf per language, so shortest code in each language is the winner.

# Answer
# Husk, 16 bytes

```
¤/#ωȯ↑⁰J¹`C∞²N¹²

```

Try it online!

Takes inputs in the same order as the test cases. Outputs a rational number. I feel like this has too many superscripts, but I don't know how to get rid of them...

## Explanation

```
¤/#ωȯ↑⁰J¹`C∞²N¹²  Inputs are n, k, i.
             N    Starting with the natural numbers [1,2,3..
   ωȯ             do this until a fixed point is reached:
                    Argument is a list s.
           ∞²       Take the infinite list [n,n,n..
         `C         and split it to the lengths in s.
       J¹           Join the resulting blocks with k.
     ↑⁰             Take the first i elements.
                  Call the result x.
¤             ¹²  For each of n and k,
  #               count their number of occurrences in x
 /                and perform exact division on the results.

```
> 5 votes

# Answer
# Jelly,  ~~25~~  16 bytes

-9 bytes ~50% attributable to Erik the Outgolfer's Jelly answer (1. using the new-ish key quick `ƙ` even with a bug in the interpreter currently costing a byte; 2. using a mapped repetition to avoid counting and indexing into the current sequence.) Go give him some credit!

```
³ẋÐ€j⁴ṁ⁵µÐLLƙ`÷/

```

A full program taking three arguments: `n`, `k`, `i` which prints the result.

**Try it online!**

### How?

```
³ẋÐ€j⁴ṁ⁵µÐLLƙ`÷/ - Main link
        µ        - monadic chain separation
         ÐL      - apply the monadic chain to the left repeatedly until no change occurs:
³                -   program's 1st argument, n
  Ð€             -   map across the current sequence (initially just n)
 ẋ               -     repeat (the first run give triangle of n i.e. [[n],[n,n],...,[n]*n]
     ⁴           -     program's 2nd argument, k
    j            -     join
       ⁵         -     program's 3rd argument, i
      ṁ          -     mould like (repeat the list to fill, or cut it, to length i)
            ƙ    - keyed application, map over groups of identical items:
             `   - (this has an arity of 2, make it monadic by repeating the argument)
           L     -   length -> [numberOfNs, numberOfKs]
               / - reduce with:
              ÷  -   division -> [numberOfNs / numberOfKs]
                 - implicit print (a single item list just prints its content)

```

example run with inputs `n=2`, `k=3`, `i=30`:

```
Start the "loop until no change", ÐL
Note: Initial left argument, n=2, implicitly range-ified by Ð€ to become [1,2]
1. mapped repeat of n: [[2],[2,2]]
          join with k: [2,3,2,2]
         mould like i: [2,3,2,2,2,3,2,2,2,3,2,2,2,3,2,2,2,3,2,2,2,3,2,2,2,3,2,2,2,3]

2. mapped repeat of n: [[2,2],[2,2,2],[2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2],[2,2,2]]
          join with k: [2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2]
         mould like i: [2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2]
                          ^different to previous result

3. mapped repeat of n: [[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2]]
          join with k: [2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2]
         mould like i: [2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2]
                                  ^different to previous result

4. mapped repeat of n: [[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2]]
          join with k: [2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2]
         mould like i: [2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2]
                                                      ^different to previous result

5. mapped repeat of n: [[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2],[2,2],[2,2,2],[2,2]]
          join with k: [2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2]
         mould like i: [2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,2,3,2,2,3,2,2,3,2,2,3,2]
                       all the same as the previous result; stop loop and yield this.

length applied to equal elements: [length([2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]), length([3,3,3,3,3,3,3,3,3])]
                                = [21,9]
reduce by division              = [21/9] = [2.3333333333333335]
implicit print                  2.3333333333333335

```
> 4 votes

# Answer
# Python 3, ~~94~~ ~~92~~ ~~89~~ 87 bytes

```
def g(n,k,i):o,t=[n],0;exec('o+=[n]*o[t]+[k];t+=1;'*i);return-1-i/(o[1:i+1].count(n)-i)

```

Try it online!

# Credits

* Reduced from 94 to 92 bytes: Colera Su.
* Reduced from 92 to 89 bytes: dylnan.
* Reduced from 89 to 87 bytes: ovs.
> 4 votes

# Answer
# Jelly, 22 bytes

```
³ẋÐ€;€⁴Ẏḣ⁵
ẋ`;ÇÐLLƙ`÷/

```

Try it online!

Full program. Takes arguments `n`, `k`, `i`.

There's a bug that makes this need to be unnecessarily longer by 1 byte.
> 4 votes

# Answer
# Mathematica, 85 bytes

```
(s={#};Do[s=Join[s,#~Table~s[[t]],{#2}],{t,#3}];Last@@Ratios@Tally@s[[#+3;;#3+#+2]])&

```

Try it online!
> 3 votes

# Answer
# APL (Dyalog Unicode), ~~126~~ 70 bytes

```
k n i←⎕
j←⍴v←⍬
:While j<i
v,←k,⍨n⍴⍨{v≢⍬:j⊃v⋄n}j+←1
:End
÷/+/¨n k⍷¨⊂j⍴v

```

Try it online!

Well, thanks to @Adám for obliterating 56 bytes out of this answer.

This is a niladic Tradfn (**trad**itional **f**unctio**n**) taking 1 input, which is a 3 element list.

`⎕PP←5` is not added to the byte count because it's only used to limit the **P**rint **P**recision to **5** digits.

`∇f` and  are not added to the byte count because they're not part of the code, only delimiters for the tradfn.

### How it Works:

```
k n i←⎕                   ⍝ Take input (←⎕) for k, n and i.
j←⍴v←⍬                    ⍝ Assign (←) an empty vector (⍬) to v, then assign its shape (⍴, which is 0) to j.
:While j<i                ⍝ while j<i, do:
v,←k,⍨n⍴⍨{v≢⍬:j⊃v⋄n}j+←1 ⍝ this:
                     j+←1 ⍝ increment j (+←1)
          {v≢⍬:     }     ⍝ if (:) v does not match (≢) ⍬
               j⊃v        ⍝ return the jth element of v (v[j])
                  ⋄n      ⍝ else (⋄) return n
      n⍴⍨                 ⍝ shape (⍴) n as the result (repeats n result times)
   k,⍨                    ⍝ append (,⍨) k
v,←                       ⍝ append to (,←) v
:End                      ⍝ End while loop
÷/+/¨n k⍷¨⊂j⍴v            ⍝ then:
           j⍴v            ⍝ shape (⍴) v as j (truncates v to j elements)
          ⊂               ⍝ enclose the resulting vector
         ¨                ⍝ for each element
        ⍷                 ⍝ find (returns a boolean vector)
     n k                  ⍝ n and k (⍷ will return a boolean vector for each)
  +/¨                     ⍝ cumulative sum of each vector (returns the number of times n and k appear in v)
÷/                        ⍝ divide them and implicitly return the result.

```
> 2 votes

# Answer
# , 88 bytes

```
function(n,k,i){s=rep(n,n);for(j in 1:i){s=c(s,k,rep(n,s[j]))};z=sum(s[1:i]==n);z/(i-z)}

```

Try it online!
> 1 votes

# Answer
# Swift, 152 bytes

```
func f(n:Int,k:Int,i:Int){var a=[0];(1...i).map{a+=(0..<(a.count>$0 ?a[$0]:n)).map{_ in n}+[k]};let m=a[1...i].filter{n==$0}.count;print("\(m)/\(i-m)")}

```

Will it be shorter than Java?

## Explanation

```
func f(n:Int,k:Int,i:Int){
  var a=[0]                                    // Initialize the array (the zero is to
                                               //  define the type of the array and will be
                                               //  ignored by the code)
  (1...i).map{                                 // Repeat i times (more than enough):
    a+=(0..<(a.count>$0 ?a[$0]:n)).map{_ in n} //  Add the right amount of n:s to the array
      +[k]                                     //  Add k to the array
  }                                            // End repeat
  let m=a[1...i].filter{n==$0}.count           // Count the amount of n:s in the first
                                               //  i elements of the array
  print("\(m)/\(i-m)")                         // Print the result
}

```
> 0 votes

# Answer
# Ruby, ~~77~~ ~~71~~ 70 bytes

```
->n,k,i{r=[n]
i.times{|c|r+=[n]*r[c]+[k]}
1r*(j=r[1,i].count n)/(i-j)}

```

Try it online!

Returns a Rational, which both operates as a number and stringifies to the exact reduced fraction.
> 0 votes

# Answer
# Pyth, 24 bytes

```
AEtcH/e.u<sm+*d]QGNH]Q)G

```

Test suite.

Fixed point of `[n]` under certain function of array.
> 0 votes

# Answer
# Zephyr, 284 bytes

```
input n as Integer
input k as Integer
input m as Integer
set s to Array(m)
for i from 1 to n
set s[i]to n
next
set s[i]to k
set N to n
set K to 1
for a from 2 to m
for b from 1 to s[a]
inc i
if i<=m
set s[i]to n
inc N
end if
next
inc i
if i<=m
set s[i]to k
inc K
end if
next
print N/K

```

Takes the three numbers from stdin on three separate lines. Outputs an exact ratio such as `104/11` or `63`.

### Ungolfed

```
input n as Integer
input k as Integer
input maxIndex as Integer

set sequence to Array(maxIndex)
for i from 1 to n
    set sequence[i] to n
next
set sequence[i] to k

set nCount to n
set kCount to 1

for a from 2 to maxIndex
    for b from 1 to sequence[a]
        inc i
        if i <= maxIndex
            set sequence[i] to n
            inc nCount
        end if
    next
    inc i
    if i <= maxIndex
        set sequence[i] to k
        inc kCount
    end if
next

print nCount / kCount

```
> 0 votes

---
Tags: code-golf, number, sequence
---


title: Clearly parenthesize APL trains

text:
# Question
Title: Clearly parenthesize APL trains
In APL, you can write tacit functions, called *trains*. How they work is irrelevant for this challenge. Here are the different ways they can be grouped, using  as the function:

```
⍴      -> ⍴
⍴⍴     -> ⍴⍴
⍴⍴⍴    -> ⍴⍴⍴
⍴⍴⍴⍴   -> ⍴(⍴⍴⍴)
⍴⍴⍴⍴⍴  -> ⍴⍴(⍴⍴⍴)
⍴⍴⍴⍴⍴⍴ -> ⍴(⍴⍴(⍴⍴⍴))
...

```

The order remains the same. The procedure is that as long as there are strictly more than 3 functions, the last 3 functions are grouped into one function. If we meet a nested train, we parenthesize that first, before continuing. Here is the procedure applied to `⍴⍴⍴⍴⍴⍴`:

```
Step 0: ⍴⍴⍴⍴⍴⍴
There are strictly more than 3 functions, repeat.
Step 1: ⍴⍴⍴(⍴⍴⍴)
There are strictly more than 3 functions, repeat.
Step 2: ⍴(⍴⍴(⍴⍴⍴))
There are 3 or less functions, we're done.

```

Here is the same procedure applied to `⍴⍴⍴(⍴⍴)⍴(⍴⍴⍴⍴(⍴⍴⍴))⍴⍴`:

```
Step 0: ⍴⍴⍴(⍴⍴)⍴(⍴⍴⍴⍴(⍴⍴⍴))⍴⍴
There are strictly more than 3 functions, repeat.
We have met a nested train, applying procedure to that first:
  Step 0: ⍴⍴⍴⍴(⍴⍴⍴)
  There are strictly more than 3 functions, repeat.
  We have met a nested train, applying procedure to that first:
    Step 0: ⍴⍴⍴
    There are 3 or less functions, we're done.
  Step 1: ⍴⍴(⍴⍴(⍴⍴⍴))
  There are 3 or less functions, we're done.
Step 1: ⍴⍴⍴(⍴⍴)⍴((⍴⍴(⍴⍴(⍴⍴⍴)))⍴⍴)
There are strictly more than 3 functions, repeat.
We have met a nested train, applying procedure to that first:
  Step 0: ⍴⍴
  There are 3 or less functions, we're done.
Step 2: ⍴⍴⍴((⍴⍴)⍴((⍴⍴(⍴⍴(⍴⍴⍴)))⍴⍴))
There are strictly more than 3 functions, repeat.
Step 3: ⍴(⍴⍴((⍴⍴)⍴((⍴⍴(⍴⍴(⍴⍴⍴)))⍴⍴)))
There are 3 functions or less, we're done.

```

# Input

For this challenge, input will be simplified. This means that you can choose 2 different chars for opening and closing parentheses and 1 char for functions, different from the ones chosen for parentheses. The chars you choose must be consistent. The input will not be empty, and will not contain parentheses with no content (i.e. `()`).

# Output

Again, you may choose 3 different chars, 2 for parentheses and 1 for functions. Note that they need not be the same as the ones chosen for input, but they must be consistent.

# Rules

* If there are parentheses which only enclose one function within them in the input, you must remove them in the output. Your output may not contain unneeded parentheses (i.e. enclosing only one function, or enclosing the whole output).
* You don't need to implement the algorithm used here, as long as your solution is valid for this challenge.
* Input and output are strings in the format explained in the Input and Output sections. The input will have at least one character.
* Using the standard loopholes is strictly forbidden.
* This is , so shortest answer wins. However, there won't be an accepted answer, since this is a per-language competition, and to encourage answering in languages in which this task would result in longer code compared to code written in other languages.

# Test cases

The chars used here are `()⍴`, you should replace them with your chosen chars.

```
⍴                          -> ⍴
⍴                          -> ⍴
⍴⍴                         -> ⍴⍴
⍴⍴⍴                        -> ⍴⍴⍴
⍴⍴⍴⍴                       -> ⍴(⍴⍴⍴)
⍴⍴⍴⍴⍴⍴⍴⍴⍴⍴⍴⍴⍴⍴⍴            -> ⍴⍴(⍴⍴(⍴⍴(⍴⍴(⍴⍴(⍴⍴(⍴⍴⍴))))))
⍴⍴⍴⍴⍴(⍴⍴⍴)⍴⍴(⍴(⍴⍴⍴)⍴⍴⍴)⍴⍴⍴ -> ⍴(⍴⍴(⍴⍴((⍴⍴⍴)⍴(⍴(⍴(⍴⍴⍴)(⍴⍴⍴))(⍴⍴⍴)))))
(⍴⍴⍴)(⍴⍴⍴)(⍴⍴⍴)            -> (⍴⍴⍴)(⍴⍴⍴)(⍴⍴⍴)
(⍴⍴⍴)(⍴⍴⍴)⍴⍴⍴              -> (⍴⍴⍴)(⍴⍴⍴)(⍴⍴⍴)
⍴⍴(⍴)⍴⍴                    -> ⍴⍴(⍴⍴⍴)
((⍴⍴))                     -> ⍴⍴
⍴⍴((⍴⍴))⍴⍴                 -> ⍴⍴((⍴⍴)⍴⍴)

```

This challenge has been posted in the Sandbox. If you have the required privilege, you can view the sandbox post here.

# Answer
# APL (Dyalog Classic), ~~71~~ ~~68~~ ~~65~~ 63 bytes

```
0{⍵≡⍕⍵:⍵⋄⍬≡⍵:'⍬'⋄1=≢⍵:⍺∇⊃⍵⋄3≥≢⍵:⍺⌽')(',⍣⍺∊1∇¨⍵⋄⍺∇¯3(↓,∘⊂1∇↑)⍵}⍎

```

Try it online!

The characters I chose for I/O are `'('`, `')'`, and `'⍬'`.

This solution is itself an APL train.

parses the input as if it's a nested array - a tree with empty numeric vectors () as leaves.

The dfn (i.e. lambda - `{ }`) traverses the tree recursively and converts it to a properly parenthesised string. The left argument  controls whether parentheses should be added to the current level if necessary.

The dfn handles the following cases based on the right argument:

* if it's already a string (`⍵≡⍕⍵`), return it
* if it's , return the char `'⍬'`
* if it's a singleton, just dig deeper ( is the symbol for a recursive call)
* if its length is ≤3, recurse for each of the items and surround with `()` if necessary
* otherwise, recurse for the 3-tail, prepend all but the 3-tail, and recurse again
> 8 votes

# Answer
# CJam, 56 bytes

Beats APL!

```
lW%~]]]{{_,{K_,({~}|}&}%{_,3>}{3/(aa\+:~}w}:K~~`1>W<W%S/

```

Try it online!

This works (I think) and I have no idea why...

Input characters are `][T` for `()⍴`, and output characters are `][0` for `()⍴` (yes, this means they are reversed from what you would expect; for example, you might pass in `TTT]TT[T]TTTT]TTT[[TT`).

## High-Level Overview

The program works with the input backwards, because it's more convenient. To parse the input, we leverage CJam's parser — reversing and executing the input provides the (backwards) parsed form of the input.

We then define a procedure `K`. `K` does most of the work for our submission, and it works as follows:

* The input array will be a mix of zeroes and nonempty sub-arrays. Identify the sub-arrays and recursively apply `K` to them. The result should be another array, and if this array consists of just a single element, unpack it (this gets rid of redundant parentheses).
* As long as the result has more than three elements, group its first three (not its last three; recall that the input is being processed backwards) into a single list.
* Return the result.

By applying `K` to the input, we get the properly parenthesized form of the input (the only thing to note is that we actually wrap the input in a singleton list and unwrap it afterwards; the reason for this is that we want the snippet that unpacks singletons to apply to the top-level program, and not just its sub-arrays). Afterwards, we just apply some minimal formatting to get our result.

# Some explanation for golfed bits

The golf I'm most proud of is using `,` to perform the check between integers and arrays.

* If the top-of-stack is an integer *n*, `,` generates the range *\[0..n)*. Since the only integer we will encounter is `0`, this always gives us the empty list `[]`, which is falsey.
* If the top-of-stack is an array, `,` takes its length. Since all arrays we encounter will be non-empty, this always gives us a positive integer, which is truthy.

Another golf that might be of interest is the method I use to group the first three elements of the array; it's somewhat similar to my "Turing complete language interpreter code golf" submission. CJam doesn't have a short way to break an array into two pieces (you can try to slice off the first part and then the other part while keeping the original array and index on the stack, but that doesn't work very well), so what I do instead is use `3/`, which groups an array into blocks of 3. I can then pop off the first element `(`, wrap in array twice `aa`, and then append back on to the start of the list `\+`. The reason we wrap in array twice is that we have to take off a layer with `:~`, since we just grouped the rest of the array into sections as well.
> 2 votes

# Answer
## JavaScript (ES6), ~~149~~ 146 bytes

```
i='a';f=s=>s==(s=s[R='replace'](/\((\w+)\)/,(q,t)=>(f[q=i+=0]=f(t),q)))&&s==(s=s[R](/(?!^)((a0+|p){3})$/,"($1)"))?s[R](/a0+/g,t=>`(${f[t]})`):f(s)
```

```
<textarea cols=80 id=I>ppp(pp)p(pppp(ppp))pp</textarea><br>
<button onclick=O.innerText=f(I.value)>Run</button><br>
<pre id=O></pre>
```

Uses `()p`, although you to use a different letter you can just change the `p` toward the end.
> 0 votes

---
Tags: code-golf, parsing, balanced-string, apl
---


# Question
Title: Tell me when the next post is... WebSockets!
# Background

I was working on a StackOverflow helper program (that sends me notifications) when I noticed something rather interesting in StackOverflow's Network tab:

StackOverflow uses WebSockets (not too surprising, but good to know)! For this challenge, we will be conquering StackOverflow's web socket server.

This particular method could be transferred over to other domains related to StackExchange, but StackOverflow is very popular and a good example. Feel free to lookup tags for other domains on StackExchange (feel free to connect to those instead, although I doubt it would reduce byte count since StackOverflow has id 1).

# StackOverflow's Unofficial WebSocket API

There are two separate WebSocket servers you could use:

* The secure, `wss://qa.sockets.stackexchange.com/`
* Or the insecure, `ws://qa.sockets.stackexchange.com/`

Since we are code golfing and we aren't going to be sending any not-already-public-information, I suspect people will lean more toward the insecure option.

Next, in order to subscribe to our favorite tag, we need to send the following to the WebSocket to 'subscribe' to the tag's feed.

```
1-questions-newest-tag-javascript

```

You can replace `javascript` with any tag we're interested in.

The server will occasional send heartbeat requests. You must reply with `hb` (so you can keep the connection alive).

A heartbeat requests looks as follows:

```
 {"action":"hb","data":"hb"}`

```

Here's a basic JavaScript-based socket (it may take a several minutes for there to be a new post, depending on time of day). I used the most popular tag JavaScript to test with, but if you know of a more popular tag, go ahead and leave a comment.

Example:

```
var exampleSocket = new WebSocket("wss://qa.sockets.stackexchange.com/");
exampleSocket.onopen = function (event) {
  exampleSocket.send("1-questions-newest-tag-javascript");
};
exampleSocket.onmessage = function (event) {
  if (JSON.parse(event.data).data === "hb") {
    exampleSocket.send("hb")
  }
  console.log(event.data)
};
```

# Specifications

Input: Any tag the user wants to receive updates about.

Output: Should be the first question (from when you connected to the WebSocket) and all consecutive available for said tag on StackOverflow.

Rules:

* You **must** use WebSockets. Or, at least connect to `sockets.stackexchange.com` (including, `ws://qa.sockets.stackexchange.com`) and use it to receive updates for the inputted tag. If you can find a better way of doing it (like not using the `1-questions-newest-tag-<tag>` but still receive updates fo the inputted tag) by all means. Or if you can write your own WebSocket equivalent in less bytes, even cooler.
* Least number of bytes wins!

# Language Compatibility

External libraries are encouraged. Many programming languages have a compatible library.

# Answer
# Clojure with gniazdo, ~~126~~, ~~*204*~~, 203 bytes

+78 bytes to handle reacting to heartbeat messages

-1 byte by changing from indexing the string converted to a vector, to just using `nth`. I was expecting more of a gain from that **:/**

```
(use '[gniazdo.core])(fn[t](let[a(atom 0)s #(send-msg @a %)o(connect"ws://qa.sockets.stackexchange.com":on-receive #(if(=((vec %)11)\h)(s"hb")(println %)))](reset! a o)(s(str"1-questions-newest-tag-"t))))

```

An anonymous function that takes a string tag, and prints the raw JSON results as they're received, while responding to heartbeats.

To test if the received message is a heartbeat, I'm testing if the 12th character of the response is the character `h`. After looking over this page, it seems impossible for `h` to be the 12th character without the response being a heartbeat. If this isn't the case, I can try to figure out a workaround.

```
(ns bits.golf.web-sock
  (:require [gniazdo.core :as g]))

(defn new-tag-posts [^String tag]
  (let [; A mutable state to hold the sock.
        ; Necessary since the sock's callback requires a reference to the
        ;  sock itself
        sock-a (atom nil)

        ; Shortcut function to save bytes
        send #(g/send-msg @sock-a %)

        handler #(if (= (nth % 11) \h) ; If the 12th character (at index 11) is 'h'
                   (send "hb") ; respond to the heartbeat
                   (println %)) ; else print the JSON

        sock (g/connect "ws://qa.sockets.stackexchange.com"
                        :on-receive handler)]

    ; Set the mutable state to the created socket
    (reset! sock-a sock)

    ; Subscribe to the given tag
    (send (str "1-questions-newest-tag-" tag))))

```
> 2 votes

# Answer
# Groovy, 388 without the @Grab

```
@Grab('org.java-websocket:Java-WebSocket:1.3.6')
import org.java_websocket.client.*;import org.java_websocket.handshake.*
new WebSocketClient(new URI("ws://qa.sockets.stackexchange.com/")){void onOpen(ServerHandshake h){send("1-questions-newest-tag-"+args[0]);}
void onClose(int c,String r,boolean b){}
void onMessage(String m){println(m);if(m.indexOf('"action":"hb"')>0){send('hb');}}
void onError(Exception e){}}.connect();
while(1){}

```

With the @Grab directive, run with `groovy snippet.groovy javascript`

Without the @grab directive, you have to download the library, and run `groovy -cp Java-WebSocket-1.3.6.jar snippet.groovy javascript`
> 1 votes

# Answer
# Bash, ~~353~~ ~~346~~ 333 + 11 = 344 bytes<br>

**Builtins only, no coreutils.** +11 bytes for `-O extglob` option.

The script contains unprintable characters, which are represented by e.g. `<81>` (a hex pair) or `<CR>` below. Also note there is a trailing space on lines 2 and 5. A full xxd dump follows..

Invoke like this:

```
$ bash -O extglob script.sh javascript

```

Output is on STDERR.

**Note:** This requires that your copy of bash was built with the `--enable-net-redirections` compile option. The default bash on OS X was not, but the version on Homebrew was (`brew install bash && $(brew --prefix)/bin/bash ...`).

```
exec</dev/tcp/qa.sockets.stackexchange.com/80>&0
p=printf\
$p"GET / HTTP/1.1
Host: x
Upgrade:
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

"
r=read;$r;$r;$r;$r;$r
$p"<81>\\`$p%o $((${#1}+151))`\0\0\0\0001-questions-newest-tag-$1"
g()($p<81><82><01><01><01><01>ic
sleep 5
g);g&
h()($r -d} D
$p"${D##?@(~?|<7F>???????|)?}}">&2
h);h

```

## xxd dump

```
<!--
00000000: 6578 6563 3c2f 6465 762f 7463 702f 7161  exec</dev/tcp/qa
00000010: 2e73 6f63 6b65 7473 2e73 7461 636b 6578  .sockets.stackex
00000020: 6368 616e 6765 2e63 6f6d 2f38 303e 2630  change.com/80>&0
00000030: 0a70 3d70 7269 6e74 665c 200a 2470 2247  .p=printf\ .$p"G
00000040: 4554 202f 2048 5454 502f 312e 310a 486f  ET / HTTP/1.1.Ho
00000050: 7374 3a20 780a 5570 6772 6164 653a 200a  st: x.Upgrade: .
00000060: 5365 632d 5765 6253 6f63 6b65 742d 4b65  Sec-WebSocket-Ke
00000070: 793a 2064 4768 6c49 484e 6862 5842 735a  y: dGhlIHNhbXBsZ
00000080: 5342 7562 3235 6a5a 513d 3d0a 5365 632d  SBub25jZQ==.Sec-
00000090: 5765 6253 6f63 6b65 742d 5665 7273 696f  WebSocket-Versio
000000a0: 6e3a 2031 330a 0a22 0a72 3d72 6561 643b  n: 13..".r=read;
000000b0: 2472 3b24 723b 2472 3b24 723b 2472 0a24  $r;$r;$r;$r;$r.$
000000c0: 7022 815c 5c60 2470 256f 2024 2828 247b  p".\\`$p%o $((${
000000d0: 2331 7d2b 3135 3129 2960 5c30 5c30 5c30  #1}+151))`\0\0\0
000000e0: 5c30 3030 312d 7175 6573 7469 6f6e 732d  \0001-questions-
000000f0: 6e65 7765 7374 2d74 6167 2d24 3122 0a67  newest-tag-$1".g
00000100: 2829 2824 7081 8201 0101 0169 630a 736c  ()($p......ic.sl
00000110: 6565 7020 350a 6729 3b67 260a 6828 2928  eep 5.g);g&.h()(
00000120: 2472 202d 647d 2044 0a24 7022 247b 4423  $r -d} D.$p"${D#
00000130: 233f 4028 7e3f 7c7f 3f3f 3f3f 3f3f 3f7c  #?@(~?|.???????|
00000140: 293f 7d7d 223e 2632 0a68 293b 68         )?}}">&2.h);h
-->
```
> 1 votes

---
Tags: code-golf
---


title: Intersection of two triangles

text:
# Question
Title: Intersection of two triangles
Given 4 points on the 2D planes `A, B, C, D`, calculate the area of the intersection region of the triangles `OAB` and `OCD`, where `O` is the center of the plane, having coordinate `(0, 0)`.

Algorithms that runs in constant time complexity (in terms of arithmetic operations) are encouraged, but not forced.

# Rules

* Each point is represented as two real numbers, denotes their X and Y coordinate.
    + Optionally, if your programming language (or some library of your programming language) has built-in `Point` type or equivalent, it is allowed to take `Point` object as input.
* The input is given as 4 points, in the formats, including but not limited to:
    + A list of 8 coordinates.
    + A list of 4 points, each point can be represented in any convenient format.
    + Two lists of 2 points.
    + etc.
* You cannot assume particular ordering of the points (counter-clockwise order or clockwise order)
* You cannot assume that the point `O` is passed as input. In other word, program must not take and use extraneous input.
* You cannot assume all the points are different. In other words, the triangles may be degenerate. You need to also handle that case (see test cases below)
* The absolute or relative difference must be less than `10<sup>-3</sup>` for the sample test cases below.

# Winning criteria

This is , the shortest answer in bytes win!

# Sample test cases

```
Ax Ay Bx By Cx Cy Dx Dy area

5 1 1 3 -1 0 0 -1 0
5 1 1 3 -1 0 0 0 0
5 1 1 3 0 0 0 0 0
5 1 1 3 3 4 4 -3 4.50418
5 1 1 3 1 2 2 1 1.5
5 1 1 3 -2 5 4 -2 1.74829
5 1 1 3 -2 5 5 4 2.96154
5 1 1 3 3 5 5 4 1.88462
5 1 1 3 3 5 3 1 3.92308
5 1 1 3 3 5 4 -1 5.26619
5 1 1 3 5 1 4 -1 0
5 1 1 3 5 1 1 3 7
1 3 1 3 5 1 1 3 0
1 3 1 3 1 3 1 3 0
4 8 4 -1 -2 6 -2 -3 0

1.2 3.4 -0.3 4.2 5 7.6 -1.1 2.4 2.6210759326188535
3.1 0.6 0.1 7.2 5.2 0.7 0.9 8 9.018496993987977

```

If anyone want, here are the outputs for the first test case group in exact form:

```
0
0
0
46375/10296
3/2
1792/1025
77/26
49/26
51/13
23345/4433
0
7
0
0
0

```

Illustration image for test case `5 1 1 3 3 4 4 -3` (the area of the green quadrilateral is the expected output):

\[\]

# Answer
> 17 votes
# Wolfram Language (Mathematica), 55 bytes

```
0&@@Area@BooleanRegion[And,Simplex[{0{,}}~Join~#]&/@#]&

```

Try it online!

Shaved a few bytes off the trivial answer.

```
%@{{{5, 1}, {1, 3}}, {{3, 4}, {4, -3}}} yields 46375/10296 or 4.504176379

```

Replacing `Area` with `DiscretizeRegion` will show the intersection.

By the way, this will work with any simplexes, not just triangles.

-1 Byte thanks to JungHwan Min

@user202729's suggestion added 4 bytes but makes it yield 0 for degenerate triangles

# Answer
> 5 votes
# Python 2 \+ PIL, ~~341~~ ~~318~~ ~~313~~ ~~284~~ 270 bytes

Special thanks to Dennis that promptly added PIL on TIO
-23 bytes thanks to Mr. Xcoder

```
import PIL.Image as I,PIL.ImageDraw as D
l=[i*1000for i in[0,0]+input()+[0,0]]
z=zip(*[[i-min(t)for i in t]for t in l[::2],l[1::2]])
print sum(map(int.__mul__,*map(lambda i,c:D.Draw(i).polygon(c,1)or i.getdata(),map(I.new,'11',[[max(l)-min(l)]*2]*2),[z[:3],z[3:]])))/1e6

```

Try it online! or Try all test cases

To calculate the diference this literally draw the triangles and check the amount of pixels that are painted in both images.
This method inserted a rounding error, that is softened by increasing the image size.

### Explanation

```
#the image/triangles are enlarged to increase the precision
#a pair of zeros are inserted in the start and at the end, this way "l" will have all 6 points to draw the triangles
l=[i*1000for i in[0,0]+input()+[0,0]]
#split the input in x and y, where x=l[::2] and y=l[1::2]
#get the smallest number on each list, that will be "0" if there is no negative number, to be used as offset.
#this will be used to overcome the fact that PIL won't draw on negative coords
#zip "x" and "y" lists, to create a list containing the points
z=zip(*[[i-min(t)for i in t]for t in x,y])
#create 2 (B&W) blank images
#where the size is the difference between the smallest and the largest coord.
map(I.new,'11',[[max(l)-min(l)]*2]*2)
#draw both triangles and return the pixel list of each image
map(lambda i,c:D.Draw(i).polygon(c,1)or i.getdata(),<result of previous line>,[z[:3],z[3:]])
#count the amount of overlapping pixels by summing the color of each pixel, if the pixel is "1" in both images, then the triangles are overlapping, then the amount of pixels is divided by the initial enlarging factor squared (1e6)
print sum(map(int.__mul__,*<result of previous line>))/1e6

```

---
Tags: code-golf, math, geometry
---


title: Keep Decoding This Number!

text:
# Question
Title: Keep Decoding This Number!
This challenge posed an algorithm for encoding an integer `n` as another integer `r`. What follows is a succinct explanation of that algorithm, using `n=60` as an example.

**The original algorithm**

* First, we encode the number as a string of brackets.

+ If `n = 1`, return an empty string.
    + Otherwise, we take `n`'s prime decomposition sorted ascending and replace each element with its prime index (1-indexed) in brackets. `60 = 2*2*3*5 => [1][1][2][3]`
    + Do this recursively until all we have are brackets. `[1][1][2][3] => [][][[1]][[2]] => [][][[]][[[1]]] => [][][[]][[[]]]`
* Once we have our string of brackets, we convert that into an integer with the following process.

+ Convert each opening bracket to a `1` and each closing bracket to a `0`. `[][][[]][[[]]] => 10101100111000`
    + Remove all trailing `0`s and the final `1`. `10101100111000 => 1010110011`
    + Convert the final string of `0`s and `1`s from binary to an integer. `1010110011 => 691`

**Decoding this encoding**

An interesting property of this algorithm is that it is *not* surjective. Not every integer can be the result of this encoding.

* Firstly, the binary representation of the result `r`, must be `balance-able` in that the number of `0`s must never exceed the number of `1`s. A short falsey test case is `4`, which is `100` in binary.
* Secondly, the brackets in the binary representation must be `sorted ascending` when the final `1` and trailing `0`s are appended once more. A short falsey test case is `12 <= 1100 <= 110010 <= (())()`.

However, just determining if a number is decode-able in this way would make for a short challenge. Instead, the challenge is to **repeatedly decode** a given input until either an un-decode-able number or a cycle is reached, and returning the resulting **sequence** of numbers.

**The challenge**

* Given a number `1 <= r <= 2**20 = 1048576`, return the **sequence of numbers** that `r` **successively decodes** into, starting with `r` itself and ending with an un-decode-able number or a cycle.
* If an **un-decode-able number** is given as input, such as `4` or `12`, will return a list containing only the input.
* A sequence ending in a **cycle** should be indicated in some way, either by **appending or prepending a marker** (pick any non-positive integer, string, list, etc. as a marker, but keep it consistent), or by **repeating the cycle** in some way (repeating the first element, repeating the whole cycle, repeating infinitely, etc.).
* On the off chance that any of the sequences are infinite (by increasing forever, for example), consider it undefined behavior.
* This is code golf. Smallest number of bytes wins.

**A worked example of decoding**

```
   1 -> 1 -> 1100 -> [[]] -> [2] -> 3
-> 3 -> 11 -> 111000 -> [[[]]] -> [[2]] -> [3] -> 5
-> 5 -> 101 -> 101100 -> [][[]] -> 2*[2] -> 2*3 -> 6
-> 6 -> 110 -> 110100 -> [[][]] -> [2*2] -> [4] -> 7
-> 7 -> 111 -> 11110000 -> [[[[]]]] -> [[[2]]] -> [[3]] -> [5] -> 11
-> 11 -> 1011 -> 10111000 -> [][[[]]] -> 2*[[2]] -> 2*[3] -> 2*5 -> 10
-> 10 -> 1010 -> 101010 -> [][][] -> 2*2*2 -> 8
-> 8 -> 1000  ERROR: Unbalanced string

```

**Test cases**

```
4 -> [4]
12 -> [12]
1 -> [1, 3, 5, 6, 7, 11, 10, 8]
2 -> [2, 4]
13 -> [13, 13]    # cycle is repeated once
23 -> [23, 22, 14, 17]
51 -> [51, 15, 31, 127, 5381]
691 -> [691, 60]
126 -> [126, 1787, 90907]
1019 -> [1019, 506683, 359087867, 560390368728]

```

Suggestions and feedback for this challenge are most welcome. Good luck and good golfing!

# Answer
# Python 3, ~~379~~ ~~358~~ ~~339~~ ~~337~~ ~~327~~ ~~310~~ 304 bytes

**Conjecture: Is `13` the only number that will lead to a cycle?** (There are no exceptions smaller than 106.)

*Fixed a bug and -7 bytes thanks to Sherlock9.
-3 byte thanks to Jonathan Frech.
-16 bytes thanks to ovs.
-6 bytes thanks to Mr. Xcoder.*

If there is a cycle, it will repeat the whole cycle.

```
def p(a,x=0,n=1):
 while a:x+=1;a-=n%x;n*=x*x
 return x
def g(a):
 c=i=0
 for v in a:
  c+=int(v)*2-1
  if c<0:return 0,0
  if c<1:break
  i+=1
 if a:x=p(g(a[1:i])[0]);b,c=g(a[i+1:]);return(x>c>0)*(0,0)or(x*b,x)
 return 1,0
def f(a):
 x=a,
 while(x.count(a)<3)*a:a,t=g(bin(a-~a)[2:]);x+=a,
 return x[:-1]

```

Try it online!

**Explanation:**

```
def p(a,x=0,n=1):     # return the a-th prime
 while a:             # magical way to enumerate primes
  x+=1
  a-=n%x
  n*=x*x
 return x

def g(a):             # decode a 0/1 string
 c=i=0
 for v in a:
  c+=int(v)*2-1       # +1 if 1, -1 if 0
  if c<0: return(0,0) # c<0: unbalanced parentheses
  if c<1: break       # first outermost parentheses
  i+=1
 if a:
   x=p(g(a[1:i])[0])  # recursive solve those inside the parentheses ...
   b,c=g(a[i+1:])     # and the remaining
   if x>c and c:      # if not ascending
    return (0,0)
   return (x*b,x)     # return (result, value of first closed parentheses)
 return (1,0)         # empty string

def f(a):
 x=a,
 while a and x.count(a)<3: # detect non-decodable or cycle
  a,t=g(bin(a-~a)[2:])     # a-~a is a*2+1
  x+=a,
 return x[:-1]

```
> 4 votes

# Answer
# Pyth, 62 bytes

```
L?b**FKme.fP_Zyd)bSIK1fTseB.u.xyvs@L,"],"\[++JjN2 1m0h-/J1/J00

```

Test suite

Indicates a cycle by repeating the final number.

```
L?b**FKme.fP_Zyd)bSIK1    Define y to decode from list format. 0 if invalid.

fTseB.u.xyvs@L,"],"\[++JjN2 1m0h-/J1/J00
     .u                                     Repeat the following until it cycles
                                            Collecting the values in a list.
                     ++JjN2 1m0h-/J1/J0     Convert the number to expanded binary
            @L,"],"\[                       Map 0 to "],", 1 to "["
           s                                Flatten to a string.
          v                                 Evaluate as a Python object.
       .x                              0    If evaluation fails, return 0.
         y                                  Otherwise decode.
  seB                                       Duplicate the final number
fT                                          Remove all 0s.

```
> 1 votes

---
Tags: code-golf, primes, balanced-string
---