title: Resolve references in a chat discussion

text:
# Question
Title: Resolve references in a chat discussion
Sometimes in chat, if someone says something you agree with, you'll send a message with an `^`, which points at the message above:

```
Radvylf: Cats are far superior to JavaScript
You: ^

```

Sometimes you'll also add some text:

```
Radvylf: I sure do like integers
You: I mostly agree with ^ but floats are pretty neat too

```

You can also use multiple `^`s to refer to messages farther back:

```
Timmy: Puppies are adorable.
Radvylf: I hate puppies.
You: ^^

```

In this challenge, given a chat log with `^`s, you'll replace the `^`s with the messages they refer to.

**Task:**

Given a multiline string of messages (without usernames), or an array where each message is a string (or some representation of one), resolve all of the `^` references in it. Note that messages can refer to messages that themselves have `^`s, which need to be properly resolved.

For example:

```
Cats are funny sometimes
^
^^, but I've met serious cats too.
^^
Opinions on static typing?
It's okay.
^ It depends on the implementation, though.
^ Big difference between good and bad static ty
^ping
Thanks ^_^

```

This would become:

```
Cats are funny sometimes
Cats are funny sometimes
Cats are funny sometimes, but I've met serious cats too.
Cats are funny sometimes
Opinions on static typing?
It's okay.
It's okay. It depends a lot on the implementation, though.
It's okay. It depends a lot on the implementation, though. Big difference between good and bad static ty
It's okay. It depends a lot on the implementation, though. Big difference between good and bad static typing
Thanks It's okay. It depends a lot on the implementation, though. Big difference between good and bad static typing_It's okay. It depends a lot on the implementation, though. Big difference between good and bad static typing

```

You'll never need to resolve a group of `^`s that points up more times than there are messages to point at. E.g., `^` will never be the first line, and `^^` will never be the second.

**Test cases:**

Input:

```
a

```

Output:

```
a

```

Input:

```
a
^b
^^

```

Output:

```
a
ab
a

```

Input:

```
a
^b
^c
^ ^^ ^^^

```

Output:

```
a
ab
abc
abc ab a

```

**Other:**

This is , so shortest answer in bytes per language wins.

# Answer
> 12 votes
# JavaScript (ES6), 56 bytes

Expects and returns an array of strings.

```
a=>a.map((s,i)=>a[i]=s.replace(/\^+/g,s=>a[i-s.length]))

```

Try it online!

# Answer
> 12 votes
# brainfuck, 240 bytes

```
+>>,[[->+<<+>]>----------[+[-<+++>]<+[[-]<.>>,>>>>]<[[[<]<]+[[>]>]<<,[->+++>+<<]+++++[->-----<]>-[[-]<<[[<]<]>>->[.[[>]>]>[->+<]<<+[[<]<]<+>>>-[[[>]>]<<+[[<]<]<+>>>-]>]<<<<[[->>>+<<<]<]>>>+[[>]>->>]<+[-<+>]>>]>[[-]<<+>]<]]<<[.[-]>>>+>>,>]<]

```

Try it online!

Now works with blank lines. This ended up saving bytes, and the slightly altered tape structure allowed the two other improvements I had tried earlier to save bytes as well.

The tape structure of this program is as follows:

```
1 firstline 0 0 0 1 secondline 0 0 0 ... 1 lastline 0 input

```

The 1 cell at the beginning of each line allows the program to cope with empty lines and lines beginning with `^` without additional effort. It also allowed me to shorten the gap between text lines, which saved a small number of bytes.

With formatting and comments:

```
Initialize tape with first line marker and input
+>>,

While there is input:
[

  Duplicate input
  [->+<<+>]

  Test for newline
  >----------

  If not newline:
  [

    Test for ^ (94)
    +[-<+++>]<+

    If anything else:
    [

      Output letter and take next input
      [-]<.>>,

      Move so rest of loop will end at next input cell
      >>>>

    ]

    If caret
    <[

      Place 1 between text lines to track which line to copy
      [[<]<]+[[>]>]<<

      Duplicate next input and check if caret
      (there's probably a shorter way to do this)
      ,[->+++>+<<]+++++[->-----<]>-

      If not another caret:
      [

        Clear test cell
        [-]

        Move to start of line to copy and delete the 1 from it
        <<[[<]<]>>->

        For each letter in that line:
        [

          Output
          .

          Move next input cell to the right
          [[>]>]>[->+<]

          Populate cell to copy to; start backup copy too
          <<+[[<]<]<+>>>-

          Copy letter to (next letter in current line) and (backup 3 left)
          [[[>]>]<<+[[<]<]<+>>>-]

        >]

        Restore line and initial 1 cell
        <<<<[[->>>+<<<]<]>>>+

        Clear indicators between lines
        [[>]>->>]

        Move input to correct cell
        (that cell contains negative one from the previous loop)
        <+[-<+>]

      >>]

      If was another caret:
      >[

        Delete input and set indicator to repeat caret loop
        [-]<<+>

      ]

  <]]

  If newline:
  <<[

    Output newline
    .

    Set up next line
    [-]>>>+>>,>

  ]

<]

```

# Answer
> 6 votes
# Jelly,~~19~~ ~~18~~ 17 bytes

```
ɓŒgċ”^ịṭʋ€Ṛ}Fṭðƒḟ

```

Try it online!

*-1 thanks to Jonathan Allan*

*-1 thanks to Jonathan Allan again*

Takes and returns lists of lines.

```
              ð ḟ    Starting with the input without any of its elements,
               ƒ     reduce by:
ɓ                    with reversed arguments: (line on left, lines on right)
 Œg                  Runs of consecutive equal elements.
        ʋ€           For each run:
       ṭ             append the run to
           }         the accumulated lines
          Ṛ          reversed
      ị              and get the item at the 1-index of
   ċ”^               the number of carets.
            F        Flatten the runs and substitutions back together,
             ṭ       and append to the list of accumulated lines.

```

Love when I shave two bytes off (from `ɓŒg=”^Sị⁸¹?ɗ€Ṛ}Fṭµƒ“”`) in the course of writing an explanation :P

# Answer
> 5 votes
# Retina 0.8.2, 31 bytes

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

```

Try it online! Link includes test cases. Explanation:

```
+1`

```

Replace one match at a time, repeating until all matches have been replaced. (This allows a replaced line to be referenced in a later line.)

```
(\^)+(?<=(.*)(?<-1>¶.*)+)

```

Match a number of `^`s, then search back that many lines for the replacement text.

```
$2

```

Replace the `^`s with the found text.

# Answer
> 4 votes
# Python 3, 87 bytes

```
import re
def f(a,*q):
	for x in a:q+=re.sub("\^+",lambda k:q[-len(k[0])],x),
	return q

```

Try it online!

-11 bytes thanks to Unrelated String

# Answer
> 4 votes
# Ruby, ~~57~~ 51 bytes

```
->c,*q{c.map{|l|q<<l.gsub(/\^+/){|r|q[-r.size]}};q}

```

Try it online!

* Saved 6 Bytes thanks to @G B

Lambda taking and returning an array of lines.

Instead of iterating the size of the array G B proposed to build the output by adding lines one by one, so that we take from that the previous (size of match) line.

We use *gsub* and the {|match| block form } which brings the last match every time.

# Answer
> 3 votes
# 05AB1E, 18 bytes

```
εD'^ÃηRāR(N+¯sè:=ˆ

```

Input as a list of lines.

Try it online or verify all test cases.

**Explanation:**

```
ε           # Foreach of the (implicit) input-list:
 D          #  Duplicate the current line
  '^Ã      '#  Pop the copy, and only keep its "^"
     η      #  Pop and push the list of prefixes of this "^"-string
      R     #  Reverse this list of prefixes
  ā         #  Push a list in the range [1,length] (without popping)
   R        #  Reverse it to range [length,1]
    (       #  Negate each to range [-length,-1]
     N+     #  Add the 0-based loop-index to each: range [N-length,N-1]
       ¯    #  Push the global array
        s   #  Swap so the list of indices is at the top again
         è  #  Index each into the global array
  :         #  Replace all "^"-strings with these strings in the current line
   =        #  Print the modified line with trailing newlines (without popping)
    ˆ       #  Pop and add it to the global array

```

# Answer
> 3 votes
# , 100 bytes

Returns by modifying its input, exits with error.

```
import std;void f(string[]s){for(int i;;i++)s[i]=s[i].replaceAll!(x=>s[i-x[0].length])=`\^+`.regex;}

```

Try it online!

---

# , 97 bytes

This one returns a Range and doesn't error.

```
import std;

```

```
(string[]s,int i=0)=>s.map!(r=>s[i++]=r.replaceAll!(x=>s[i+~x[0].length])=`\^+`.regex)

```

Try it online!

# Answer
> 3 votes
# APL (Dyalog Unicode), 43 bytes

Full program. Prompts for and prints list of strings.

```
⊢{(⍵⊃t)←'\^+'⎕R{t⊃⍨i-≢⍵.Match}t⊃⍨i←⍵}¨⍳≢t←⎕

```

Try it online!

prompt for text from console

`t←` store in `t`

tally of texts

**i**ndices 1 through that

`{` apply the following anonymous lambda to each text; argument is :

`i←⍵` store argument as `i`

`t⊃⍨` pick that element from the input

`'\^+'⎕R{``}`**R**eplace each run of carets with:

`⍵.Match` the match

the length of that

`i-` subtract that from `i`

`t⊃⍨` pick that element from the input

`(⍵⊃t)←` in-place update the argument'th element of `t` with that (and implicitly return it)

return (and implicitly print) that

# Answer
> 2 votes
# Charcoal, ~~51~~ 43 bytes

```
ＷＳ«⊞υω≔⁰θＦ⪪⁺ιψ^¿κ«⊞υ⁺⁺⊟υ⎇θ§υθω⁻κψ≔±¹θ»≦⊖θ»υ

```

Try it online! Link is to verbose version of code. Takes input as a list of newline-terminated lines. Explanation:

```
ＷＳ«

```

Repeat for each line.

```
⊞υω

```

Add a new empty output line to the predefined empty list.

```
≔⁰θ

```

Start with no `^`s.

```
Ｆ⪪⁺ιψ^

```

Append a null character to the input line, split the result on `^`s and loop over the pieces.

```
¿κ«

```

If this piece is not empty, then...

```
⊞υ⁺⁺⊟υ⎇θ§υθω⁻κψ

```

... remove the last line, concatenate a previous line if there were `^`s accumulated, concatenate the split piece without any null characters, and add it back to the list of lines (the indexing for the previous line works because the last line isn't in the array during the concatenation); then...

```
≔±¹θ

```

... set the number of `^`s to `1` assuming that there's a following piece that was separated from this piece with a `^`.

```
»≦⊖θ

```

Empty pieces correspond to consecutive `^`s so simply increment the number of `^`s.

```
»υ

```

Output the final list of lines.

# Answer
> 2 votes
# SNOBOL4 (CSNOBOL4), 106 bytes

```
	T =TABLE()
I	X =X + 1
	I =INPUT	:F(END)
R	I SPAN('^') . K =T[X - SIZE(K)]	:S(R)
	T[X] =OUTPUT =I	:(I)
END

```

Try it online!

# Answer
> 2 votes
# Lua, 83 bytes

```
s=...;for i,l in ipairs(s)do print((l:gsub("%^+",function(m)return s[i-#m]end)))end

```

Must be loaded as a "chunk" (file or string). Expects input as table of strings. Prints output.

# Answer
> 2 votes
# C++ (gcc), ~~191~~ ~~186~~ 181 bytes

```
#import<regex>
int f(std::string*a,int n){for(int b=0,c,i;b<n;++b)for(i=-1;++i<a[b].size();c?a[b].replace(i-c,c,a[b-c]),i+=a[b-c].size()-c:0)for(c=0;a[b][i]==94;++c)++i;}

```

Try it online!

Dang, this is bad. Only wins the Brainfuck answer lol.

For anyone trying to help here's the ungolfed code:

```
#include <iostream>
#include <vector>
#include <string>

void chat_reference(std::vector<std::string> &chat)
{
    for(int list_message = 0; list_message < chat.size(); ++list_message)
    {
        int reference_counter = 0;
        for(int i = 0; i < chat[list_message].size(); ++i)
        {
            while(chat[list_message][i] == '^')
            {
                ++reference_counter;
                ++i;
            }
            if(reference_counter > 0)
            {
                chat[list_message].replace(i - reference_counter, reference_counter, chat[list_message - reference_counter]);
                i += chat[list_message- reference_counter].size() - reference_counter;
                reference_counter = 0;
            }
        }
    }
}

```

*-6 bytes thanks to ceilingcat*

*-4 bytes thanks to ceilingcat*

*-11 bytes thanks to ceilingcat*

---
Tags: code-golf, string
---


title: Can you draw this in one stroke?

text:
# Question
Title: Can you draw this in one stroke?
Related | Related

---

Given an ASCII art with `|`, `_`, and , check if you can draw the art in one stroke.

## Description

Your task is, if the ASCII art is representing lines, then check if you can draw the whole art in one stroke, which means:

* without drawing an already drawn line again
* without lifting and continuing the stroke with skipping blocks

## Connection Rules

* A pipe is connected to the left end of the underscore when:
    + the pipe is left to the underscore `|_`
    + the pipe is bottom-left to the underscore, but only when it's below a space

```
 _
|

```
* A pipe is connected to the right end of the underscore when:
    + the pipe is right to the underscore `_|`
    + the pipe is bottom-right to the underscore, but only when it's below a space

```
_
 |

```
* An underscore is connected to another underscore if it is left/right to it `___`
* A pipe is connected to another pipe if it is above/under it

```
|
|
|

```

A space should not be viewed as a line but as a gap. It can't connect to a pipe or an underscore.

---

So this art can be drawn in one stroke:
(Start at the red cross and end at the blue cross)

# Rules

## Examples

```
[In]:
 __
|__|

[Out]: True

[In]:

|__|
|__|

[Out]: False

[In]:
 ___
|___|_ |

[Out]: False (because of the space)

[In]:
 _
|_|_
  __|
 |__|

[Out]: True

[In]:
 _
|_|_
  |_|

[Out]: True

[In]:
 _   _
|_| |_|

[Out]: False

[In]:
    _
|_||_|

[Out]: False (the middle pipes are not connected)

[In]:
__
|_|

[Out]: True (begin top-left)

[In]:
___
|_

[Out]: False (the pipe can't connect to the above underscore)

[In]:
___
   |
   |
   |
[Out]: True

[In] (example by DLosc):
 _
|_|_
  |_

[Out]: False (the two pipes are connected to each other, and so is each underscore it the upper pipe, but the central underscores are not (because there's a pipe between them) and neither underscore to the lower pipe (because the pipe is not below a space)

```

Good luck!

# Answer
> 9 votes
# Python 3.8 (pre-release), 524 bytes

```
def o(A,C=[5]*3,L=[],E=enumerate):d=A.split('\n');Q=A.count;l,c,r=C;return len(L)==Q('|')+Q('_')or any(r<5and[(T:=(Y:=[int(g)-1for g in str(U)])[:4]*all(len(d)>l+u>-1<c+v<len(d[0])!='|_ '[w]==d[l+u][c+v]for u,v,w in zip(Y[4::3],Y[5::3],Y[6::3])))and r==T[0]and(O:=[l+T[1],c+T[2]])not in L and o(A,O+T[3:],L+[O])for U in[3111,3213211,3124122,3102102,1113,1011011,1024013022,1002013002,4112,4124122,4121121,4223123221,2114,2102102,2101101,2203103201]]or[o(A,[i,j,e+(c<'|')])for i,l in E(d)for j,c in E(l)for e in[0,2]if' '<c])

```

Try it online!

**Input must be rectangular.**

What a mess. The ungolfed version (with long variable names) was a nice 2700 bytes (or so), but I have golfed it down so much that it's down to 524.

Brute-force method. We try to start at every point: for every character that is either a pipe or an underscore, we determine whether:

* it is possible to start at the top of that character if it is a pipe, or the left if it is an underscore, and follow the path of the art (recursively calling the function to move forward, and if there are two or more directions possible, try all of them) until all lines are used up and no line is used more than once; or
* the same is possible with the bottom if pipe, or right if underscore.

When trying to move forward, we store all possible connections according to which character we are currently at and which side of that character we are at, and we use all the connections that are not yet used. If there are none, then it is not possible to draw in one stroke.

---
Tags: code-golf, math, ascii-art, decision-problem, graph-theory
---


title: Radiation Detector!

text:
# Question
Title: Radiation Detector!
A radiation-hardened program is a program where, if any character of the code is removed, the program will still function the same. For this question, we'll be writing a program that detects when it is irradiated.

Write a program or function that, when *any* single byte is removed, the resulting program will output that byte and only that byte. (*You may output that byte multiple times, as long as you don't output any other byte*)

### Rules:

* The program has to contain at least 2 distinct bytes. (No solutions of just 0s ;)
* It doesn't matter what the original program does
* No reading your own source code.
* The code will be scored on the number of distinct bytes, where the highest amount wins. For example, `abc` = 3 points, `ababba` = 2 points, `abc` wins.
    + Tie-breaker is the smaller byte count, followed by the earlier submission time

Good luck!

# Answer
> 15 votes
# 05AB1E, ~~9~~ 7 bytes (Score of 3)

```
22'''rr

```

Try it online!

# Removing a `'`

With any `'` removed, `22''rr` will result in 22 being the first thing on the stack and a `'` being the last thing on the stack, which when reversed twice results in `'`.

# Removing an `r`

With any `r` removed, `22'''r` results in 22 being the first thing on the stack, a `'` being the second thing on stack, and an `r` being the last thing on the stack. This `r`, however, was preceeded by a `'` which makes it the literal string `"r"` (as opposed to the command `reverse stack`), which is implicitly printed.

# Removing a `2`

With any `2` removed, `2'''rr` will result in a `2` being the 1st thing on the stack, `'` being the 2nd thing on the stack and finally `r` being the last thing on the stack, which when reversed once results in `2`.

Therefore, this answer is valid. With nothing removed it outputs `'`, which is irrelevant. This works for any number other than 2 as well.

---

# Created a validity checker, you can use it to compete in 05AB1E\*.

\*I'm not 100% sure how many solutions are even possible in 05AB1E...

---

# More valid solutions that are ***Worse or the Same***

* 1-Point (invalid)
* 2-Point
    + `'''''''VV`, `'''''''XX` or `'''''''<any command that pops a without pushing>x2`
    + Any odd # of `'` above 3 followed by any even # of `s` above 1 (E.G. `'''''''''ssss`).
    + `'''..` with any number of periods above 1 and any odd number of `'` above 2.
* 3-Point
    + `'\\'''rr` \- same idea as `22'''rr` but `\` is 'remove last stack item'.

# Answer
> 11 votes
# Brainfuck, Score 3

May be noncompeting as output is only seen through a memory dump.

```
+++++++++++++++++++++++++++++++++++++++++++++,-

```

Assuming input is empty and EOF leaves the cell unchanged. Uses an interpreter that dumps the memory to an output, such as this one.

Remove a plus, and the memory is the unicode value for "+" , else it is the unicode value for ",". Its more of a rule bender than a answer though. Pretty much the same with "-". Abuses the fact that these three characters are after each other in the unicode-characterset.

# Answer
> 11 votes
# A Pear Tree, 256 distinct bytes, 975 bytes

Unfortunately, the question pretty much requires an optimal solution to contain a NUL byte somewhere (as it needs to contain all 256 bytes somewhere). This means that a) I can't give you a TIO link (because TIO dislikes NUL in programs, or at the least, I haven't figured out a way to type it that my browser can cope with), and b) I can't paste the program into Stack Exchange literally. Instead, I've placed an `xxd` reversible hexdump hidden behind the "code snippet" link beneath.

```
00000000: 0a24 7a7b 242f 7d2b 2b3b 242f 3d24 5c3d  .$z{$/}++;$/=$\=
00000010: 2440 3b21 247a 7b24 5f7d 3f24 7a7b 245f  $@;!$z{$_}?$z{$_
00000020: 7d3d 313a 6465 6c65 7465 247a 7b24 5f7d  }=1:delete$z{$_}
00000030: 666f 7220 7370 6c69 742f 2f2c 3c44 4154  for split//,<DAT
00000040: 413e 3b70 7269 6e74 206b 6579 7325 7a3e  A>;print keys%z>
00000050: 353f 225c 6e22 3a6b 6579 7325 7a3b 5f5f  5?"\n":keys%z;__
00000060: 4441 5441 5f5f 2000 0102 0304 0506 0708  DATA__ .........
00000070: 090b 0c0d 0e0f 1011 1213 1415 1617 1819  ................
00000080: 1a1b 1c1d 1e1f 2326 2728 292a 2b2d 2e30  ......#&'()*+-.0
00000090: 3334 3536 3738 3942 4345 4647 4849 4a4b  3456789BCEFGHIJK
000000a0: 4c4d 4e4f 5051 5253 5556 5758 595a 5b5d  LMNOPQRSUVWXYZ[]
000000b0: 5e60 6162 6367 686a 6d71 7576 7778 7c7e  ^`abcghjmquvwx|~
000000c0: 7f80 8182 8384 8586 8788 898a 8b8c 8d8e  ................
000000d0: 8f90 9192 9394 9596 9798 999a 9b9c 9d9e  ................
000000e0: 9fa0 a1a2 a3a4 a5a6 a7a8 a9aa abac adae  ................
000000f0: afb0 b1b2 b3b4 b5b6 b7b8 b9ba bbbc bdbe  ................
00000100: bfc0 c1c2 c3c4 c5c6 c7c8 c9ca cbcc cdce  ................
00000110: cfd0 d1d2 d3d4 d5d6 d7d8 d9da dbdc ddde  ................
00000120: dfe0 e1e2 e3e4 e5e6 e7e8 e9ea ebec edee  ................
00000130: eff0 f1f2 f3f4 f5f6 f7f8 f9fa fbfc fdfe  ................
00000140: ff4b 3d20 ab0a 247a 7b24 2f7d 2b2b 3b24  .K= ..$z{$/}++;$
00000150: 2f3d 245c 3d24 403b 2124 7a7b 245f 7d3f  /=$\=$@;!$z{$_}?
00000160: 247a 7b24 5f7d 3d31 3a64 656c 6574 6524  $z{$_}=1:delete$
00000170: 7a7b 245f 7d66 6f72 2073 706c 6974 2f2f  z{$_}for split//
00000180: 2c3c 4441 5441 3e3b 7072 696e 7420 6b65  ,<DATA>;print ke
00000190: 7973 257a 3e35 3f22 5c6e 223a 6b65 7973  ys%z>5?"\n":keys
000001a0: 257a 3b5f 5f44 4154 415f 5f20 0001 0203  %z;__DATA__ ....
000001b0: 0405 0607 0809 0b0c 0d0e 0f10 1112 1314  ................
000001c0: 1516 1718 191a 1b1c 1d1e 1f23 2627 2829  ...........#&'()
000001d0: 2a2b 2d2e 3033 3435 3637 3839 4243 4546  *+-.03456789BCEF
000001e0: 4748 494a 4b4c 4d4e 4f50 5152 5355 5657  GHIJKLMNOPQRSUVW
000001f0: 5859 5a5b 5d5e 6061 6263 6768 6a6d 7175  XYZ[]^`abcghjmqu
00000200: 7677 787c 7e7f 8081 8283 8485 8687 8889  vwx|~...........
00000210: 8a8b 8c8d 8e8f 9091 9293 9495 9697 9899  ................
00000220: 9a9b 9c9d 9e9f a0a1 a2a3 a4a5 a6a7 a8a9  ................
00000230: aaab acad aeaf b0b1 b2b3 b4b5 b6b7 b8b9  ................
00000240: babb bcbd bebf c0c1 c2c3 c4c5 c6c7 c8c9  ................
00000250: cacb cccd cecf d0d1 d2d3 d4d5 d6d7 d8d9  ................
00000260: dadb dcdd dedf e0e1 e2e3 e4e5 e6e7 e8e9  ................
00000270: eaeb eced eeef f0f1 f2f3 f4f5 f6f7 f8f9  ................
00000280: fafb fcfd feff 4b3d 20ab 0a24 7a7b 242f  ......K= ..$z{$/
00000290: 7d2b 2b3b 242f 3d24 5c3d 2440 3b21 247a  }++;$/=$\=$@;!$z
000002a0: 7b24 5f7d 3f24 7a7b 245f 7d3d 313a 6465  {$_}?$z{$_}=1:de
000002b0: 6c65 7465 247a 7b24 5f7d 666f 7220 7370  lete$z{$_}for sp
000002c0: 6c69 742f 2f2c 3c44 4154 413e 3b70 7269  lit//,<DATA>;pri
000002d0: 6e74 206b 6579 7325 7a3e 353f 225c 6e22  nt keys%z>5?"\n"
000002e0: 3a6b 6579 7325 7a3b 5f5f 4441 5441 5f5f  :keys%z;__DATA__
000002f0: 2000 0102 0304 0506 0708 090b 0c0d 0e0f   ...............
00000300: 1011 1213 1415 1617 1819 1a1b 1c1d 1e1f  ................
00000310: 2326 2728 292a 2b2d 2e30 3334 3536 3738  #&'()*+-.0345678
00000320: 3942 4345 4647 4849 4a4b 4c4d 4e4f 5051  9BCEFGHIJKLMNOPQ
00000330: 5253 5556 5758 595a 5b5d 5e60 6162 6367  RSUVWXYZ[]^`abcg
00000340: 686a 6d71 7576 7778 7c7e 7f80 8182 8384  hjmquvwx|~......
00000350: 8586 8788 898a 8b8c 8d8e 8f90 9192 9394  ................
00000360: 9596 9798 999a 9b9c 9d9e 9fa0 a1a2 a3a4  ................
00000370: a5a6 a7a8 a9aa abac adae afb0 b1b2 b3b4  ................
00000380: b5b6 b7b8 b9ba bbbc bdbe bfc0 c1c2 c3c4  ................
00000390: c5c6 c7c8 c9ca cbcc cdce cfd0 d1d2 d3d4  ................
000003a0: d5d6 d7d8 d9da dbdc ddde dfe0 e1e2 e3e4  ................
000003b0: e5e6 e7e8 e9ea ebec edee eff0 f1f2 f3f4  ................
000003c0: f5f6 f7f8 f9fa fbfc fdfe ff4b 3d20 ab    ...........K= .
```

## Explanation

This program consists of three identical parts. (Concatenating multiple identical portions of a program is something of a theme for me in programs.) Every A Pear Tree requires a checksum somewhere to let the interpreter know which parts of the program to run; it rotates any portion of the program for which the checksum succeeds to the start before running it (or prints `a partridge` if no checksum matches). In this case, we have a checksum on each of the three parts, and thus a non-irradiated part will move to the start. So we can assume that the program consists of an unmodified part, followed by two other parts (one of which may have been modified).

Each part starts with a newline, then continues with the following code (I've added whitespace and comments below):

```
$z{$/}++;      # In the hash table %z, set the key "\n" to 1
$/=$\=$@;      # Turn off newline handling when reading ($/ = undef);
               # Also don't add newlines when printing ($\ = undef)
               # $@ is set to undef by default
!$z{$_}?       #   If the current character is not in the hash table %z
  $z{$_}=1:    #   place it in the hash table %z
  delete$z{$_} #   else remove it from the hash table %z
for split//,   # for each character in
    <DATA>;    # the text appearing from the line beneath __DATA__ to EOF
print          # Print the following (no newline because $\ was undefined):
  keys%z>5?    # if the hash table %z contains more than 5 elements:
  "\n":        #   a newline; otherwise
  keys%z;      #   every key of %z, separated by spaces
__DATA__       # Start a string literal running from after this line to EOF

```

After that comes a copy of every octet that hasn't been used in the program so far (purely to run the score up), and finally the checksum. (There's no trailing newline; parts start with a newline but don't end with one.)

There are three distinct cases here:

* **A character other than a newline was deleted**. In this case, it'll appear an odd number of times in the second and third parts. That means it'll be added and/or removed from `%z` an odd number of times, finally ending up in the hash table. In fact, it'll be the *only* key in the hash table (as the string runs from after the newline of the second part to the end of the third part, and the hash table started with just a single newline), so it'll just be printed out on its own.
* **The first or third newline was deleted**. In this case, the program will be rotated such that it's the third of the newlines that's missing, effectively merging the second and third parts into a single line. The string literal accessed via `<DATA>` contains every character an even number of times, so the hash table will have its original content, a single newline, and that'll get printed.
* **The second newline was deleted**. In this case, the program won't be rotated (as the first part has a valid checksum), so the second part will be moved onto the same line as the first part. `<DATA>` only starts reading from the line below `__DATA__`, so it'll only see the third part. This has more than five characters that appear an odd number of times, so it'll trigger the special case to print a newline.

## Verification

One final thing that has to be checked for pretty much any radiation-hardened A Pear Tree program is whether a deletion happens to randomly cause an unwanted section of the code to checksum correctly and rotate the code into the wrong place; given that we're using 32-bit checksums, this is unlikely but not impossible. I used the following brute-force script to ensure that this doesn't happen for any deletion:

```
use 5.010;
use IPC::Run qw/run/;
use warnings;
use strict;
use Data::Dumper;
$Data::Dumper::Useqq=1;
$Data::Dumper::Terse=1;
$Data::Dumper::Indent=0;
undef $/;
$| = 1;
my $program = <>;

for my $x (0 .. (length($program) - 1)) {
    my $p = $program;
    my $removed = substr $p, $x, 1, "";
    alarm 4;
    say Dumper($p);
    run [$^X, '-M5.010', 'apeartree.pl'], '<', \$p, '>', \my $out, '2>', \my $err;
    if ($out ne $removed) {
        print "Unexpected output deleting character $x ($removed)\n";
        print "Output: {{{\n$out}}}\n";
        print "Errors: {{{\n$err}}}\n";
        exit;
    }
}

say $program;
run [$^X, '-M5.010', 'apeartree.pl'], '<', \$program, '>', \my $out, '2>', \my $err;
if ($out ne '') {
    print "Unexpected output not mutating\n";
    print "Output: {{{\n$out}}}\n";
    print "Errors: {{{\n$err}}}\n";
    exit;
}

say "All OK!";

```

The verification script confirms that this program works correctly.

# Answer
> 7 votes
# Stax, 11 bytes (Score of 4)

```
'''cc'~~'dd

```

Run and debug online!

It is my honor to have the first (chronologically) answer to this challenge with a score higher than or equal to 4. Maybe the score can be even higher though.

In Stax, a string literal that is composed of a single character is written with `'`, so `'', 'c, 'd, '~` are all string literals. The corresponding commands for `c` `d` and `~` means duplicate the top of the main stack, pop the top of the main stack, and pop the top of the main stack and push to the input stack, respectively. For this challenge, input stack does not affect output and is not important, hence we can say `d` and `~` are identical.

## Explanation

It is best to divide the code into several parts and consider them separately.

When it is not tampered with, `'''cc` pushes a literal `'` and a literal `c` to the main stack, and duplicates the top, so the stack would be (from to bottom) `c,c,'`.

When not tampered with, `'~~` pushes the literal `~` and then pops it (and push to the input stack), which is basically a no-op for the main stack.

When not tampered with, `'dd` pushes the literal `d` and then pops it, another no-op for the main stack.

At the end of the program, since no explicit output is done, the top of the main stack will be implicitly printed out.

If the program is running as-is, the final stack is still `c,c,'` and will output `c`.

If the first part becomes `''cc`, then we have a literal `'`, and two copy instructions, the final stack will be `',','`. Given that the two other parts are no-op, the result will be `'`.

If the first part becomes `'''c`, the result is basically the same with the untampered one, but the `c` is not duplicated. So the stack will be `c,'`. After two no-op's the top of the stack is `c`.

So we can detect radiation in the first part.

The second part and the third part work in exactly the same way. I will take the third part as an example.

If the third part is tampered with, then the first two parts are kept as-is and the stack before running the third part is `c,c,'`

If the third part becomes `'d`, a literal `d` is pushed to the top of the main stack and nothing further is done. The top of the main stack is now `d` which will be output.

If the third part becomes `dd`, two elements are popped from the main stack and now the top of the stack is `'` and is output.

Hence we can detect radiation in the third part. For the same reason we can detect radiation in the second part.

# Answer
> 5 votes
# Jelly, 5 bytes, score 2

```
”””ḷḷ

```

Try it online!

**With any  removed:**

```
””ḷḷ

```

Try it online!

The character  begins a one byte character literal. This programs begins with `””` which yields the string . The  dyad takes it's left argument. The string  just gets passed through the two instances of .

**With any  removed:**

```
”””ḷ

```

Try it online!

In this program `””` yields the character  then `”ḷ` yields the character  and only this is output.

---

**Other solutions**

* Lots of other characters such as `a` or `o` would have worked in place of  for this submission.
* `⁾⁾⁾⁾FFF`. This works in a similar way.  is like  but it starts a *two* byte string literal. The "irradiated" programs output the deleted byte twice which was ruled valid in the comments.

---

Here is a (much less fancy) Jelly version of Magic Octopus Urn's validity checker. The left column of the output is the deleted character and the right column is the output of the resulting program.

# Answer
> 5 votes
# 05AB1E, score 2, 6 bytes

```
„"""„„

```

Prints double the removed character sometimes. Doesn't contain `'`.

# How it works:

## Removing the first

```
"""„„

```

Try it online!

First, we push an empty string literal to the stack. Then we push `„„`, which is printed implicitly.

## Removing a `"`

```
„""„„

```

Try it online!

First, we push `""` to the stack with the `2-char string` instruction. Then we try to get another 2-character string, but this is aborted (I'm not exactly sure why) and the `""` is printed.

## Removing the second or third

```
„"""„

```

Try it online!

First, we push `""` to the stack with the `2-char string` instruction. Then we push , which is printed implicitly.

# Answer
> 2 votes
# Vyxal, 65 bytes, score 22

```
\\\::\__\⅛⅛\££\→→\((\[[\‟‟\**\••\--\oo\PP\ḞḞ\↳↳\↲↲\⋏⋏\ǑǑ\FF\jj\∇∇

```

Try it Online!

Based on Weijun Zhou's Stax answer.

In Vyxal, `\` takes the next character as a single character. So, the bit at the start `\\\::` pushes `"\"`, pushes `":"`, then duplicates it with the operation `:`.

The stack is now `["\", ":", ":"]`.

If either `:` is removed, the `:` operation is not run and the stack is just `["\", ":"]`. If any `\` is removed, the stack becomes `["\","\","\"]`.

The rest of the program is chunks of `\xx`, where x is some operation that effectively does nothing but remove a string from the stack. These chunks normally do nothing, as they effectively push and pop a value.

If a backslash is removed, an operation that effectively pops the stack is run twice, removing the two `":"` from the stack and leaving the backslash we pushed at the start.

If either x is removed, the string `"x"` is pushed to the stack and not removed.

Finally, the top of the stack is implicitly output.

### Operations, and why they work

For these, `x` is the value already on the stack and `y` is the value

* `_` \- Simply pops `y`
* \- Pushes `y` to the global array.
* `£` \- Stores `y` to the register
* \- Stores `y` to the empty variable
* `(` \- starts a for loop over `y`. As it's a 1-character string the code inside is run once
* `[` \- If `y` is truthy, execute the remaining code. It will always be truthy.
* \- Rotate `y` to the bottom of the stack.
* `*` \- Ring translate `x` by `y`. Since the strings share no characters, nothing happens.
* \- Give `x` the casing of `y`. Since this occurs before anything alphabetical, nothing happens.
* `-` \- Remove `y` from `x`
* `o` \- Remove `y` from `x`
* `P` \- Strip `y` from the outside of `x`
* \- Replace spaces in `x` with `y`. There are no spaces in `x`.
* \- Pad `x` according to `y`
* \- Pad `x` according to `y`
* \- Center `x` according to `y`
* `Ǒ` \- Remove `y` from `x` until `x` doesn't change
* `F` \- Remove characters in `y` from `x`
* `j` \- Join `y` by `x`. This does nothing to a 1-character `x`.
* \- Rotate the top three items of the stack. Has to be at the end.

---
Tags: code-challenge, radiation-hardening
---


# Question
Title: What is the longest possible DDL query in PostgreSQL?
We all know and love the corpulent DDL expressions one can write in PostgreSQL with wording like `DEFERRABLE INITIALLY DEFERRED`, `ALTER FOREIGN DATA WRAPPER`, or even `DROP TEXT SEARCH CONFIGURATION`. But how far can one go? Here comes the definitive challenge for the longest DDL expression, with constraints of course. Mwahahaha!

Rules:

* The length of the submission is counted in Unicode codepoints.
* Whitespaces are contracted to minimally necessary when counting.
* The semicolon counts.
* The submission must be a valid data definition expression in PostgreSQL 12 as described in the relevant manual section.
* Optionally repeatable subexpressions (like column definitions in a `CREATE TABLE`) must not be repeated.
* Every user-specifiable identifier only adds 1 towards the total length. So a table named `a` is worth the same as `aaa`.
* Function call expressions add exactly 4 towards the total length, as if they were always of the form `f(x)`.
* String constants only add as much towards the total length as if they were empty strings.
* Numeric constants always add exactly 1 towards the total length, as if all you had were single digit integers.
* Recursion is not allowed. For example, the `SQL SELECT` statement defines the concept of a **from\_item** recursively, where a **from\_item** can be of the form **from\_item** \[...\] **join\_type** \[...\] **from\_item**. This is a recursive definition, and its usage is forbidden. This challenge disallows terms embedded in the same type of term, in any depth.

Good luck, have fun. To kickstart your thoughts, here's a beatable example of length 106:

```
  create function f(x)
  returns table(a float) as $$$$
  language sql
  rows 1
  immutable
  parallel safe
  leakproof;

```

# Answer
# PostgreSQL 12, `CREATE TABLE`, 482 chars:

```
CREATE GLOBAL TEMPORARY TABLE IF NOT EXISTS table_name
PARTITION OF parent_table (column_name WITH OPTIONS CONSTRAINT constraint_name REFERENCES reftable (refcolumn) MATCH PARTIAL ON DELETE referential_action ON UPDATE referential_action NOT DEFERRABLE INITIALLY IMMEDIATE CONSTRAINT constraint_name
EXCLUDE USING index_method (column_name opclass DESC NULLS FIRST WITH operator) INCLUDE (column_name) WITH (storage_parameter = value) USING INDEX TABLESPACE tablespace_name WHERE (predicate) NOT DEFERRABLE INITIALLY IMMEDIATE) FOR VALUES WITH (MODULUS numeric_literal, REMAINDER numeric_literal) PARTITION BY RANGE (column_name COLLATE collation opclass) USING method WITHOUT OIDS ON COMMIT PRESERVE ROWS
TABLESPACE tablespace_name;

```

# How?

To produce the largest possible DDL query in PostgreSQL 12, I wrote a script that does the following:

1. Navigates to the full list of PostgreSQL 12 commands.
2. For each command, extracts its synopsis.
3. Parses the synopsis into an Abstract Syntax Tree.
4. Traverses the Abstract Syntax Tree, producing all queries, pruning branches for rudimentary optimization by choosing the longest keywords.
5. For the generated queries, finds the maximum by condensing non-keyword identifiers down to a single character, eliminating unnecessary whitespace, etc.
> 2 votes

---
Tags: code-bowling, sql
---


title: Draw dice results in ASCII

text:
# Question
Title: Draw dice results in ASCII
Show the random result of a dice toss if done with a cube shaped die, in ASCII.

```
$ dice

```

should result in one of

```
-----
|   |
| o |
|   |
-----

-----
|o  |
|   |
|  o|
-----

-----
|o  |
| o |
|  o|
-----

-----
|o o|
|   |
|o o|
-----

-----
|o o|
| o |
|o o|
-----

-----
|o o|
|o o|
|o o|
-----

```

# Answer
> 7 votes
## Golfscript, 56 characters

```
"-"5*n"|":|"o "1/:&6rand:§1<=" "&§3<=|n|&§5<=]&§2%=1$-1%

```

The solution can be tested here.

# Answer
> 30 votes
## Python, 112 110 chars

```
from random import*
r=randrange(6)
C='o '
s='-----\n|'+C[r<1]+' '+C[r<3]+'|\n|'+C[r<5]
print s+C[r&1]+s[::-1]

```

# Answer
> 11 votes
## Ruby 1.9, 80 ~~84~~ characters

```
z=" o";$><<(s=?-*5+"
|#{z[2/~a=rand(6)]} #{z[a/3]}|
|"+z[a/5])+z[~a%2]+s.reverse

```

# Answer
> 8 votes
## Windows PowerShell, 89 ~~93~~ ~~96~~ ~~97~~ ~~101~~ ~~119~~ characters

```
-join('-----
|{0} {1}|
|{2}{3}'-f'o '[$(!($x=random 6);$x-lt3;$x-ne5;$x%2)])[0..14+13..0]

```

# Answer
> 6 votes
### Python, 109 unicode characters

```
#coding:u8
print u"鱸헓ȅ᪮ԅ᪅餠☏汁끝鐸즪聗K糉툜㣹뫡燳闣≆뤀⩚".encode("u16")[2:].decode("zlib").split("\n\n")[id(list())%7-1]

```

Note: This does not used random function, so it will be not so random like others does.

# Answer
> 5 votes
## Perl, 74 chars

Run with `perl -M5.010`.

```
$-=rand 6;$_="-----
|0 2|
|4";s/\d/$->$&?o:$"/ge;say$_,$-&1?$":o,~~reverse

```

(Note that the newlines in the listing are part of the string, and not just inserted for legibility.)

If you find yourself wondering what the heck the `$->$` operation does, the following reading notes may be helpful:

* The variable `$-` automatically truncates its assigned value to an integer.
* The variable `$"` is preset to a single space.
* `o` is a bareword (representing `"o"`).

# Answer
> 4 votes
First time golfer

## Python, 161 chars

```
from random import*
n=randint(1,7)
o,x='o '
a='-'*5
b=(x,o)[n>3]
d=(x,o)[n>5]
c=(x,o)[n>1]
print a+'\n|'+c+x+b+'|\n|'+d+(x,o)[n%2]+d+'|\n|'+b+x+c+'|\n'+a

```

# Answer
> 4 votes
# JavaScript, ~~215~~ ~~213~~ ~~212~~ ~~145~~ 135

```
r=Math.random()*6|0;alert('-----\n|'+[r>2?'o o':r?'o  ':'   ',r%2?r>3?'o o':'   ':' o ',r>2?'o o':r?'  o':'   '].join('|\n|')+'|\n-----');

```

Beat mellamokb, but I changed my original solution completely. If you want this to look good, use Google Chrome or something, change `alert` to `console.log`, and voilà.

Edit: borrowed mellamokb's |0 trick to save some characters.

# Answer
> 4 votes
# **Common Lisp 170**

```
(let*((r(random 6))(a "-----
|")(c "o")(d " ")(e "|
|")(f(concatenate 'string a(if(< r 1)d c)d(if(< r 3)d c)e(if(> r 4)c ))))(concatenate 'string f(if(evenp r)c d)(reverse f)))

```

Note that the newlines are significant. Unlike these silly "modern" languages, Common Lisp favors readability over succinctness, so we have the cumbersome "concatenate 'string..." construct and no succinct way to reference a character in a string.

# Answer
> 4 votes
## JavaScript (169 168 141 137)

```
r=Math.random()*6|0;s='-----\n|'+(r>0?'o ':'  ')+(r>2?'o':' ')+'|\n|'+(r-5?' ':'o');alert(s+(r%2?' ':'o')+s.split('').reverse().join(''))

```

Doesn't look quite right in `alert` because it's not fixed-width font, but rest assured it is correct, or test by emitting a `<pre>` tag and doing `writeln` :-)

Proof: http://jsfiddle.net/d4YTn/3/ (only works in JS 1.7-compliant browsers, such as FF2+)

Credits: Hacked `Math` trick from @minitech and die print logic from @Keith.

**Edit**: Remove `Math` trick from @minitech because it actually made it *longer* :-)

**Edit 2**: Save 17 chars. Borrow trick from @Keith for taking advantage of dice symmetry. Use trick for simplifying converting random number to int.

**Edit 3**: Remove `1+` to shift random number from 1-6 to 0-5 and save 2 chars. As a result, I can also change `r%2-1` to `r%2` and save another 2 chars.

**Edit 4**: jsfiddle is working again. Updated :-)

# Answer
> 3 votes
**PHP 119 126 128 131 188 201 213 234 239**

```
<?$c=($r=rand()%6)%2?$r>4?'o ':'  ':' o';$b=$r>0?$r<3?'o  ':'o o':'   ';echo$a="-----\n|$b|\n|$c",substr(strrev($a),1);

```

# Answer
> 3 votes
**Python** **108** 114 119 121 122 129

wtf! looks like 1st solution ?! but iam not ... cheater

108

```
import random as R
i=R.randint(1,6)
X=' 0'
A='-----\n|%s %s|\n|'%(X[i>1],X[i>3])+X[i>5]
print A+X[i%2]+A[::-1]

```

119

```
import random as R
i=R.randint(1,6)
X=' 0';a=X[i>5]
A='-----\n|%s %s|\n|%s|'%(X[i>1],X[i>3],a+X[i%2]+a)
print A+A[-6::-1]

```

# Answer
> 3 votes
Python 133

```
import random as R
i=R.randint(1,6)
a='   ';b='0 0'
A='-----\n|'+((a,'0  ')[i>1],b)[i>3]+'|\n|'
print A+((a,' 0 ')[i%2],b)[i>5]+A[::-1]

```

# Answer
> 3 votes
## F# - 165 161 characters

```
(System.Random()).Next 6|>fun x->[for y in[x>0;x%2=0;x>2;x=5]->if y then"o"else" "]|>fun[a;b;c;d]->printf"-----\n|%s %s|\n|%s%s%s|\n|%s %s|\n-----"a c d b d c a

```

# Answer
> 3 votes
### perl - 111 103 101

```
$n=int rand 6;
($t="-----\n|0 1|\n|232|\n|1 0|\n-----\n")=~s/(\d)/5639742>>6*$1>>$n&1?o:$"/eg;
die$t;

```

# Answer
> 3 votes
## APL (69)

```
5 5⍴(5⍴'-'),{⊃⍵↓' o|'}¨2,(⌽M),2,2,(N∊¨6(1 3 5)6),2,2,2,⍨M←3 6 1>⍨N←?6

```

# Answer
> 3 votes
### Golfscript ~~80~~ 65

```
6rand):^;'-'5*n+:_[^6&0^4&^6=].^1&+-1%+3/{'|'\{'o'' 'if+}/'|'n}/_

```

The program can be tested here

# Answer
> 3 votes
## Haskell, *154* 162 167 172 chars

```
import System.Random
main=randomRIO(1::Int,6)>>=putStrLn. \x->let{h="-----\n|"++c(>1):' ':c(>3):"|\n|"++[c(>5)];c f|f x='o'|True=' '}in h++c odd:reverse h

```

It uses roughly the same idea as the Python one.

Readable version:

```
import System.Random

main = do
    x <- randomRIO (1 :: Int, 6)
    putStrLn (render x)

render x = str ++ check odd ++ reverse str
  where
    str = concat
        [ "-----\n|"
        , check (> 1)
        , " "
        , check (> 3)
        , "|\n|"
        , check (> 5)
        ]
    check f = if f x then "o" else " "

```

# Answer
> 2 votes
**PHP 126 127 179**

```
<?$x=($r=rand(1,6))>3?"o o":($r<2?"   ":"o  ");$z=$r>5?"o o":($r%2==0?"   ":" o ");$v="-----\n|$x|\n";echo"$v|$z|".strrev($v);

```

Another PHP solution. I came to the almost same solution by Oleg.

# Answer
> 2 votes
**C** \- 215

```
#include <time.h>
#include <stdlib.h>
main(){char a[]=A,b[]=B,c=3,d=(srand(time(0)),rand()%6+1),e=d-2;if(d==1)a[5]=C;else{while(--e>-1)a[b[D[d-3]-48+e]-48]=C;a[0]=a[10]=C;}p(E);while(--c>-1)p("|%s|\n",a+c*4);p(E);}

```

Compiles with:

```
cl /DA="\"   \0   \0   \"" /DB="\"5282582468\"" /DC='o' /DD="\"0136\"" /DE="\"+---+\n\"" /Dp=printf dice.c

```

# Answer
> 2 votes
## Python (153)

This is by far not the smallest submission, i just thought it looked nice :)

```
import random as r
print"""-----
|%c %c|
|%c%c%c|
|%c %c|
-----"""%tuple(
r.choice([
"   o   ",
"o     o",
"o  o  o",
"oo   oo",
"oo o oo",
"ooo ooo"]))

```

# Answer
> 2 votes
# Q (120 chars)

```
dice:{(`t`e`l`c`r`w!5 cut"-----|   ||o  || o ||  o||o o|")(,/)(`t;(`e`c`e;`l`e`r;`l`c`r;`w`e`w;`w`c`w;`w`w`w)(*)1?6;`t)}

```

Usage:

```
dice[]

```

# Answer
> 2 votes
# C, ~~168~~ ~~164~~ 163 chars

Sorry if I'm a bit late to the party, but since no answer has been accepted yet, and the only other C solution was somewhat longer, here goes...

```
#include<stdio.h>
main(){srand(time(0));char*o="O ",r=rand()%6,i=o[r<1],j=o[r<3],k=o[r<5];printf("-----\n|%c %c|\n|%c%c%c|\n|%c %c|\n-----\n",i,j,k,o[r&1],k,j,i);}

```

You can remove the include and save another 18 chars, but then it doesn't compile without warnings.

**Edit**:
using user23241's command-line trick, the shortest C code that produces the result (without compiler warnings) is only 12 chars:

```
#include I
M

```

At least if you cheat and use the following command line to compile:

```
gcc -DI="<stdio.h>" -DM="main(){srand(time(0));char*o=\"O \",r=rand()%6,i=o[r<1],j=o[r<3],k=o[r<5];printf(\"-----\n|%c %c|\n|%c%c%c|\n|%c %c|\n-----\n\",i,j,k,o[r&1],k,j,i);}" dice.c -o dice

```

# Answer
> 2 votes
# c, 140 chars

```
r,i,s;main(){srand(time(i=0));r=rand()%6;for(s=-1;i-=s;)putchar("\n|   |-o"[i>5?i==8&&r||i==10&&2<r||i==14&&4<r||i==15&&(s=1)&~r?7:i%6:6]);}

```

# Answer
> 1 votes
## PHP:1284

This is my second CodeGolf, and I wasn't really aiming for shortness as much as code mutability and matching the gaming criteria.

You can generate 4 sided dice as well as 6 sided.

Maybe later I will shorten it and make it a little more dynamic.

```
function draw_dice($numdice=1,$sides=4)
{
/* Verify acceptable parameters. */
if($sides<4){die("You must choose 4 sides or greater.");}
if($numdice<1){die("You must have at least one dice.");}
/* End verification */
$a=' ';
$b=' ';
$c=' ';
$d=' ';
$e=' ';
$f=' ';
$g=' ';
$h=' ';
$i=' ';
$j=' ';

switch($sides)
{
case $sides%2==0:
if($sides==4)
{
$ran=rand(1,$sides);
switch($ran)
{
case 1:
$e="o";
break;
case 2:
$a="o";
$j="o";
break;
case 3:
$b="o";
$g="o";
$j="o";
break;
case 4:
$a="o";
$c="o";
$g="o";
$j="o";
break;
}
echo "<div style='text-align:center;display:inline-block;'>";
echo " - <br/>";
echo "| |<br/>";
echo "|$a$b$c|<br/>";
echo "| $d$e$f |<br/>";
echo "|  $g$h$i$j  |<br/>";
echo "---------<br/>";
echo "</div>";

}

if($sides==6)
{
$ran=rand(1,$sides);
switch($ran)
{
case 1:
$e="o";
break;
case 2:
$a="o";
$i="o";
break;
case 3:
$a="o";
$i="o";
$e="o";
break;
case 4:
$a="o";
$c="o";
$g="o";
$i="o";
break;
case 5:
$a="o";
$c="o";
$g="o";
$i="o";
$e="o";
break;
case 6:
$a="o";
$c="o";
$d="o";
$f="o";
$g="o";
$i="o";
break;
}
echo "-----<br/>";
echo "|$a$b$c|<br/>";
echo "|$d$e$f|<br/>";
echo "|$g$h$i|<br/>";
echo "-----<br/>";
}

if($sides!==4&&$sides!==6)
{
die("Only 4 and 6 sided are supported at this time.");
}

break;

case $sides%2==1:
die("Must have even number of sides.");
break;
}

}

draw_dice(1,4);

```

## Output 4 sided:

```
    -
   | |
  |o o|
 |     |
|  o  o  |
---------

```

## Output 6 sided:

```
-----
|o  |
| o |
|  o|
-----

```

# Answer
> 1 votes
## JavaScript 220 bytes

```
r=(1+Math.random()*6|0).toString(2).split("").reverse();b=r[1];c=r[2];s=[[b|c,0,c],[b&c,1&r[0],b&c],[c,0,b|c]];"-----\n|"+s.map(function(v){return v.map(function(w){return w?"o":" "}).join("")}).join("|\n|")+"|\n-----";

```

# Answer
> 1 votes
# PHP 5.4, 107 bytes

```
<?$r=rand(1,6);$d=[' ','o'];$o='+---+
|'.$d[$r>1].' '.$d[$r>3].'|
|'.$d[$r>5];echo$o.$d[$r%2].strrev($o);

```

**102 bytes\***

```
<?$r=rand(1,6);$d=' o';$o='+---+
|'.$d[$r>1].' '.$d[$r>3].'|
|'.$d[$r>5];echo$o.$d[$r%2].strrev($o);

```

\**Unfortunately, the 102 byte version issues notices due to the casting of `bool` to `int` when indexing the string `$d`. Other than that, it works fine.\*

# Answer
> 1 votes
### Ruby , 134 132 119 118 117 112 111 chars,

My second golf in life. I've used magic numbers. Any advises please?

```
r=?-*5+"
|"+((a=:ghklm[rand 6])?a.to_i(36).to_s(2).tr("10","o "):"    o").insert(3,"|
|")
$><<r+r[0,14].reverse

```

Outputs:

```
ice@distantstar ~/virt % ruby ./golf.rb
-----
|o o|
|   |
|o o|
-----
ice@distantstar ~/virt % ruby ./golf.rb
-----
|o o|
|o o|
|o o|
-----
ice@distantstar ~/virt % ruby ./golf.rb
-----
|   |
| o |
|   |
-----
ice@distantstar ~/virt %

```

# Answer
> 1 votes
# Mathematica 166 161 146 143 chars

```
a="O  ";b=" O ";c="  O";d="   ";e="O O";RandomInteger@{1, 6}/.Thread@Rule[Range@6,{{d,b,d},{a,d,c},{a,b,c},{e,d,e},{e,b,e}, {e,e,e}}]//MatrixForm

```

Sample Output:

---

If the matrix braces offend, you may replace `MatrixForm` with `TableForm` in the code.

# Answer
> 1 votes
## VimScript – 169 chararacters

Note that this is not pure Vim since Vim has no builtin random number generator. There are extensions that can be downloaded for it of course, but since I am a diehard Linux man, I thought, why not just rely on the shell environment instead.

### Code

```
norm5a-^[YPo|   |^[YPP
let x=system('echo $RANDOM')%6+1
if x<2
norm jllro
el
norm lrolljj.k
if x>3
norm k.hjj
en
if x>2
norm h.k
en
if x>5
norm .l
en
if x>4
norm l.
en
en

```

### Explanation

* The first line generators the "box" that represents the die.
* The second line fetches a random number from the environment and using modular arithmetic forces it to be a valid number for a dice.
* The remaining lines move around the die face filling in the `o` 's. Note that this is meant to be optimized for the least number of characters, not the least number of movements (i.e. there would be faster ways in turns of keystrokes if I was doing it manually—doing the `if`s all in my head).
* As always, `^` is not a literal `^` but an indication of an escape sequence.

### Testing

Change `RANDOM` to `DICEVALUE`, save the VimScript code into `dice.vim`, then run this shell script on it, giving as arguments whatever numbers you want to test:

```
#!/bin/sh
for DICEVALUE in $@; do
    export DICEVALUE
    vim -S dice.vim
done

```

# Answer
> 0 votes
# SmileBASIC, ~~117~~ 99 bytes

```
N=RND(6)B=N>2?"-"*5L!!N*5-B*2L!(N<<31)*4-(N>4)L!!N+B*2?"-"*5DEF L I?"|";MID$("   o o  ",I,3);"|
END

```

Output

Cheating version: `?""[RND(6)]` (What it looks like in SmileBASIC's font)

# Answer
> 0 votes
# Vyxal, 38 bytes

```
3`|% |%%`-3/ømvøm⁋»∧⁰¾×O↓»b7ẇ℅ƛ‛o $i;%

```

Try it Online!

```
=== Part 1: Construct the dice ===
         -         # Prepend...
3                  # Literal
         -         # Minuses to...
 `|% |%%`          # Literal
          3/       # Into 3 pieces
            ømvøm  # Quad palindromise
                 ⁋ # Newline joined
=== Part 2: Roll the dice ===
»...»             # Compressed base-2 integer containing bits for each
     b            # To bits
      7ẇ℅         # Choose a random group of 7
         ƛ     ;  # Map...
          ‛o $i   # o or space depending on if its truthy
                % # Format above with this

```

# Answer
> 0 votes
# , 58 55 52 bytes

```
?@6{' o|-'{~6 3 3(3,~3,2,.,.&2)"2@$#:@36b3igm68ktg7p
```

Attempt This Online!

* `6 3 3... $#:@36b3igm68ktg7p` Generate all dice patterns from a single base 36 number containing all the bits.
* `(3,~3,2,.,.&2)"2` Add the frame integers.
* `' o|-'{~` Convert to ascii.
* `?@6{` Randomly choose one.

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


title: Merge two values

text:
# Question
Title: Merge two values
You have two values each of which is either `0` representing "unknown", or one of `1,2,3`. Merge them into a single value as follows:

* If both values are nonzero and equal, output that value:
`(3,3) -> 3`
* If both values are nonzero but unequal, output 0 for unknown:
`(1,2) -> 0`
* If one value is zero and the other is not, output the nonzero value:
`(2,0) -> 2, (0,1) -> 1`
* If both values are zero, output zero:
`(0,0) -> 0`

**Test cases:**

There are 16 possible input pairs.

```
  | 0 1 2 3
--+--------
0 | 0 1 2 3
1 | 1 1 0 0
2 | 2 0 2 0
3 | 3 0 0 3

(0, 0) -> 0
(0, 1) -> 1
(0, 2) -> 2
(0, 3) -> 3
(1, 0) -> 1
(1, 1) -> 1
(1, 2) -> 0
(1, 3) -> 0
(2, 0) -> 2
(2, 1) -> 0
(2, 2) -> 2
(2, 3) -> 0
(3, 0) -> 3
(3, 1) -> 0
(3, 2) -> 0
(3, 3) -> 3

```

## Leaderboards

```
var QUESTION_ID=165314,OVERRIDE_USER=8478;function answersUrl(e){return"https://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"https://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
> 24 votes
# Python 3, ~~27~~ 25 bytes

```
lambda x,y:(x|y)>>(x*y&2)

```

Try it online!

# Answer
> 16 votes
# Jelly, 4 bytes

```
gf|S

```

Try it online!

### How it works

```
gf|S  Main link. Left argument: x. Right argument: y.

g     Compute a, the gcd of x and y.
  |   Compute b, the bitwise OR of x and y.
 f    Filter; yield all common elements of [a] and [b].
   S  Take the sum.

```

# Answer
> 10 votes
# APL (Dyalog), 5 bytes

```
⌈×∧=⌊

```

Try it online!

Useful reference

`∧=⌊`: Returns `1` if the lowest common multiple is equal to the minimum. This is only true if one of the values is zero, or both are equal. Alternatively I could have `=*⌊`

`⌈×`: The maximum multiplied by the above.

# Answer
> 8 votes
# Shakespeare Programming Language, 296 bytes

```
Z.Ford,.Ajax,.Act I:.Scene I:.[Enter Ford and Ajax]Ajax:Listen to thy heart.Ford:Listen to thy heart.Am I as fat as you?Ajax:If so,let us Scene C.Am I as fat as zero?If so,let us Scene C.Ford:Am I as fat as zero?If not,you zero.open heart.let us Scene V.Scene C:.Ajax:open heart.Scene V:.[Exeunt]

```

Try it online!

First participation to a code-golf challenge, so let's start with one of my favorite joke languages !

Explanation : Declaration of the two variables Ford and Ajax (shortest variable names available)

```
Z.Ford,.Ajax,.

```

First Scene : Put the two values into the variable, then test them for equality, then test Ajax against 0. If the value that we have to return is stored in the variable Ford, go to Scene C.

```
Act I:.
Scene I:.
[Enter Ford and Ajax]
Ajax:
Listen to thy heart.
Ford:Listen to thy heart.
Am I as fat as you?
Ajax:
If so,let us Scene C.
Am I as fat as zero?
If so,let us Scene C.

```

If Ford is 0, print Ajax, else set Ajax as 0 then print Ajax. Then go to the end of the program.

```
Ford:Am I as fat as zero?
If not,you zero.
open heart.
let us Scene V.

```

Scene C : Print Ford

```
Scene C:.
Ajax:open heart.

```

Scene V: End of the program.

```
Scene V:.
[Exeunt]

```

# Answer
> 6 votes
# Ruby, 21 bytes

```
->a,b{(a|b)*531[a*b]}

```

Try it online!

Because Ruby

# Short explanation:

* `a|b` is bitwse OR, so it gives us the right number if a==b or one of them is zero.
* Magic number `531` is 2^9+2^4+2^1+2^0, and the \[\] operator extracts a single bit. This means: multiply by 1 if a\*b is 0, 1, 2, 4 or 9, multiply by 0 otherwise.
* This won't work for values \> 3

# Answer
> 6 votes
# Haskell, 25 bytes

```
x!y=0^((x-y)^2*x)*y+0^y*x

```

Try it online!

# Answer
> 6 votes
# Pyth, ~~8~~ 7 bytes

```
@{+0SQ3

```

Try it online!

```
@{+0SQ3   Implicit: Q=input()

    SQ    Sort input
  +0      Prepend 0
 {        Deduplicate
@     3    Get 4th element (index 3), modular indexing

```

**Case 1 - Both values nonzero and equal**

```
Sorted Input   [3,3]
Prepend 0      [0,3,3]
Deduplicate    [0,3] - index 3 yields 3

```

**Case 2 - Both values nonzero and unequal**

```
Sorted Input   [1,2]
Prepend 0      [0,1,2]
Deduplicate    [0,1,2] - index 3 yields 0

```

**Case 3 - Exactly one value zero**

```
Sorted Input   [0,1]
Prepend 0      [0,0,1]
Deduplicate    [0,1] - index 3 yields 1

```

**Case 4 - Both values zero**

```
Sorted Input   [0,0]
Prepend 0      [0,0,0]
Deduplicate    [0] - index 3 yields 0

```

---

*Alternate solution, also 7 bytes*

```
*eSQ}s{

```

Try it online

```
*eSQ}s{QQ   Trailing Q's inferred

      {Q    Deduplicate input
     s      Take the sum
    }   Q   Is this in the input? True treated as 1, false as 0
*           Multiplied by
 eSQ        Max from input (end of sorted input)

```

---

*Previous version, 8 bytes*

```
@+0{-QZ3

```

# Answer
> 5 votes
# JavaScript (Node.js), 17 bytes, port somehow from Python answer

```
a=>b=>a*b&2?0:a|b

```

Try it online!

# JavaScript (Node.js), 21 bytes

```
a=>b=>a-b?a*b?0:a+b:a

```

Try it online!

# Answer
> 5 votes
# Java 8, 20 bytes

Curried lambda. Stolen from here.

```
a->b->(a|b)>>(a*b&2)

```

# Answer
> 4 votes
# Stax, 8 bytes

```
Ç∞∟∙◄╥*♣

```

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

```
    e.g.        [2, 0]
c:s [2, 0] 2    calculate the "span" of the input array (max(a) - min(a))
+   [2, 0, 2]   append the span to the input array
o   [0, 2, 2]   sort the 3-element array
E   0 2 2       explode the 3 elements into 3 separate stack entries
a   2 2 0       rotate the third stack element to the top of stack
!   2 2 1       logical not, produces 1 iff the top value was 0
*   2 2         multiply
                implicitly print top of stack

```

Run this one

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

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

```

Try it online!

# Answer
> 4 votes
(first submission so please don't kick too hard)

# Python 2, 57 44 43 bytes

```
lambda a,b:(0 if a*b else a+b)if a-b else a

```

Try it online!

(compressed a bit after looking at first python answer)

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

`f(a,b){a=a^b&&a*b?0:a|b;}`

pseudo-code:

```
foo(A,B)
    if A XOR B and A*B are > 0
        return 0
    else
        return A OR B`

```

# Answer
> 3 votes
# C (gcc), 26 bytes

```
f(a,b){a=a*b?a-b?0:a:a+b;}

```

Try it online!

Expanation / Ungolfed:

```
int f(int a, int b) { // implicit-int (C89)
    // return replaced with assignment: link
    return a*b ? // if a and b are both not zero, then
        a-b ? // if a != b
        0 : // a != b, so return 0
        a // a == b, so return a
    : a+b // one of a,b is zero, so return whichever is nonzero
    ;
}

```

# Answer
> 3 votes
# MATL, 9 bytes

```
dGp*~GX>*

```

Try it online!

### Explanation:

```
           % Implicit input as a vector with two elements implicitly. Stack: [0,2]
d          % The difference between the two elements. Stack: [2]
 G         % Push input again. Stack: [2], [0,2]
  p        % The product of the last element (the input). Stack: [2], [0]
   *       % Multiply the two elements on the stack. Stack: [0]
    ~      % Negate. Stack: [1]
     G     % Push input again. Stack: [1], [0,2]
      X>   % Maximum value. Stack: [1], [2]
        *  % Multiply the two elements on the stack. Stack: [2]
           % Implicit output

```

# Answer
> 3 votes
# GNU sed, 23 bytes

```
s/^0?(.)\1?0?$/\1/
t
c0

```

(must be run with `-r` flag)

Try it online!

# Answer
> 3 votes
# QBasic, 34 bytes

Different approach!

```
INPUT a,b
?(a OR b)*-(a*b=0OR a=b)

```

Observe that the nonzero values in the output grid are all the bitwise `OR` of the two input numbers. This is just `a OR b` in QBasic. We want to output this value when `a*b=0 OR a=b`, and `0` otherwise, which we can do by multiplying by the negative of the aforementioned conditional (negative, since truthy is `-1` in QBasic).

# Answer
> 2 votes
## Batch, ~~38~~ ~~36~~ ~~35~~ 30 bytes

```
@cmd/cset/a"(%1|%2)>>(%1*%2&2)

```

Port of @Dennis's Python answer, as conditionals are too expensive in Batch.

# Answer
> 2 votes
# Swift, 118 bytes

```
func c(n1:Int,n2:Int){n1==n2 ? print("\(n1)") : (n1*n2 != 0 ? print("0") : (n1==0 ? print("\(n2)") : print("\(n1)")))}

```

# Answer
> 2 votes
# brainfuck, 25 bytes

```
,>,[>]<<[[->->+<<]>[>]]>.

```

Input is two byte values (not ascii)

# Answer
> 2 votes
# , 8 7 bytes

1 byte saved by H.PWiz.

```
>.*=^<.

```

Try it online!

A J port of H.PWiz's APL solution

`=` are the numbers equal? (results in 1 or 0)

`^` to the power of

`<.` the smaller number

`*` multiplied by

`>.` the larger number

# Answer
> 2 votes
# 05AB1E, ~~9~~ 8 bytes

```
àIËIP_+*

```

-1 byte thanks to *@MagicOctopusUrn*.

Try it online or verify all test cases.

**Explanation:**

```
à         # Take the maximum of the input-list
          #  [0,2] → 2
IË        # Are all elements in the input-list equal?
          #  [0,2] → 0
  IP_     # Take the product of the input-list, and verify if it equals 0
          # (`_` transforms 0 into 1; everything else into 0)
          #  [0,2] → 0 (product) → 1 (==0)
     +    # Add them together (since only 1 is truthy in 05AB1E, this is basically an OR)
          #  0+1 → 1
*         # Multiply both values on the stack
          #  2*1 → 2

```

**Generalized explanation:**

```
IËIP_+    # If both values are equal, or one of them is a zero:
 à        #  Output the maximum of the two values
          # Else:
          #  Output 0

```

# Answer
> 2 votes
# Python 2, ~~34~~ 28 bytes

```
lambda i,j:(i|j,0)[0<i!=j>0]

```

Try it online!

-6 with thanks to @Dennis

# Answer
> 2 votes
# Brachylog, 10 bytes

```
=h|∋0&⌉|∧0

```

Try it online!

# Answer
> 2 votes
# Javascript ES6, 25 22 21 20 bytes

```
a=>b=>a?b-a?!b*a:a:b

```

**14 13 bytes**, If the arguments are provided in sorted order

```
a=>b=>a%b?0:b

```

# Answer
> 2 votes
# Javascript, 35 bytes

```
f=(m,n)=>(m||n)&&(m!=n)?(m>n?m:n):0

```

# Answer
> 2 votes
# 05AB1E, 6 bytes

```
ê0ýÙ7è

```

Try it online!

Port(ish) of my Pyth answer.

*TIO header/footer taken from Emigna's answer*

# Answer
> 2 votes
# QBasic, ~~38~~ ~~36~~ 35 bytes

```
INPUT a,b
?(a*b>0)*(b-a*(a<>b))+a+b

```

Partly inspired by Erik's `IF ... THEN ... ELSE` answer, here's a math-only solution.

### How I got here

*Important note for understanding math-with-conditionals: in QBasic, the results of comparison operators are `0` and `-1`, not `0` and `1`.*

We start with Erik's code:

```
IF a*b THEN?a*-(a=b)ELSE?a+b

```

In other words, if `a` and `b` are both nonzero, then print `a*-(a=b)` (`a` if `a=b`, otherwise `0`); else (at least one of `a` and `b` is zero), output `a+b` (the nonzero number, or `0` if they're both zero).

There's already some math with conditionals going on here. Let's take it a step farther and see if we can eliminate the `IF` statement entirely. We'll have to use `a*b>0` for the outer condition: `a*b` can have multiple different truthy values, which is fine for `IF` but causes problems for math.

```
c=a*b>0
?c*a*(a=b)+(c+1)*(a+b)

```

This is the standard trick of `IF`-elimination. When `c` is true, `c*a*(a=b)` is `-a*(a=b)` and `(c+1)*(a+b)` is `0`; when `c` is false, `c*a*(a=b)` is `0` and `(c+1)*(a+b)` is `a+b`. So this expression gives the same results as the `IF ... THEN ... ELSE`. The only problem is, it makes our program 40 bytes instead of 38. Maybe we can shorten it by rearranging the math.

```
c=a*b>0
?c*a*(a=b)+c*(a+b)+a+b

```

Still 40 bytes...

```
c=a*b>0
?c*(a+b+a*(a=b))+a+b

```

Now our program is back to 38 bytes. But since we're only using `c` once, we don't have to assign it to a variable anymore:

```
?(a*b>0)*(a+b+a*(a=b))+a+b

```

Now we're down to 36 bytes.

*But wait there's more...* That `a+b+a*(a=b)` expression looks a bit redundant. `a*(a=b)` is `-a` if `a=b` and `0` otherwise. When we add it to `a`, we get `0` if `a=b` and `a` otherwise. Maybe we can achieve the same thing in fewer bytes by reversing the condition.

```
b+a*-(a<>b)

```

At first, this doesn't look shorter. But we can save a byte by subtracting instead of adding a negative:

```
b-a*(a<>b)

```

And there we have our 35-byte solution.

# Answer
> 2 votes
# Shakespeare Programming Language, 187 bytes

```
,.Ajax,.Puck,.Act I:.Scene I:.[Enter Ajax and Puck]Ajax:Listen tothy!Puck:Listen tothy!Be
you nicer zero?If notyou be I.Am I worse a cat?If notam I as big as you?If notyou zero.Open heart

```

Try it online!

# Answer
> 2 votes
# Vyxal, 15 bytes

```
?0⁼?0⁼∨??⁼∨??∴*

```

Try it Online!

Surprisingly no Vyxal answer yet. Return the max, multiplied by the boolean value indicating whether the values are equal or one of them is zero.

---

# Vyxal, 6 bytes

```
s0pU3i

```

Try it Online!

Thanks @lyxal for this version which ports the Pyth answer.

# Answer
> 1 votes
# Japt, ~~12~~ 9 bytes

Takes input as an array of integers.

```
×&2?0:Ur|

```

Try it online!

# Answer
> 1 votes
# Jelly, ~~7~~ 6 bytes

```
×¬o=a»

```

Try it online! or Try all combinations!

**How?**

```
×¬o=a»   Dyadic link
×        Multiply the two arguments.
 ¬       Logical not. Gives 1 if one argument is 0, 1 otherwise.
   =     Are the two arguments equal?
  o      Logical or the result of = and ¬.
     »   Greater of the two arguments.
    a    Logical and. Gives the greater of the two arguments if they are equal
         or if one of them is zero and gives 0 otherwise.

```

Using the method in the APL answer, we get the same byte count. One byte longer than that answer because lowest common multiple is two bytes.

**6 bytes**

```
«=æl×»

```

Try it online!

# Answer
> 1 votes
# Clean, ~~46~~ ~~43~~ 42 bytes

```
import StdEnv
?[a,b]|a<1||a==b=b=0

```

#

```
?o sort

```

Try it online!

Anonymous composition `:: [Int] -> Int`, sorts the pair and then matches off the first member.

Doing it as a composed lambda is the same length:

```
import StdEnv

```

#

```
(\[a,b]|a<1||a==b=b=0)o sort

```

# Answer
> 1 votes
# Python 3, 30 bytes

```
lambda a,b:0==a*b*(a-b)and a|b

```

Try it online!

-5 bytes thanks to Oliver
-1 byte thanks to Jo King

# Answer
> 1 votes
# TI-Basic, 10 bytes

```
max(Ans)not(prod(Ans)ΔList(Ans

```

Multiply maximum value by result of (some element equals zero OR elements are equal)

# Answer
> 1 votes
# C (gcc), 22 bytes

```
f(x,y){x=x*y&2?0:x|y;}

```

Try it online!

# Answer
> 1 votes
# Haskell, 27 bytes

```
a#b=max a b*0^(a*b*(a-b)^2)

```

Try it online!

# Answer
> 1 votes
# Octave, 28 bytes

```
@(a,b)~(a*b*(a~=b))*max(a,b)

```

Try it online!

or

```
@(a,b)(a==b|~(a*b))*max(a,b)

```

Try it online!

---

### Explanation:

The maximum value should be outputted if `a*b=0` or if `a==b`. The function takes `a` and `b` as inputs. It multiplies `a*b`, thus getting a zero if one of them is zero, and checks that `a~=b`, thus getting a zero if the two are equal. We negate both, so that both conditions gives us a truthy value telling us that we should output the maximum value. We then multiply this boolean (`0/1`) by the maximum value, and outputs it.

# Answer
> 1 votes
# 05AB1E, 7 bytes

```
`α*P_*Z

```

Try it online!

**Explanation**

```
`α        # absolute difference of the inputs
  *       # multiplied by the inputs
   P      # product of the result
    _     # logically negated
     *    # multiplied by the inputs
      Z   # max

```

# Answer
> 1 votes
# JavaScript (ES6)

## 27 bytes

A rather long formula, but without any conditional statement.

```
a=>b=>(a|4)*(b|4)*6%61%27&3

```

Try it online!

## 17 bytes

Simply a port of Dennis' method.

```
a=>b=>a*b&2?0:a|b

```

Try it online!

# Answer
> 1 votes
# Elixir, 34 bytes

Pretty simple in a functional programming language, just get the first match. No maths here!

```
fn a,a->a
a,0->a
0,a->a
_,_->0 end

```

Try it online!

# Answer
> 1 votes
# Retina 0.8.2, ~~20~~ 18 bytes

-2 bytes thanks to Martin Ender.

```
(.)\1|0
$1
..|^$
0

```

Try it online!

# Answer
> 1 votes
# , 35 bytes

```
rep(unique(sort(c(0,scan()))),4)[4]

```

Try it online!

Shameless port of Sok's well-explained Pyth answer.

# Answer
> 1 votes
# Befunge-93, 20 bytes

```
&::&*#v_&+.@
@.*!-&<

```

Try it online!

## Explanation

this boils down to:

```
if(A * B = 0) {
    output (A + B)
    end
} else {
    output A * (A = B)
    end
}

```

# Answer
> 1 votes
# Shakespeare Programming Language, ~~216~~ 208 bytes

```
,.Ajax,.Ford,.Act I:.Scene I:.[Enter Ajax and Ford]Ajax:Listen tothy!Ford:Listen tothy!Am I as bad as you?If soyou zero.Is the product ofyou I worse a cat?If soyou be the sum ofyou I.If notyou zero.Open heart

```

Try it online!

As psuedo-code:

```
f(a,b):
  if a==b:
    b=0
  if a*b<1:
    b=a+b
  else:
    b=0
  return b

```

# Answer
> 1 votes
# Befunge-93, 17 bytes

```
&::&-!_&*!\&+*.@.

```

Try it online!

As psuedo-code:

```
f(a,b):
  if a-b==0:
    print(b)
  else:
    print((!(a*b))*(a+b))

```

# Answer
> 1 votes
# Python 2, ~~42~~ 34 bytes

```
lambda a,b:(0in(a,b)or a==b)*(a|b)

```

EDIT: -8 thanks to @TIO and @JonathanAllan

# Answer
> 1 votes
# **JavaScript, 24 Bytes**

```
x=>y=>!x*y|!y*x|(x==y)*x

```

Allows all numbers, no conditional, doesn't require sorted input

# Answer
> 1 votes
# Prolog (SWI), 27 bytes

```
N+N+N.
N+0+N.
0+N+N.
_+_+0.

```

Try it online!

The most naive translation ever.

# Answer
> 1 votes
# Glee, ~~24~~ ~~22~~ 20 bytes

Idea to append zero taken from Sok’s Pyth solution.

`~~=>n,0& *>0\+ >1~ *n\>>~~`

```
=>n,0& *>0\+ <2*n\>>             $$<2 instead of >1~ (not > 1)

```

Explanation:

```
a b=>n,0& *>0\+ <2*n\>>
a b=>n                      3 1     2 2     0 3     0 0     assign a b to n
      ,0                    3 1 0   2 2 0   0 3 3   0 0 0   catenate 0
        &                   0 1 3   0 2     0 3     0       unique elements
          *>0               011     01      01      0       mark all > 0 (boolean)
             \+             2       1       1       0       reduce by addition
                <2          0       1       1       1       result <2 ?
                  *n        0 0     2 2     0 3     0 0     multiply with n
                    \>>     0       2       3       0       largest element

```

Old version

```
=>n--[2]=0|(n\* =0)*n\>>

```

Explanation for a pair of numbers (a b):

```
                              result for a b pairs
                               3 1    2 2    0 3
a b=>n--[2]=0|(n\* =0)*n\>>
a b                            3 1    2 2    0 3   create vector (a b)
   =>n                                             assign vector to n
      --                       0 _2   0 0    0 3   calculate the first difference vector of n (monadic --)
        [2]=0                  0      1      0     result vector at index 2 equal to 0 ? (boolean)
              (n\*             3      4      0     n reduced by multiplication
                   =0)         0      0      1     equal to 0 ? (boolean)
             |                 0      1      1     OR (boolean) (dyadic |)
                      *n       0 0    2 2    0 3   multiplied by n (dyadic *)
                        \>>    0      2      3     largest element (monadic \>>)

```

# Answer
> 1 votes
# QBasic 1.1, 38 bytes

```
INPUT A,B
IF A*B THEN?A*-(A=B)ELSE?A+B

```

-1 thanks to DLosc.

Input is two comma-separated integers.

# Answer
> 0 votes
# Attache, 32 bytes

```
{If[_=_2,_,If[Min!__,0,Max!__]]}

```

Try it online!

Takes input as two arguments, such as `f[0, 1] = 1`.

## Other solutions

## 34 bytes

```
{If[Same!_,_@0,If[Min!_,0,Max!_]]}

```

Try it online! The same as above, but takes input as an array

## 39 bytes

```
{ToBase[47483073034,5][FromBase&4!_]-1}

```

Try it online!

Hardcodes the solution in a base-5 integer. More interesting IMO but longer.

# Answer
> 0 votes
# Pyth, 11 bytes

```
e+Z.-+xFQQ{

```

Try it here

### Explanation

```
e+Z.-+xFQQ{
     +xFQQ      Prepend the XOR of the inputs to the inputs.
   .-     {Q    Remove one copy of the deduplicated (implicit) input.
 +Z             Prepend 0.
e               Take the last.

```

### Alternative solution, 11 bytes

```
e+0.-F{B+xF

```

# Answer
> 0 votes
# Pyth, 10 bytes

```
-iFQ&.AQnF

```

Try it online!

# Answer
> 0 votes
# JavaScript (Node.js), 20 bytes

```
a=>b=>a-b&&a*b?0:a|b

```

Try it online!

# Answer
> 0 votes
# Tcl, 43 bytes

```
proc M a\ b {expr !$a?$b:!$b?$a:$a-$b?0:$a}

```

Try it online!

# Answer
> 0 votes
# C#, ~~48~~27 bytes

```
(x,y)=>x==y?x:(x*y>0?0:x|y)

```

Try it online

Thanks @Charlie for the TIO link & helping trim 21 chars off the code

# Answer
> 0 votes
# Husk, 4 bytes

-1 thanks to H.PWiz.

```
!4uΘ

```

Try it online!

# Answer
> 0 votes
# 12-basic, 36 bytes

```
FUNC M(A,B)?(A or B)*(!A~!B|A==B)END

```

This can probably be shortened.

`~` is bitwise XOR (as well as bitwise NOT when used as a unary operator) (Just like in Lua)

# Answer
> 0 votes
# dc, 28 bytes

```
[pq]sqsidli=qd0rli*0!=qli++p

```

Try it online!

I'll keep mulling over this, it feels like it must be golfable. `[pq]sq` just makes a print & quit macro. `sidli` stores one of our values in the register `i`, duplicates the other value, and then recalls `i`. `=q` consumes two values on the stack, and executes macro `q` if they're equal (so, prints the one value left behind). `d0r` duplicates the value on the stack again, and then puts a `0` on the stack in between them. `li*0!=` loads `i`, multiplies the two values, and runs `q` to print the `0` that we left on the stack if the two values were not equal. If none of these things has happened yet, we `li` to load `i`, and we now have three values on the stack - two zeroes and our one non-zero value. `++` add the three together, and `p`rint.

# Answer
> 0 votes
# Perl 5 `-p`, 25 bytes

```
/ /;$_=($'|$`)>>($'*$`&2)

```

Try it online!

Steals the method from @Dennis's Python answer.

# Answer
> 0 votes
# **PHP - 52 bytes**

```
<?=($a=$argv[1])==($b=$argv[2])?$a:($a*$b?0:$a|$b);

```

Try it online!

Explanation:

```
$a==$b  Check for equality, display first value if equal
$a*$b   If multiplication equates to non-zero, display 0 (Unknown) else...
$a|$b   Display the non-zero value.

```

# Answer
> 0 votes
# PHP, ~~42~~ 40 bytes

```
[,$a,$b]=$argv;echo$a*$b&&$a-$b?0:$a|$b;

```

Run with `php -r '<code>' <a> <b>` or Try it online.

**breakdown**

```
[,$a,$b]=$argv; // import input
echo
    $a*$b       // if both not 0
    &&$a-$b     // and unequal
        ?0      // then print 0
        :$a|$b  // else print the non-zero value, if there is one
;

```

# Answer
> 0 votes
# Q'Nial7, 40 bytes

```
n is OP A B{2>sum(cull A B 0>0)*max A B}

n is OP A B{                           }    operation n with parameters A B (pair of numbers)
                       A B 0                append 0 to pair of numbers
                  cull                      create list of unique elements
                            >0              create booleans of elements that are > 0
              sum(            )             sum up the booleans
            2>                              sum > 2 ? (boolean)
                               *max A B     multiply boolean with max of A B

```

result:

```
     n 0 3
3
     n 1 2
0
     n 2 2
2
     n 0 0
0

```

---
Tags: code-golf
---


title: The Missing Match

text:
# Question
Title: The Missing Match
You are given a string of unknown length that contains a varied amount of `(`, `{`, `[` and their respective closing parentheses (in this context all referred to as *brackets*).

With one exception, all the brackets are all balanced, meaning an opening one has a corresponding closing one somewhere afterwards in the string.
The brackets *may not be* "interpolated" with each other, i.e. opening bracket **b** which is inside opening bracket **a** must close *before* bracket **a** closes, so `([)]`, `{[(]})`, and `({[(])}())[()]` are invalid, but `([])`, `{[()]}`, and `({[()]})()[()]` are valid.

### Challenge

The task is, inside the string there is a single unbalanced bracket, i.e. an opening bracket that does not have a closing one. You must insert the closing bracket where it is the **farthest distance apart** from the opening bracket, but not interpolated with other brackets, then return the modified (or new) string.

### Test cases

`^` added to point out where a bracket was added.

```
"("                        --> "(**)**"
                                 ^
"[(]"                      --> "[(**)**]"
                                  ^
"{[({}()([[[{}]]])]{[]}}"  --> "{[({}()([[[{}]]])**)**]{[]}}"
                                                 ^
"[[[]]"                    --> "[[[]]**]**"
                                     ^
"{[[]([(()){[[{}]()]})]}"  --> "{[[]([(()){[[{}]()]}**]**)]}"
                                                    ^

```

### Scoring

This is , so shortest code wins.

##### Difference from "possible dupes":

1. This one only wants to see if the brackets are matched; nothing else
2. Quite similar, but in that question is the possibility that one must add multiple braces, which I would approach quite differently in answering

# Answer
# Python 3, 185 167 154 bytes

This is probably more golfable, but I figured I'd try a more logical approach than the brute force attempts of the other answers:

```
def M(a):
 *u,b,f="",lambda s:s.translate(")] } "*25)
 for x in a:
  if x in"([{":u+=x,
  elif x!=f(y:=u.pop()):b+=f(y);*u,_=u
  b+=x
 return b+f(str(*u))

```

Edit -18 bytes: saved some space with a for loop, and found a better solution to adding a potential missing closing bracket to the end of the string than the `if` I was using. (Bonus: this code can be made to work for an arbitrary number of unclosed brackets, at a cost of only +8 bytes, by changing `b+=f(str(*u))` to `while u:b+=f(u.pop()`)

Edit -13 bytes: all thanks to some clever golfs by @ovs

Try it online!

### Ungolfed code + Explanation

Instead of brute force checking each combination, this program loops through the string, and wherever it finds a closing bracket that doesn't match the last unclosed opening bracket, it adds the missing closing bracket.

```
def M(a):
    u=[] ## List being used as a stack holding the unmatched brackets
    b="" ## Result string that gets built up
    f=lambda s:s.translate(")] } "*25) ## Lambda that swaps each opening bracket for its closing version
    for x in a: ## loop through the characters in the input
        if x in "([{": ## "pop" the first char to x, check if its an opening bracket
            u.append(x) ## if so, just push it onto the list of unmatched brackets
        elif x!=f(y:=u.pop()): ## if its a closing bracket, check if it matches the most recently opened bracket
            b+=f(y) ## if it doesn't, add the bracket that would close that one
            u.pop() ## and then pop the bracket x actually closes
        b+=x ## stick this loops x onto the output
        a=a[1:] ## because you cant .pop() a str in python, we dont actually remove the first char until here
    b+=f(str(*u)) ## if theres anything left unclosed, flip it and stick it on the end
    return b

```
> 5 votes

# Answer
# x86-64 machine code, ~~26~~ 24 bytes

```
AA 04 01 0D 01 C3 31 C0 50 AC A8 0B 7B F2 59 88 0F AE 75 FA E3 EF EB F1

```

Try it online!

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as a null-terminated byte string; and the address of the input, as a null-terminated byte string, in RSI. The starting point is after the first 6 bytes.

-2 with some overlapping of instructions.

Note the binary representations of the brackets' ASCII codes:

```
( 00101000
) 00101001
[ 01011011
] 01011101
{ 01111011
} 01111101

```

In assembly:

```
o:  stosb       # (For left brackets) Add AL to the output string, advancing the pointer.
    add al, 1   # Add 1 to AL.
    .byte 0x0D, 0x01    # These two bytes combine with the next two instructions
                        #  to produce 'or eax, 0xC031C301'.
                        # The effect on AL (which is the low byte of EAX) is
                        #  to set its low bit to 1.
                        # This produces the corresponding right bracket.
e:  ret     # Return.
f:  xor eax, eax            # (Start here) Set RAX to 0.
    push rax        # Push RAX onto the stack.
s:  lodsb           # Load a byte from the input string into AL, advancing the pointer.
    test al, 0x0B   # Set flags from its bitwise AND with binary 1011.
    jpo o           # Jump if that has an odd number of 1 bits -- true for left brackets.
c:  pop rcx         # (For right brackets and 0) Pop from the stack into RCX.
                    # The low byte is the expected character for balanced brackets.
    mov [rdi], cl   # Add that byte to the output string.
    scasb           # Compare that byte with AL, advancing the pointer.
    jne c           # Jump back if they are not equal, to continue popping.
    jrcxz e         # Jump, to return, if RCX is 0.
    jmp s           # Jump back to process the next byte.

```
> 4 votes

# Answer
# Jelly,  ~~33~~  22 bytes

```
;⁶ȧ®ṪOịʋ;ɼȧ$e?€“] } )”

```

A monadic Link that accepts a list of characters (from `(){}[]`) and yields a list of characters (with one of `)}}` inserted/appended),

**Try it online!**

### How?

Forms a string by keeping open *brackets* and closing the last, as yet unclosed, open *bracket* when a close *bracket* (or the end of the string) is encountered.

```
;⁶ȧ®ṪOịʋ;ɼȧ$e?€“] } )” - Link: list of (){}[] characters, A:
;⁶                     - concatenate a space
                          - will be identified as a closing bracket later
               “] } )” - set the right argument to "] } )"
              €        - for each in the augmented A:
             ?         -   if...
            e          -   ...condition: exists in "] } )"?
       ʋ               -   ...then: last four links as a dyad:
  ȧ®                   -     logical AND with the register
    Ṫ                  -     tail (last, as yet unclosed opening bracket)
     O                 -     ordinal
      ị                -     index into "] } )" (1-indexed & modular)
                              - gives the matching closing bracket
           $           -   ...else: last two links as a monad:
         ɼ             -         apply to register (initially 0)
        ;              -         concatenate
          ȧ            -         logical AND (to get back the single bracket)

```
> 3 votes

# Answer
# , 80 bytes

```
[:;@({~a:i:~<@(rplc&(,_2;&''\'()[]{}')^:_)@;"1)[:,/')}]';&.(1&|.)"0 1/<\,.<@}.\.

```

Try it online!

Simple approach:

* Construct every possible solution:
    + Insert each of `)`, `]`, and `}` into every possible position.
    + This turns out to be verbose because J lacks an "insert at" verb.
* For each candidate solution, repeatedly reduce it by replacing `()`, `[]`, and `{}` with the empty string.
    + Valid solutions will have reduced to the empty string.
* Of the valid solutions, pick the one whose insertion point was farthest to the right.
> 3 votes

# Answer
# Python 3, 167 bytes

## Golfed Code

```
def f(s):
 S="";B="a"
 for c in s+B:
  if c in"({[":S+=c;B+=c
  elif abs(ord(c)-(b:=ord(B[-1])))>2:B=B[:-2];S+=chr(b+(1,2)[b>40])+c
  else:B=B[:-1];S+=c
 return S[:-1]

```

Try it online! Note that TIO has an old version of Python which doesn't allow assignment expressions, so the linked code is slightly longer than the real code.

## Explanation

Similar to the other python answer in its basic approach - instead of brute forcing, it loops through the string, adding in the missing bracket when it finds a closing bracket that does not match the last unclosed opening bracket. However, the code is quite different.

* `def f(s)`: Defines a function that accepts a parameter `s`, which will be the input string.
* `S="";B="a"`: Creates two variables `S` and `B`. `S` is the new string with the extra bracket inserted, which gets added to in the `for` loop. `B` is a string to store unclosed opening brackets.

An extra character gets added to `B` (I chose `"a"` but it could be anything) because an extra run of the loop must be done to check if there is an unclosed bracket at the end of the string, and this would cause an error if `B` were empty.
* `for c in s+B`: Loops through the characters in the input string.

An extra character is added to the end of the string so that an extra run of the loop is done at the end. This is to check if there is still an unclosed bracket at the end of the string. Since `B` is currently equal to a string with one character, `s+B` can be used instead of e.g. `s+"a"`, saving two bytes.
* `if c in"({[":S+=c;B+=c`: If the current character is an opening bracket, adds it to both `S` (the new string), and `B` (the string of unclosed opening brackets).
* `elif abs(ord(c)-(b:=ord(B[-1])))>2:B=B[:-2];S+=chr(b+(1,2)[b>40])+c`: Only gets run if the current character is not an opening bracket (in which case it is of course a closing bracket).

`abs(ord(c)-(b:=ord(B[-1]))>2)` is `True` if the closing bracket does not correspond to the last unclosed opening bracket. This is because the ASCII codes of closing brackets are always either 1 or 2 larger than those of their corresponding opening brackets (`ord("(")==40`, `ord(")")==41`, `ord("[")==91`, `ord("]")==93`, `ord("{")==123`, `ord("}")==125`).

The `b:=` also assigns the ASCII code of the last unclosed opening bracket to a variable `b`, used later in the line to determine which closing bracket should be added. This is the bit TIO complains about, because it was only added in Python 3.8.

`B=B[:-2]` removes the last two characters of `B` (the list of unclosed opening brackets).

`S+=chr(b+(1,2)[b>40])+c` adds the missing closing bracket, and then the current character, to `S` (the new string). This once again uses the ASCII codes of the brackets.
* `else:B=B[:-1];S+=c`: Only runs if the character is a closing bracket, and it matches the last unclosed opening bracket. `B=B[:-1]` removes the last character from the `B`; `S+=c` adds the character to the new string.
* `return S[:-1]`: Returns the new string. Due to the extra run of the loop, it will have an extra character at the end. The `[:-1]` removes this character.
> 3 votes

# Answer
# Retina 0.8.2, 101 bytes

```
+T`()[]{}`d`\(\d*\)|\[\d*]|{\d*}
\(\d*(?=]|}|$)
$&)
\[\d*(?=\)|}|$)
$&]
{\d*(?=\)|]|$)
$&}
T`d`()[]{}

```

Try it online! Link includes test cases. Explanation:

```
+T`()[]{}`d`\(\d*\)|\[\d*]|{\d*}

```

Repeatedly substitute matched brackets with digits, where matched brackets are either `()`, `[]`, `{}`, or any of the three pairs separated by an arbitrary number of digits, e.g. `[()]` would be substituted twice, first to `[01]`, then to `2013`.

```
\(\d*(?=]|}|$)
$&)
\[\d*(?=\)|}|$)
$&]
{\d*(?=\)|]|$)
$&}

```

Find an unmatched bracket and insert its match.

```
T`d`()[]{}

```

Substitute matched brackets back from their digits.
> 2 votes

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


title: Fix the Braces, etc

text:
# Question
Title: Fix the Braces, etc
Your mission, should you choose to accept it, is to **add** the **minimum** number of parentheses, braces, and brackets to make a given string (containing only parentheses, braces, and brackets) have correct brace matching. **Ties of symbols added** must be broken by having the **maximum** distance between paired braces. You must return only one correct answer that matches these two rules; Further ties, should they exist, may be broken any way you see fit.

Examples:

```
input      output
                          // Empty String is a legal input
[          []             // Boring example
[()]       [()]           // Do nothing if there's nothing to be done
({{        ({{}})         // NOT (){}{} (0 + 0 + 0). Maximum distance is 4 + 2 + 0, ({{}})
[([{])]}   {[([{}])]}     // NOT [([])]{[([])]} or similar

```

You may write a program or function, receives the input via STDIN as a string argument to your function, which returns the output as a string or prints it to STDOUT (or closest alternative). You may optionally include a single trailing newline in the output.

You may assume the input string consists only of the following 6 characters (or lack thereof): `[](){}` (You do not need to support `<>`)

This is , shortest program wins. Standard loopholes are banned, of course.

# Answer
> 2 votes
# Python 3, 211 207 198 bytes

After some work on this variation of this question (matching the brackets given exactly 1 unclosed opening bracket, with no possible unopened closing brackets), I realized that my answer to that could be adapted to this problem (which was linked as a possible duplicate).

```
f=lambda s:s[::-1].translate(" ] [)(} {"*14)
def m(a):
 *u,b="",
 for x in a:
  if x in"([{":u+=x
  elif u and x!=f(y:=u.pop()):b+=f(y);*u,_=u
  b+=x
 return b+f("".join(u))
M=lambda a:f(m(f(m(a))))

```

Edit -4 bytes: inspired by some golfs on my answer on the other post by @ovs

Edit -9 bytes: We have tied the old python2 answer here!! I knew there had to be some way to golf the closing of any trailing unclosed brackets onto the return statement, and after trying a lot of nonsense involving `map()` I realized that if I just `.join(u)` with the empty string, I can reverse it with `f()` at the same time as flipping the brackets

Try it online!

### Explanation and ungolfed code:

This answer takes my answer to the other problem, which loops through a string and adds a missing closing bracket to properly match an unclosed opening bracket, adapts it slightly to ensure it works for multiple unclosed brackets, and then applies it to the string twice, flipping the string in-between.

```
f=lambda s:s[::-1].translate(" ] [)(} {"*14) ## lambda that flips a string, and reverses all the brackets in it
def m(a): ## function that takes a string and matches every unclosed opening bracket (ignores unopened closing brackets)
    u=[] ## list holding all currently unclosed brackets
    b="" ## string that the result is build in
    for x in a: ## loop through the input
        if x in"([{": ## if its an opening bracket
            u+=[x] ## add it to the unclosed list
        elif u and x!=f(y:=u.pop()): ## if there are unclosed brackets and this bracket doesnt close the last opened one
            b+=f(y); ## add the necessary closing bracket
            u.pop() ## pop the extra opening bracket that x closes
        b+=x ## no matter what, add this character to the result
    return b+f("".join(u)) ## join the remaining unclosed brackets into a single string, flip it with f(), and add it to the result
M=lambda a:f( ## Flip the final string back to the correct order
         m(f( ## Flip the string and apply m again to match the unopened closing brackets
         m(a)))) ## Apply the above function to the result to match all unclosed opening brackets

```

# Answer
> 1 votes
# Haskell, 513

The function `h`. Previous version did not give correct answers for `"({{)["` and `"({{)}}"`

```
import Control.Monad

m '('=')'
m '['=']'
m '{'='}'
m ')'='('
m ']'='['
m '}'='{'

data B=B Char[B]|N[B]|Z B Char[B]
instance Eq B where(==)a b=q a==q b
instance Ord B where(<=)a b=q a<=q b

w(B o s)=o:(s>>=w)++[m o]
v(N k)=k>>=w
n(B _ k)=(sum$n<$>k)+1
q(N k)=sum$n<$>k

u(Z(Z g pc pk) c k)=Z g pc(pk++[B c k])
u(Z(N pk) c k)=N(pk++[B c k])
t(N k)=N k
t z=t$u z

f z c|elem c "([{"=[Z z c[]]
f z@(Z p o k) c|m c==o=[u z]|2>1=(u$Z(Z p o [])(m c)k):f(u z)c
f (N k)c=[Z(N[])(m c)k]

h s=v.minimum$t<$>foldM f(N [])s

```

# Answer
> 1 votes
# Python 2 - 198

I was hoping to get some of the comprehensions down a bit more but don't have a lot of time right now to really test different ways of doing things.

```
s="()[]{}";f=s.find
def F(S):
 r=m=""
 for c in S:
    i=f(c)^1
    if i%2:m=c+m;r+=c
    else:
     for d in m:
        if d==s[i]:break
        r+=s[f(d)^1]
     else:r=s[i]+r+c
     m=m[1:]
 for c in m:r+=s[f(c)^1]
 return r

```

The OP did not include an example like `{[([{}])]}{[` (with adjacent groups), but whether or not this functionality is required this outputs the correct `{[([{}])]}{[]}`

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