title: Color count, sorted by occurences

text:
# Question
Title: Color count, sorted by occurences
This one is simple to describe and I could hardly believe that this was not golfed before:

For a given image (whatever format is supported by your language), find the unique colors and output a list of the colors.

* Print the color code in hex RGB, that is a hash sign `#` followed by 2 digits for R, 2 digits for G and 2 digits for B. (`#xxxxxx` where x can be 0-9, A-F and/or a-f).
* The hex code shall be followed by a space  and the decimal pixel count, then a newline (`\n` or `\r\n`).
* The list shall be sorted by count descending (most frequent color at the top).
* If there's a tie (two colors with the same amount), the order is not important.
* The image will not contain transparency, so any alpha value is not important. The alpha value may not be part of the output.
* An image size of 4000x3000 must be supported (that may matter to type definitions)

Sample image "10red 20blue 30black 40white":

Expected output:

```
#FFFFFF 40
#000000 30
#0000FF 20
#FF0000 10

```

Sample image "blue gradient":

One of the expected outputs (since the order of same colors may vary):

```
#718DFF 19
#5571FF 15
#3855FF 11
#8DAAFF 11
#1C38FF 7
#AAAAFF 7
#8D8DFF 6
#AAC6FF 6
#C6C6FF 5
#C6E2FF 4
#001CFF 3
#E2E2FF 3
#FFFFFF 3

```

Sample image "testImage", kindly provided by @Luis Mendo:

Expected output:

```
#FFFFFF 18042
#000000 1754
#FF3300 204

```

Similar to this question, but the output is text, not an image.

# Answer
## PowerShell v2+, 187 bytes

```
$a=New-Object System.Drawing.Bitmap $args[0]
$b=@{}
0..($a.Height-1)|%{$h=$_;0..($a.Width-1)|%{$b["#"+-join($a.GetPixel($_,$h).Name[2..7])]++}}
$b.GetEnumerator()|Sort value -des|FT -h -a

```

Re-uses almost all of the code from my answer on Get the most dominant color. So, please reference that for full explanation.

The changes here are in indexing `$b` in the third line to match the explicit output format requirements, and in the last line we `sort` by `value` in `-des`cending order, then pipe to `Format-Table` with `-H`ideTableHeaders and `-A`utoSize as parameters. It's very rare to actually use `FT` here on PPCG, since output is implicit at the end of execution, but here it's very useful to ensure we get only the correct parts output.

### Examples

The first is the "red" test image from the Dominant Color challenge, the second is the "testimage" from this challenge.

```
PS C:\Tools\Scripts\golfing> .\color-count.ps1 C:\Tools\Scripts\golfing\img\red.png

#ff0000 139876
#dcd9cf 3056
#f2f1ed 1512
#ffffff 1508
#ffe6e6 1488
#ffe3e3 8
#eae8e2 4
#fffbfb 4

PS C:\Tools\Scripts\golfing> .\color-count.ps1 C:\Tools\Scripts\golfing\img\z07VA.gif

#ffffff 18042
#000000 1754
#ff3300 204

```
> 3 votes

# Answer
# Bash + coreutils, 54

* 7 bytes saved thanks to @manatwork

```
grep -oE '#\w+'|sort|uniq -c|sort -nr|awk '$0=$2" "$1'

```

This assumes STDIN input of Imagemagick's .txt format.

Ideone.

---

If the above input format is too much of a stretch, then we can add Imagemagick conversion from any format:

# Bash + coreutils + Imagemagick, 71

```
convert $1 txt:-|grep -oE '#\w+'|sort|uniq -c|sort -nr|awk '$0=$2" "$1'

```

Here, the input image filename is passed in as a command-line parameter.
> 5 votes

# Answer
# Mathematica, 91 bytes

```
StringRiffle@SortBy[Tally["#"<>IntegerString[#,16,2]&/@Join@@#~ImageData~"Byte"],-Last@#&]&

```

Uses a completely different method from @DavidC's answer. Unlike that one, this can support images with any size and color count. Explanation:

```
#~ImageData~"Byte"                   Take the RGB values of the image...
Join@@(...)                          Flatten to a list of colors...
"#"<>IntegerString[#,16,2]&/@(...)   Convert each color to #012def format...
Tally[(...)]                         Convert to a list of {color, multiplicity}
                                      pairs (this does most of the work)...
SortBy[(...),-Last@#&]               Order by the multiplicity descending...
StringRiffle@(...)                   And create a string with the desired format.

```
> 4 votes

# Answer
# JavaScript (ES6), ~~359~~ 355 bytes

### Saved 4 bytes thanks to @Neil

```
u=>{i=new Image;i.src=u;e=document.createElement`canvas`;c=e.getContext`2d`;i.onload=_=>{w=e.width=i.width;h=e.height=i.height;c.drawImage(i,0,0);d=c.getImageData(0,0,w,h).data;for(o={},i=0;i<d.length;i+=4)++o[s='#'+`00000${(d[i]<<16|d[i+1]<<8|d[i+2]).toString(16)} `.slice(-7)]?0:o[s]=1;Object.keys(o).sort((a,b)=>o[b]-o[a]).map(c=>console.log(c+o[c]))}}

```

## Demo

```
f=u=>{i=new Image;i.crossOrigin='';i.src=u;e=document.createElement`canvas`;c=e.getContext`2d`;i.onload=_=>{w=e.width=i.width;h=e.height=i.height;c.drawImage(i,0,0);d=c.getImageData(0,0,w,h).data;for(o={},i=0;i<d.length;i+=4)++o[s='#'+`00000${(d[i]<<16|d[i+1]<<8|d[i+2]).toString(16)} `.slice(-7)]?0:o[s]=1;Object.keys(o).sort((a,b)=>o[b]-o[a]).map(c=>console.log(c+o[c]))}}
f('http://i.imgur.com/acPudA9.gif')
```

```
<input value="https://i.imgur.com/acPudA9.gif" onchange="console.log('-------');f(this.value)">
```

Other test cases I uploaded to imgur to support CORS:

The specific color data on these two seems to have altered slightly when uploading for some reason but it still prints the same amount of occurrences for those two test cases.
> 3 votes

# Answer
# Pyth, 29 bytes

```
jmj;_d_SrSm+\#.[\06.Hid256'Q8

```

Try it online!

(The online interpreter cannot read image, so I stripped of that part and inputted the result of reading that image, which is a list of color triplets. The part responsible for reading the image is `'`, a single colon.)

Proof of functionality of `'` a single colon
> 2 votes

# Answer
# Mathematica ~~103~~ 92 bytes

```
{"#"<>IntegerString[255Round[List@@#],16,2],#2}&@@@DominantColors[#,9999,{"Color","Count"}]&

```

---

## Example

---

## Explanation

`DominantColors` normally returns a list of colors and counts representing the main clusters in a picture. When the number of colors requested exceeds the number of colors in the image, the exact pixel colors are returned. (I am assuming that fewer than 10 000 colors will be in the input image.)

---

`{"#"<>IntegerString[255Round[List@@#],16,2],#2}` converts the base 10 color values with hexadecimal values.

---

Note: there are only 5 colors in the mandrill image. (I used `ColorQuantize[<image>,5]` to reduce the number of colors in the standard mandrill image.)
> 2 votes

# Answer
# Java (1.4+), ~~483~~ 428 bytes

```
import java.util.*;class I {public static void main(String[] a) throws Exception {java.awt.image.BufferedImage i = javax.imageio.ImageIO.read(new java.io.File(a[0]));Map m=new HashMap();String s;for(Integer x=0,y=0,c;y<i.getHeight();y++)for(x=0;x<i.getWidth();m.put(s=x.toHexString(((c=i.getRGB(x++,y))&0xff0000)>>16)+x.toHexString((c & 0xff00)>>8)+x.toHexString(c&0xff),m.get(s)==null?1:(int)m.get(s)+1));System.out.print(m);}}

```

~~Try it online!~~ (Doesn't work online)

---

Ungolfed:

```
import java.util.*;

class I {
    public static void main(String[] a) throws Exception {
        java.awt.image.BufferedImage i = javax.imageio.ImageIO
                .read(new java.io.File(a[0]));
        Map m = new HashMap();
        String s;
        for (Integer x = 0, y = 0, c; y < i.getHeight(); y++)
            for (x = 0; x < i.getWidth(); m
                    .put(s = x.toHexString(((c = i.getRGB(x++, y)) & 0xff0000) >> 16)
                            + x.toHexString((c & 0xff00) >> 8)
                            + x.toHexString(c & 0xff), m.get(s) == null ? 1
                            : (int) m.get(s) + 1))
                ;
        System.out.print(m);
    }
}

```

---

The `toString()` of map outputs like this:

```
{7c7c7c=6, 1d57a5=20468, 121212=7, d3d3d3=3, bdbdbd=9, 949494=2, 333=14, 626262=3, cacaca=2, 141414=5, fff=11, c9c9c9=1, e8e8e8=1, 919191=4, 161616=5, c2c2c2=1, 646464=7, 979797=12, fafafa=2, 808080=1, 7b7b7b=1, 484848=4, b9b9b9=2, f1f1f1=2, 6b6b6b=6, 363636=15, 262626=4, d8d8d8=2, 868686=4, 757575=1, 575757=3, a7a7a7=2, cecece=2, dcdcdc=2, c3c3c3=2, 1d1d1d=5, 727272=9, 656565=2, 3a3a3a=3, 7d7d7d=10, 393939=5, 797979=3, 222=31, 8f8f8f=2, 454545=4, 181818=9, 2e2e2e=2, 222222=1, 1c1c1c=19, b8b8b8=2, e1e1e1=5, 232323=5, 8a8a8a=3, 959595=7, 6a6a6a=9, 434343=7, 5c5c5c=3, 111=20, 909090=3, 424242=4, 212121=1, 1a1a1a=6, 202020=7, efefef=1, 565656=5, 6e6e6e=7, 767676=3, 323232=2, eee=5, 444=18, 2c62ab=1, 717171=2, b1b1b1=3, 6c6c6c=3, 545454=7, 515151=17, 2f2f2f=2, 4a4a4a=3, 888888=6, 6d6d6d=3, 898989=3, a3a3a3=5, 7e7e7e=9, ddd=9, b6b6b6=3, 2b2b2b=5, 313131=5, 8d8d8d=1, a2a2a2=2, 696969=3, a5a5a5=3, 4f4f4f=5, 828282=7, 191919=5, 606060=4, 6f6f6f=4, 8b8b8b=3, ebebeb=2, 555=19, 929292=3, 131313=11, 999999=5, d2d2d2=2, 444444=9, 474747=4, dddddd=1, 585858=8, 5a5a5a=3, 000=9887, afafaf=2, dfdfdf=3, 747474=3, 666666=4, a1a1a1=4, 2a2a2a=11, 4d4d4d=6, 818181=2, 878787=5, 215aa6=1, d9d9d9=4, b5b5b5=3, b4b4b4=3, 737373=4, aeaeae=3, bbb=15, 242424=4, 2d2d2d=8, 888=19, c1c1c1=1, 494949=9, dbdbdb=5, ccc=19, 5d5d5d=3, 5f5f5f=1, 414141=6, c8c8c8=3, aaa=16, 1e1e1e=3, 707070=2, 9e9e9e=2, 373737=7, 9d9d9d=2, 1b1b1b=4, 303030=7, 535353=10, 595959=2, 8e8e8e=3, 383838=5, 939393=18, 616161=2, 686868=6, dadada=1, e3e3e3=2, 5b5b5b=3, a4a4a4=5, 8c8c8c=5, a6a6a6=11, 292929=6, 4c4c4c=3, 151515=6, fefefe=2, 787878=2, 505050=2, e2e2e2=1, 1f1f1f=9, adadad=2, ababab=1, 5e5e5e=6, 252525=4, 4e4e4e=3, 282828=7, a8a8a8=4, 9c9c9c=3, aaaaaa=1, 101010=5, b7b7b7=2, 969696=6, 7f7f7f=4, 555555=2, a9a9a9=5, 343434=8, 999=17, 777777=3, ffffff=76669, f0f0f0=4, bbbbbb=1, 1e58a5=1, b3b3b3=4, 777=20, 636363=2, d4d4d4=1, 2c2c2c=5, 848484=1, 3c3c3c=3, bfbfbf=2, 3e3e3e=9, 333333=4, 7a7a7a=3, 858585=4, 4b4b4b=3, 272727=7, 111111=6, 666=13, 9b9b9b=1, bcbcbc=4, cfcfcf=2, 9a9a9a=1, 404040=21, 525252=3, 989898=4, 171717=5, 3b3b3b=2, c4c4c4=1, 3f3f3f=7, 464646=1, cdcdcd=2, b2b2b2=33, c5c5c5=2, bababa=2}

```

---

Please don't post 1.8 specific golfs suggestions, unless it works in older Java, me no want.

**Example:** Lambdas don't work in more versions of Java than they do work in.
> 1 votes

# Answer
# Tcl/Tk, 134 bytes

```
console s
lmap s [concat {*}[[image c photo -fi $argv] d]] {dict inc D $s}
dict fo k\ v [lsort -int -s 2 -inde 1 -de $D] {puts $k\ $v}

```

`d` is for `data`.

~~Tcl/Tk, 232 bytes
```
console s
set I [image c photo -fi $argv]
set i 0
time {set j 0
time {dict inc D #[join [lmap s [$I g $i $j] {format %02X $s}] ""]
incr j} [image h $I]
incr i} [image w $I]
dict fo k\ v [lsort -int -s 2 -inde 1 -de $D] {puts $k\ $v}

```~~

##

`wish sort_pix.tcl QTE4O.png`

---

`wish sort_pix.tcl 5s1Ob.png`

---

`wish sort_pix.tcl z07VA.gif`
> 1 votes

# Answer
# Brain-Flak, 1110 bytes

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

```

Try it online!

Well that was an adventure. Turns out, Brain-Flak is not very good at image processing. Who knew?

I'll start off by noting that this technically doesn't meet the strict output format requested. If you want that enforced let me know and I'll try to add translation code. For now it outputs decimal numbers: each 4 numbers represents a color in the order RED GREEN BLUE COUNT.

Next up, input. Allowed input formats were more flexible so I used the format easiest for Brain-Flak to parse (that I could find): Netpbm P6. Unfortunately, Brain-Flak could not parse decimal numbers from the P3 format because all Netpbm images start with the character `P` and Brain-Flak can't handle decimal input from files containing non-numeral characters. So P6 was used instead, because P6 stores color information as bytes, which are treated as numbers in ASCII input mode. There remained a challenge because the header information was *not* encoded usefully, but fortunately I didn't need any of that information so it is just discarded. This program doesn't fully adhere to the Netpbm standard because it does not allow newlines within the header, but newlines are not *required* by the standard so the inputs are valid Netpbm files.

Last caveat, the version on TIO is actually not correctly configured for "official" operation because (to my knowledge) I can't supply files as input on TIO, nor could I supply bytes corresponding to unprintable ASCII in the direct input. For official operation the `-a` flag is needed to take input as raw bytes and `-f` to take input from a file. The sample input on the TIO link was instead manually translated from the example on the Netpbm wiki page.

Additionally, I'd like to thank the Brain-Flak wiki for providing helpful snippets of code to work from. In particular, the Bubble-Sort implementation here was instrumental to the final step once I had gotten a count for every color, since I didn't really have any idea where to start otherwise. It took heavy modification, but I'm glad I didn't have to start from scratch.

Here is the ungolfed and commented version of the code. Brain-Flak is a bit too verbose to include a usefully formatted explanation right in this post, but the ungolfed version on TIO contains everything I would include in one with better formatting than I could manage here, so if you're interested please take a look.

There may be golfing yet to do, my previous Brain-Flak answer went through a lot of revisions, but hopefully the lessons learned there gave this a better starting point.
> 1 votes

# Answer
# Python 2, 186 bytes

```
import Image
I=Image.open(input()).convert('RGB')
w,h=I.size
r=['#'+('%0.2X'*3)%I.getpixel((i%w,i/h))for i in range(w*h)]
for a,b in sorted(set((r.count(v),v)for v in r))[::-1]:print b,a

```

Try it online!

Disclaimer: Presented outputs are one-liners for readability. Code outputs result with space and line separation as requested by challenge.

Output for 10red 20blue 30black 40white:

```
[('#FFFFFF', 40), ('#000000', 30), ('#0000FF', 20), ('#FF0000', 10)]

```

Ouput for blue gradient:

```
[('#718DFF', 19), ('#5571FF', 15), ('#8DAAFF', 11), ('#3855FF', 11), ('#AAAAFF', 7), ('#1C38FF', 7), ('#AAC6FF', 6), ('#8D8DFF', 6), ('#C6C6FF', 5), ('#C6E2FF', 4), ('#FFFFFF', 3), ('#E2E2FF', 3), ('#001CFF', 3)]

```

Output for test image

```
[('#FFFFFF', 18042), ('#000000', 1754), ('#FF3300', 204)]

```

Explanation:

```
w,h=I.size # field size stores tuple of values of width and height of image

I.getpixel((i%w,i/h)) # returns tuple of base10 RGB values

('%0.2X'*3) # format string to convert int into hex

set((r.count(v),v)for v in r) # generate set of unique pairs count-color

sorted(set(...))[::-1] # apply sorted(), as it sorts set of tuples by firts elements and reverse sort

print b,a  # swap values in tuples and print

```
> 0 votes

# Answer
# SmileBASIC, 165 bytes

```
DEF C A
L=LEN(A)DIM C[L],N[L]FOR J=0TO L-1FOR I=0TO U-1ON A[J]-C[I]GOTO@L
NEXT
U=U+1@L
C[I]=A[J]INC N[I]NEXT
RSORT.,U,N,C
FOR I=0TO U-1?"#";HEX$(C[I],6),N[I]NEXT
END

```

Image is given as an array of 32 bit ARGB color values (the alpha value is trimmed when the number is converted to a 6 digit hex string)
> 0 votes

---
Tags: code-golf, image-processing, color
---


title: Expand compressed brain-flak

text:
# Question
Title: Expand compressed brain-flak
**This challenge was posted as part of the April 2018 LotM challenge, as well as for Brain-flak's 2nd birthday**

---

I was thinking about what the most efficient way to encode brain-flak programs would be. The obvious thing to do, since there are only 8 valid characters, is to map each character to a 3-bit sequence. This is certainly very effective, but it's still very redundant. There are some features of brain-flak code that we could take advantage of to shorten the encoding.

* The nilads, which are all represented by 2 matched brackets, really act as a single unit of information rather than 2. If we replaced each bracket with a single byte character, this would make the encodings much smaller without losing any data.
* This one is less obvious, but the *closing bytes* of the monads are redundant too. Think you could guess what the `'?'` characters represent in the following snippet?

```
 {(({}?<>?<>?

```

If we assume the input is valid brain-flak code, then there is only one option for each of those question marks. This means that we can unambiguously use a *close monad* character to represent every closing bracket. This has the added benefit of keeping the character set small, which would greatly help if we wanted to use a huffman encoding. Since the *close monad* character will most likely be the most common character by a wide margin, it could be represent by a single bit, which is hugely efficient.

These two tricks will let us compress brain-flak code via the following algorithm:

1. Replace every closing bracket of a monad with `|`. Or in other words, replace every closing bracket that **is not** preceded by it's opening match with a bar. So...

```
(({})<(()()())>{})

```

would become

```
(({}|<(()()()||{}|

```
2. Replace every nilad with it's closing bracket. Therefore, matched brackets with nothing in them use the following mapping:

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

```

Now our last example becomes:

```
((}|<()))||}|

```
3. Remove trailing `|` characters. Because we know that the total number of bars should equal the total number of `({[<` characters, if there are bars at the end missing, we can infer them. So an example like:

```
({({})({}[()])})

```

would become

```
({(}|(}[)

```

Your challenge for today is to reverse this process.

Given a string of compressed brain-flak containing only the characters `(){}[]<>|`, expand it into the original brain-flak code. You can assume that the input will always expand to valid brain-flak. This means that no prefix of the input will ever contain more `|` than `({[<` characters.

The input will not contain trailing `|` characters. These must be inferred from context.

As usual, you can submit either a full program or a function, and input/output formats are permissive. And since this is a , your code will be scored by the length of the source code in bytes, the smaller the score the better.

### Test cases

Here are some test cases. If you would like more, you can generate your own test cases with this python script and the Brain-Flak Wiki, which is where the majority of these test cases come from.

```
#Compressed code
#Original code

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

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

({(}|(}[)|||}
({({})({}[()])}{})

(((()))||(](((}}||(}([(((}))||||(]((}}|}|}}|||]||]|[))||(}))|}(}|(}]]|}
((((()()()))([]((({}{}))({}([((({}()())))]([](({}{}){}){}{})))[]))[])[()()])({}()()){}({})({}[][]){}

```

# Answer
# Brain-Flak, ~~952 916~~ 818 bytes

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

```

Saved 360 bytes by calculating opposing brackets relatively rather than from scratch (e.g. `')'` = `'(' + 1` instead of `(((5 * 2) * 2) * 2) + 1`)

Saved 34 bytes with some direct replacements from DJMcMayhem

Saved 10 bytes by overlapping the `>]}` handling code

Saved 118 bytes by deduplicating rolls

Saved 40 bytes by taking advantage of the empty stack to simplify the first roll

Saved 48 bytes by marking EOF with -1, enabling more concise roll code

Saved 36 bytes by using the stock equals logic instead of my own

Saved 98 bytes thanks to Jo King finding a more efficient way to build the output

Try it online!

First time golfing in Brain-Flak, so there are probably some really big improvements, but it works. Lots of copy/paste to handle each bracket type, and big thanks to the automatic integer generator and the Roll snippet from here.

Explanation here, TIO formats it more easily

Bonus answer:

# Compressed Brain-Flak 583 bytes

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

```

Try it online!

(Note that the above link does not run because TIO doesn't have a Compressed Brain-Flak interpreter. You can find a transpiler to Brain-Flak here)

I have checked that this is valid by transpiling to Brain-Flak using this tool, now efficient enough that timing out is unlikely.
> 33 votes

# Answer
# Retina 0.8.2, ~~103~~ 98 bytes

```
[])}>]
$&;
T`])}>|`[({<;
r`(.*)((;)|(?<-3>.))*
$&$.1$*;
(?<=(.)((;)|(?<-3>.))*);
;$1
T`;-{`_>-}`;.

```

Try it online! Link includes test cases. Edit: Saved 5 bytes with inspiration from @MartinEnder. Explanation:

```
[])}>]
$&;
T`])}>|`[({<;

```

Put a `;` after every close bracket and change them all to open brackets, and change the `|`s to `;`s too.

```
r`(.*)((;)|(?<-3>.))*
$&$.1$*;

```

Count the number of unmatched open brackets and add that many `;`s.

```
(?<=(.)((;)|(?<-3>.))*);
;$1

```

Copy each opening bracket to its matching `;`.

```
T`;-{`_>-}`;.

```

Flip the copied brackets and delete the `;`s.
> 7 votes

# Answer
# TIS, ~~670~~ 666 bytes

<sup>-4 bytes for jumping forward to jump back</sup>

Code:

```
@0
MOV UP RIGHT
@1
MOV ANY ACC
SUB 41
NOP
NOP
NOP
NOP
NOP
NOP
NOP
NOP
MOV ACC DOWN
@2
NOP
MOV 124 LEFT
@3
MOV ANY DOWN
@4
MOV UP ACC
JGZ O
MOV 40 LEFT
JLZ (
MOV 41 LEFT
JRO 3
O:SUB 21
MOV ACC DOWN
JRO -8
(:MOV 41 RIGHT
@5
MOV ANY DOWN
@6
MOV ANY DOWN
@7
MOV UP ACC
JGZ O
MOV 60 LEFT
JLZ <
MOV 62 LEFT
JRO 3
O:SUB 31
MOV ACC DOWN
JRO -8
<:MOV 62 RIGHT
@8
MOV ANY DOWN
@9
MOV ANY DOWN
@10
S:MOV UP ACC
JGZ O
MOV 91 LEFT
JLZ [
MOV 93 LEFT
JRO 3
O:SUB 31
MOV ACC DOWN
JRO -8
[:MOV 93 RIGHT
@11
MOV ANY DOWN
@12
MOV ANY DOWN
@13
MOV UP ACC
JEZ |
MOV 123 LEFT
JLZ {
MOV 125 LEFT
JRO 2
|:MOV DOWN LEFT
JRO -7
{:MOV 125 RIGHT
@14
MOV ANY DOWN
@15
MOV UP DOWN
@16
MOV UP LEFT

```

Layout:

```
6 3
CCCCCCCCCCCCCCCCSC
I0 ASCII -
O0 ASCII -

```

Try it online!

I doubt this is smallest, but I don't see a way to make it smaller. Unfortunately, all the `NOP`s seem necessary for timing, and I can't put the stack where `@14` currently is because of the read from `ANY` in `@11`.

The structure of this solution is as follows:

```
Input
  |
  V
  0    1:synchro  2:EOF
  3    4:parens     5
  6    7:angles     8
  9   10:squares   11
 12   13:curlies   14
 15      stack     16
  |
  V
Output

```

Upon seeing an open brace, the open is sent along the left column to be output, and the close is sent along the right column to the stack.

Upon seeing a close brace, the open and close are both sent along the left column to be output.

Upon seeing a pipe, the stack is popped and sent to output.

Upon EOF, `@1` will begin reading from `@2`, instead of the input stream from `@0`. `@2` produces an endless stream of pipes, so the stack will be drained.

Once both the input and the stack are exhausted, the program halts.

Warning: due to the limitations of TIS, the stack size is limited to 15. If anything is nested deeper than that, this implementation will produce an incorrect result.
> 5 votes

# Answer
# JavaScript (ES6), 107 bytes

Takes input as an array of characters. Returns a string.

```
a=>a.map(c=>(n=(S='|()[]{}<>').indexOf(c))?n&1?(s=[S[n+1],...s],c):S[n-1]+c:s.shift(),s=[]).join``+s.join``

```

Try it online!
> 4 votes

# Answer
# Brain-Flak, ~~606 548 496 418 394~~ 390 bytes

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

```

Try it online!

I started this by golfing Kamil Drakari's answer, but it got away from me to the point where I decided to post it as a separate answer.

### Explanation:

```
{ #While input on stack
	((({})))(<>)	#Preserve copy of the character
	(((((		#Push the differences between start bracket characters
	((([(())()()()]){}){}){}())	#Push -31, 1
	(()))				#Push -30, 1
	(((())()())()){}{})		#Push -19, 1
	){}[()])			#Push -39
	({<(({}<>{}[()]))>(){[()](<{}>)}{}<>}{}<><{}>)	#If the character is any of the start brackets
	{({}({})<>)(<>)}{}					#Push the current character + TOS to the other stack

	({}<>)(<>)
	(((((		#Push the differences between end bracket characters
	((([(())()()()]){}){}){}())	#Push -31, 1
	(()))				#Push -30, 1
	(((())()){}()){})		#Push -19, 1
	){})				#Push -40
	({<(({}<>{}[()]))>[()]{()(<{}>)}{}<>}{}<>)	#If the character is any of the end brackets
	{(<({}(<()>)<>({})<{({}<>)<>}>)>)<>{({}<>)<>}}{}	#Push the character + TOS to the output

	({}()<>)	#If the character is not a |
	{{}({}<>)((<>))}{}	#Move current character to the other stack and push a zero
	{}		#Pop the top value of the stack, either the | or a 0
	<>(<({}(<()>)<><{({}<>)<>}>)>)<>{({}<>)<>}{}<>	#And push top of other stack to the output
}{}
{({}{}<>)<>}<>	#Reverse output and append the excess end brackets

```

And of course...

# Compressed Brain-Flak, 285 bytes:

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

```
> 4 votes

# Answer
## Haskell, ~~127~~ 121 bytes

```
(""#)
(u:t)#('|':b)=u:t#b
s#(c:b)|elem c")>]}"=m c:c:s#b|q<-m c:s=c:q#b
s#b=b++s
m c="> < ] [)(} {"!!mod(fromEnum c-6)27

```

Try it online!

Edit: -6 bytes by using @Laikoni's function to find the matching bracket.
> 3 votes

# Answer
# Ruby, 104 bytes

```
a=[];$<.chars{|c|r="|[{(<>)}]";i=r.index(c);i<1||(i<5?a:$>)<<r[-i];$>.<<i<1?a.pop: c};$><<a.reverse.join

```

This is a full program that outputs to the console. `(i<5?a:$>)<<r[-i]` has got to be one of the coolest golfs I have ever done.

Try it online!

# Ruby, 106 bytes

```
->s{a=[];(s.chars.map{|c|r="|>)}][{(<";d=r[-i=r.index(c)];i<5||a<<d;i<1?a.pop: i<5?d+c:c}+a.reverse).join}

```

This is my first solution. An anonymous lambda function that takes and returns strings.

Try it online!
> 3 votes

# Answer
# Java 10, 424 bytes

```
s->{int i=0;for(var c:s.toCharArray()){if("(<[{".indexOf(c)>-1)i++;if(c=='|')i--;}for(;i-->0;)s+='|';s=s.replace(")","()").replace(">","<>").replace("]","[]").replace("}","{}");char[]c=s.toCharArray(),r=new char[124];r[40]=41;r[60]=62;r[91]=93;r['{']='}';var o="";for(;++i<c.length ;){if(c[i]=='|'){c[i]=o.charAt(0);o=o.substring(1);}if("(<[{".indexOf(c[i])>-1&")>]}".indexOf(i+1<c.length?c[i+1]:0)<0)o=r[c[i]]+o;}return c;}

```

It's kind of lengthy, but I couldn't figure out how to shorten it further. This is a nice challenge though.

Try it online here.

Ungolfed version:

```
s -> { // lambda taking a String argument and returning a char[]
    int i = 0; // used for counting the number of '|'s that have been removed at the end of the input
    for(var c : s.toCharArray()) { // look at every character
        if("(<[{".indexOf(c) > -1) // if it's an open monad character
            i++; // we will need one more '|'
        if(c == '|') // if it's a close monad character
            i--; // we will need one '|' less
    }
    for(; i-- > 0; ) // add as many '|'
        s += '|';    // as necessary
    s = s.replace(")", "()").replace(">", "<>").replace("]", "[]").replace("}", "{}"); // replace compressed nilads with their uncompressed versions
    char[] c = s.toCharArray(), // from now on working on a char[] is more efficient since we will only be comparing and replacing
    r = new char[124]; // map open monad characters to their counterparts:
    r[40] = 41;   // '(' to ')'
    r[60] = 62;   // '<' to '>'
    r[91] = 93;   // '[' to ']'
    r['{'] = '}'; // '{' to '}'
    var o = ""; // we use this String as a kind of stack to keep track of the last open monad character we saw
    for(; ++i < c.length ;) { // iterate over the length of the expanded code
        if(c[i] == '|') { // if the current character is a close monad character
            c[i] = o.charAt(0); // replace it with the top of the stack
            o = o.substring(1); // and pop the stack
        }
        if("(<[{".indexOf(c[i]) > -1 // if the current character is an open monad/nilad character
         & ")>]}".indexOf(i+1 < c.length ? c[i+1] : 0) < 0) // and it's not part of a nilad (we need to test for length here to avoid overshooting)
            o = r[c[i]]+o; // using the mapping we established, push the corresponding character onto the stack
    }
    return c; // return the uncompressed code
}

```
> 2 votes

# Answer
# Python 2, ~~188~~ ~~184~~ ~~180~~ ~~177~~ ~~174~~ 173 bytes

```
p,q='([{<',')]}>'
d,s,a=dict(zip(p,q)),[],''
for c in input():
 if c in d:a+=c;s+=[c]
 elif'|'==c:a+=d[s.pop()]
 else:a+=dict(zip(q,p))[c]+c
for c in s[::-1]:a+=d[c]
print a

```

Saved 4 bytes thanks to DJMcMayhem.
Try it online!
> 2 votes

# Answer
# Python 3, 122 bytes

```
D='()<>[]{} '
def f(x):
 a=s=''
 for c in x:i=D.find(c);a+=i<0and s[0]or D[i-(i&1):i+1];s=D[i+1][i&1:]+s[i<0:]
 return a+s

```

Try it online!
> 2 votes

# Answer
# Haskell, 152 bytes

```
fst.p
m c="> < ] [)(} {"!!mod(fromEnum c-6)27
p(c:r)|elem c")]}>",(s,t)<-p r=(m c:c:s,t)|c/='|',(s,'|':t)<-p$r++"|",(u,v)<-p t=(c:s++m c:u,v)
p e=("",e)

```

Try it online! or verify all test cases. `p` implements a recursive parser, which might be over kill for the simple grammar.
> 1 votes

# Answer
# Python 2, 244 bytes

```
s=input()
B='([{<'
C=')]}>'
Z=zip(B,C)
P=sum(map(s.count,B))-s.count('|')
for i,j in Z:s=s.replace(j,i+j)
s+=P*'|'
b=[0]
for i in s:[b.pop()for j,k in Z if j==b[-1]<k==i];b+=[i][:i in B];s=i=='|'and s.replace(i,C[B.find(b.pop())],1)or s
print s

```

Try it online!

It took way more than an hour or two to get this working...
> 1 votes

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


title: Approximate a Bell Curve

text:
# Question
Title: Approximate a Bell Curve
Create a program to display some approximation of a bell curve. You are free to use whatever method you wish for generating the data, but the data must be displayed vertically, as in oriented like so:

Other restrictions:

* Your code must create the approximation, that is, don't hardcode or take data from the internet.
* The shape must actually look like a bell.

This is a , so be creative.

# Answer
# Java

The method of generation is based off of the game *Sugar, Sugar*. In that game, sugar particles fall, traveling randomly left and right. In my program, `Dust` objects fall until they hit the ground. I collect data based on where they land; this is the bell curve:

```
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.Stack;
import javax.imageio.ImageIO;

/**
 *
 * @author Quincunx
 */
public class ApproxBellCurve {

    public static final int NUM_DUST = 10_000_000;
    public static final int NUM_THREADS = Runtime.getRuntime().availableProcessors() - 1;
    public static final int LOOP_LIMIT = NUM_DUST / (NUM_THREADS + 1);

    public static void main(String[] args) {
        BufferedImage output = new BufferedImage(2049, 2049, BufferedImage.TYPE_INT_RGB);

        Stack<Thread> threads = new Stack();

        for (int i = 0; i < NUM_THREADS; i++) {
            threads.push(new Thread(new Duster()));
            threads.peek().start();
        }

        Dust d;
        Random r = new Random();
        for (int i = 0; i < LOOP_LIMIT + NUM_DUST - (LOOP_LIMIT * (NUM_THREADS + 1)); i++) {
            d = new Dust(r);
            while (!d.end) {
                d.step();
            }
            if ((i & 1024) == 0) {
                r = new Random();
            }
        }
        while (threads.size() > 0) {
            try {
                threads.pop().join();
            } catch (InterruptedException ex) {

            }
        }
        int maxy = 0;
        for (int x = 0; x < Dust.data.length; x++) {
            maxy = Dust.data[x] > maxy ? Dust.data[x] : maxy;
        }

        for (int x = 0; x < Dust.data.length; x++) {
            for (int y = 0; y < output.getHeight(); y++) {
                output.setRGB(x, y, (y >= output.getHeight() - (Dust.data[x] * output.getHeight() / maxy)) ? 6591981 : 16777215);
            }
        }
        try {
            ImageIO.write(output, "png", new File("Filepath"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private static class Duster implements Runnable {

        @Override
        public void run() {
            Dust d;
            Random r = new Random();
            for (int i = 0; i < LOOP_LIMIT; i++) {
                d = new Dust(r);
                while (!d.end) {
                    d.step();
                }
                if ((i & 1024) == 0) {
                    r = new Random();
                }
            }
        }

    }

    private static class Dust {

        public static int[] data = new int[2049];

        static {
            for (int i = 0; i < data.length; i++) {
                data[i] = 0;
            }
        }

        private int[] location;
        private Random r;
        public boolean end;

        public Dust(Random rand) {
            location = new int[]{1024, 0};
            r = rand;
            end = false;
        }

        public void step() {
            if (end) {
                return;
            }
            if (location[1] >= 1024) {
                end = true;
                synchronized (data) {
                    data[location[0]] += 1;
                }
                return;
            }
            location[1] += 1;
            location[0] += r.nextInt(21) - 10;
        }
    }
}

```

Sample output (took 1 minute to create):

Because of the nature of the random number generation, it is possible to get an `ArrayIndexOutOfBoundsException`.

I used multithreading to speed up the process. The program determines the number of processors available and creates that many threads to run the simulations.

To obtain a finer image, `NUM_DUST` can be increased, but that would also lead to an increased risk of an `ArrayIndexOutOfBoundsException`.

Each thread creates a new `Random` after every 1024 `Dust` objects are simulated. When that code was removed, the image was more coarse.

`rand.nextInt(21) - 10` is to widen the distribution. A change to `rand.nextInt(3) - 1` would remove all chance of an `ArrayIndexOutOfBoundsException`.
> 12 votes

# Answer
## Mathematica

I decided it should not only look like a bell curve, it should look like a bell. So hey, let's spin it around the Z-axis and make it 3D.

And hey, while we're at it, it should *sound* like a bell as well.

So, each time you evaluate the code, it makes a nice pleasing church-bell BWONNGGG!

```
Manipulate[
 RevolutionPlot3D[PDF[NormalDistribution[mu, sigma], x], {x, -4, 4},
  PlotRange -> {Automatic, Automatic, Automatic},
  BoxRatios -> {1, 1, 1}, PlotStyle -> {Orange, Yellow},
  ImageSize -> {500, 500}], {{mu, 0, "mean"}, -3, 3,
  Appearance -> "Labeled"}, {{sigma, 1.47, "standard deviation"}, .5,
  2, Appearance -> "Labeled"}]
EmitSound[Sound[SoundNote[0, 3, "TubularBells", SoundVolume -> 1]]]

```

Here's what it looks like:

And here's a brief video of the bell ringing.
> 9 votes

# Answer
## Haskell, 9 LoC

Everyone's code is so ... huge, and their approximations are ... less than deterministic. Just to remind everyone of the simplicity of the actual task, here's a nine-liner in Haskell:

```
import Data.List; import Data.Ratio
main = do
  putStrLn "please choose the width and the maximum height:"
  [w, mh] <- (map read.words) `fmap` getLine
  let dist = map length $ group $ sort $ map length $ subsequences [2..w]
      scale = ceiling $ maximum dist % mh
      maxD = scale * ceiling (maximum dist % scale)
  putStrLn $ unlines $ map (row dist) [maxD, maxD - scale .. 0]
      where row dist y = map (\x -> if x >= y then '*' else ' ') dist

```

OK... that wasn't exactly fast. Here's another go. Does it still count as not hard-coded?

```
import Data.List; import Data.Ratio

main = do
  putStrLn "please choose the width and the maximum height:"
  [w, mh] <- (map read.words) `fmap` getLine
  let dist = map ((w-1) `choose`) [0..(w-1)]
      scale = ceiling $ maximum dist % mh
      maxD = scale * ceiling (maximum dist % scale)
  putStrLn $ unlines $ map (row dist) [maxD, maxD - scale .. 0]
      where row dist y = map (\x -> if x >= y then '*' else ' ') dist

factorial x = product [1..x]
n `choose` k = factorial n `div` factorial k `div` factorial (n-k)

```
> 7 votes

# Answer
## Wolfram Alpha (tongue-in-cheek) 4 bytes:

Here is a practical application of the Central Limit Theorem. I even golfed it!

Type this into the input box on Wolfram Alpha:

```
3d20

```

Here is a link to the results. It interprets this input as 3 icosahedral dice, and decides you want a graph of the distribution function of the pip sums. It prints the following graph:

We can make the graph more and more bell shaped by adding more dice. I don't see this as taking my data from the internet since, if I could run the query engine for it on my home computer I would. Unfortunately, Wolfram Research doesn't provide it for download, though.
> 6 votes

# Answer
# Ruby

Simulates the classic example of bell curves, dropping a ball down a grid full of pole thingies.

```
a = [0]*30
1000.times do
  x = 15
  49.times do
    x += (rand(3) - 1)
  end
  a[[[x.to_i, 29].min, 0].max] += 1
end
until a.all?{|x| x == 0}
  a.each_with_index{|x,i|
    if x == 0
      print ' '
    else
      print 'x'
      a[i] -= 1
    end
  }
  puts
end

```

Sample output:

```
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  xxxxxxxxxxxxxxxxxxxxxxxxxx
  xxxxxxxxxxxxxxxxxxxxxxxxxx
  xxxxxxxxxxxxxxxxxxxxxxxxxx
  x xxxxxxxxxxxxxxxxxxxxxxxx
    xxxxxxxxxxxxxxxxxxxxxxxx
    xxxxxxxxxxxxxxxxxxxxxxxx
    xxxxxxxxxxxxxxxxxxxxxxxx
     xxxxxxxxxxxxxxxxxxxxxxx
     xxxxxxxxxxxxxxxxxxxx
     xxxxxxxxxxxxxxxxxxxx
     xxxxxxxxxxxxxxxxxxxx
     xxxxxxxxxxxxxxxxxxxx
     xxxxxxxxxxxxxxxxxxxx
     xxxxxxxxxxxxxxxxxxxx
     xxxxxxxxxxxxxxxxxxxx
     xxxxxxxxxxxxxxxxxxx
      xxxxxxxxxxxxxxxxxx
      xxxxxxxxxxxxxxxxxx
      xxxxxxxxxxxxxxxxxx
      xxxxxxxxxxxxxxxxxx
       xxxxxxxxxxxxxxxxx
        xxxxxxxxxxxxxxxx
        xxxxxxxxxxxxxxxx
        xxxxxxxxxxxxxxx
        xxxxxxxxxxxxxxx
        xxxxxxxxxxxxxxx
        xxxxxxxxxxxxxxx
        xxxxxxxxxxxxxxx
        xxxxxxxxxxxxxxx
        xxxxxxxxxxxxxxx
        xxxxxxxxxxxxxxx
        xxxxxxxxxxxxxx
        xxxxxxxxxxxxxx
         xxxxxxxxxxxxx
         xxxxxxxxxxxxx
         xxxxxxxxxxxxx
         xxxxxxxxxxxxx
         xxxxxxxxxxxxx
         xxxxxxxxxxxxx
         xxxxxxxxxxxx
          xxxxxxxxxxx
          xxxxxxxxxxx
          xxxxxxxxxxx
          xxxxxxxxxxx
           xxxxxxxxxx
           xxxxxxxxxx
           xxxxxxxxxx
           xxxxxxx xx
           xxxxxxx xx
           xxxxxxx xx
            xxxxxx xx
            xxxxxx xx
            xxxxxx x
            xxxxx  x
            xxxxx  x
              xxx  x
              xxx  x
              xxx  x
              xxx  x
              xxx  x
              xxx
              xxx
              xxx
              xxx
              xxx
              xxx
              xxx
              xxx
              xxx
              x x
              x x
              x x
              x x
              x
              x
              x

```

Oh, did I forget to mention it's upside down?
> 4 votes

# Answer
## Python

```
from pygame import*
t,u=640,400;init();d=display;s=d.set_mode((t,u))
s.fill(0xFFFFFF)
for x in range(t):
  d.flip();event.get()
  draw.line(s,u,(x,int(u-2**(-((x-t*.5)/120)**2)*u)),(x,u))

while time.wait(50):
 for e in event.get():
  if e.type==QUIT:exit()

```

This is actually a normal distribution, using *2* as the base of the exponent instead of *e*, and not dividing by *⎷2π*, because without axes, it doesn't really matter if the area under the curve isn't exactly *1*.

The last 3 lines just keep the window open until the user closes it manually.
> 4 votes

# Answer
# Mathematica

Generating the sums of 5 random integers, each between 0 and 100, 20000 times.

```
Histogram[Plus @@@ RandomInteger[100, {20000, 5}]]

```

---

Here's the result for sums of 1,2, 3 numbers. As the number of integers to be summed increases, the curve approaches the bell shape.

When single random integers are generated, but not summed, the distribution should be fairly uniform, not favoring any value. The apparent anomaly for 100 may be the result of how Matheamtica bins data. (see https://mathematica.stackexchange.com/questions/43300/does-randominteger0-n-disfavor-n/43302#43302 )

```
Table[Histogram[Plus @@@ RandomInteger[100, {20000, k}]], {k, 1, 3}]

```
> 4 votes

# Answer
## C#, WPF

Rough approximation with a hand-crafted Bézier curve. To make it more interesting: No use of `Line`, `Path` or similar, only `Ellipse`.

```
public MainWindow()
{
    InitializeComponent();
    // Requires a Canvas named Canvas in XAML file
    DrawBellCurve(Canvas, 300, 300);
}

public static void DrawBellCurve(Canvas canvas, int width, int height)
{
    Point p1 = new Point(0, height);
    Point p2 = new Point(0.3 * width, 1 * height);
    Point p3 = new Point(0.4 * width, 0.1 * height);
    Point peak = new Point(width / 2, 0);
    Point p3r = new Point(width - p3.X, p3.Y);
    Point p2r = new Point(width - p2.X, p2.Y);
    Point p1r = new Point(width, height);
    List<Point> controlPoints = new List<Point> { p1, p2, p3, peak, p3r, p2r, p1r };

    DrawBezierCurve(canvas, controlPoints, Color.FromRgb(50, 200, 25));
    DrawPoints(canvas, controlPoints, 5, Color.FromRgb(80, 80, 220));
}

public static void DrawPoints(Canvas canvas, List<Point> points, double radius, Color color)
{
    foreach (var p in points)
    {
        Ellipse ellipse = new Ellipse();
        ellipse.Width = radius;
        ellipse.Height = radius;
        ellipse.SetValue(Canvas.LeftProperty, p.X - radius / 2);
        ellipse.SetValue(Canvas.TopProperty, p.Y - radius / 2);
        ellipse.Fill = new SolidColorBrush(color);
        canvas.Children.Add(ellipse);
    }
}

public static void DrawBezierCurve(Canvas canvas, List<Point> controlPoints, Color color)
{
    var curvePoints = new List<Point>();
    double tStep = 0.01;
    for (double t = 0; t <= 1; t += tStep)
    {
        curvePoints.Add(GetBezierPoint(controlPoints, t));
    }

    DrawPoints(canvas, curvePoints, 3, color);
}

public static Point GetBezierPoint(List<Point> controlPoints, double t)
{
    // De Casteljau's algorithm
    if (controlPoints.Count == 1)
    {
        return controlPoints[0];
    }

    var newControlPoints = new List<Point>();
    for (int i = 0; i < controlPoints.Count - 1; i++)
    {
        Point p1 = controlPoints[i];
        Point p2 = controlPoints[i + 1];
        Point p = new Point(
            t * p1.X + (1 - t) * p2.X,
            t * p1.Y + (1 - t) * p2.Y);
        newControlPoints.Add(p);
    }
    return GetBezierPoint(newControlPoints, t);
}

```
> 4 votes

# Answer
# Java 8

It gets the height and the width from the user, chooses `width` random booleans and count how many are true, registering the counted frequency. Repeat this until some of the generated frequencies is enough to fill the height:

```
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Bell {
    public static int[] bell(int width, int height) {
        // I could have used Random.nextGaussian() method, but this way is more fun.
        Random r = new Random();
        int max = 0;
        int[] freqs = new int[width];
        for (int j = 0; max < height - 1; j++) {
            int count = 0;
            for (int i = 0; i < width; i++) {
                if (r.nextBoolean()) count++;
            }
            freqs[count]++;
            if (freqs[count] > max) max++;
        }
        return freqs;
    }

    public static BufferedImage drawBell(int[] ps, int width, int height) {
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < ps[i]; j++) {
                bi.setRGB(i, height - j - 1, 0xFF00FFFF); // Cyan
            }
            for (int m = i - 1; m <= i + 1; m++) {
                if (m < 0 || m >= width) continue;
                for (int n = ps[i] - 1; n <= ps[i] + 1; n++) {
                    if (n < 0 || n >= height) continue;
                    bi.setRGB(m, height - n - 1, 0xFF0000FF); // Blue
                }
            }
            for (int j = ps[i] + 1; j < height; j++) {
                bi.setRGB(i, height - j - 1, 0xFFFFFFFF); // White
            }
        }
        return bi;
    }

    public static void main(String[] args) {
        String a = JOptionPane.showInputDialog("Give the width:");
        String b = JOptionPane.showInputDialog("Give the height:");

        int w, h;
        try {
            w = Integer.parseInt(a);
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(null, "Invalid width.");
            return;
        }

        try {
            h = Integer.parseInt(b);
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(null, "Invalid height.");
            return;
        }

        int[] freqs = bell(w, h);
        BufferedImage image = drawBell(freqs, w, h);

        EventQueue.invokeLater(() -> {
            JFrame j = new JFrame("Bell curve");
            j.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            j.add(new SimpleSprite(image));
            j.setResizable(false);
            j.pack();
            j.setVisible(true);
        });
    }

    public static class SimpleSprite extends JComponent {
        private final BufferedImage image;
        private final Dimension dim;

        public SimpleSprite(BufferedImage image) {
            this.image = image;
            this.dim = new Dimension(image.getWidth(), image.getHeight());
        }

        @Override
        public Dimension getMinimumSize() {
            return dim;
        }

        @Override
        public Dimension getMaximumSize() {
            return dim;
        }

        @Override
        public Dimension getPreferredSize() {
            return dim;
        }

        @Override
        public void paintComponent(Graphics g) {
            g.drawImage(image, 0, 0, null);
        }
    }
}

```

Screenshot:
> 3 votes

# Answer
## GeoGebra

I don't know whether it is valid to use an application that is made to draw graphs, but if you enter this in the input, you get a Bell Curve:

```
f(x) = 3ℯ^(-(x - 1)²)

```

Or, if you want a customizable bell curve:

```
a = 0
b = 0
c = 0
d = 0
f(x) = a ℯ^((-(x - b)²) / 2 c²) + d

```

Then, make sure that you enable the sliders for the variables (if they are disabled, click on the circle next to the variable names). Then, you can set a value for them by sliding.

Image of the curve with the sliders (click to enlarge):
> 3 votes

# Answer
## Java

Throwing 6 dice in every possible combination approaches a 'normal distribution', which happens to be a bell curve.

```
public class Temp {
    public static void main(String[] args) throws Exception {
        int[] hist = new int[31];
        for (int d1 = 0; d1 < 6; d1++)
            for (int d2 = 0; d2 < 6; d2++)
                for (int d3 = 0; d3 < 6; d3++)
                    for (int d4 = 0; d4 < 6; d4++)
                        for (int d5 = 0; d5 < 6; d5++)
                            for (int d6 = 0; d6 < 6; d6++)
                                hist[d1 + d2 + d3 + d4 + d5 + d6]++;
        for (int y = 4104; y >= 0; y -= 228)
            for (int x = 0; x < 32; x++)
                System.out.print(x == 31? '\n' : hist[x] <= y? '\u3000' : (char)('\u2580' + Math.min(Math.ceil((hist[x] - y) / 28.5), 8)));
    }
}

```

Some Unicode tricks make the output smoother:

```
　　　　　　　　　　　　　　▅█▅
　　　　　　　　　　　　　▂███▂
　　　　　　　　　　　　　█████
　　　　　　　　　　　　▁█████▁
　　　　　　　　　　　　███████
　　　　　　　　　　　　███████
　　　　　　　　　　　▅███████▅
　　　　　　　　　　　█████████
　　　　　　　　　　　█████████
　　　　　　　　　　▇█████████▇
　　　　　　　　　　███████████
　　　　　　　　　▃███████████▃
　　　　　　　　　█████████████
　　　　　　　　▁█████████████▁
　　　　　　　　███████████████
　　　　　　　▃███████████████▃
　　　　　　　█████████████████
　　　　　▁███████████████████▁
▁▁▁▂▅█████████████████████▅▂▁▁▁

```
> 3 votes

# Answer
# Python and tkinter

I liked Doorknob's generation method and Victor's output (his generation is actually equivalent), so I decided to combine the two with tkinter!

```
from tkinter import *
import random

bins = [0]*201
for i in range(20000):
    x = 0
    for j in range(100):
        if random.randint(0, 1):
            x += 0.5
        else:
            x -= 0.5
    bins[int(x)+100] += 1

master = Tk()

w = Canvas(master, width = 201, height=200)
w.pack()

for i in range(201):
    w.create_line(i, 200, i, 200-bins[i]/10, fill="light blue")
    w.create_line(i-1, 200-bins[i-1]/10, i, 200-bins[i]/10, fill="blue")

```
> 2 votes

# Answer
# C

Based on random walks

```
#include <stdio.h>
#include <stdlib.h>

#define X_SIZE 40
#define Y_SIZE 15
#define SMOOTH 100

int main(void)
{
int i,j;
int T[X_SIZE*2];
int w;

for (i=0; i<X_SIZE*2; i++) T[i]=0;

// random walks
do  {
    w=X_SIZE;
    for (i=0;i<X_SIZE;i++)
        w+=rand()%2?1:-1;
    T[w]++;
    }
while (T[w]<Y_SIZE*SMOOTH);

// display
for (j=Y_SIZE; j>=0; j--)
    {
    for (i=0; i<X_SIZE*2; i+=2)
        printf("%c", (T[i]>j*SMOOTH)?'#':' ');
    printf("\n");
    }

}

```

Output :

```
               ###
               ###
              #####
              #####
              #####
             #######
             #######
            #########
            #########
            #########
           ###########
           ###########
          #############
         ###############
     #######################

```
> 2 votes

# Answer
# Octave

```
c=79;
x=ifft(fft([ones(1,10) zeros(1,c-10)]).^8);
y=(1:c)*0+' ';
for l=-24:-1,
  for k=1:c,
    if -real(x(k))<l*2e5,
      y(k)='*';
    end
  end
  printf([char(y) '\n'])
end

```

Try it online!

Instead of directly simulating coin flips, this just uses the observation that the pdf of a sum of random variables is the convolution of the pdfs of each of the random variables. An efficient way to do circular convolution is to take the inverse fourier transform of the element-wise product of the fourier transforms of the pdfs of each of the random variables. For the purpose of this problem (not true in general) circular convolution can stand in for linear convolution.

As an example, given the following pdf of a uniform random variable.

```
                           **********
                           **********
                           **********
                           **********
                           **********
                           **********
                           **********
                           **********
                           **********
                           **********
                           **********
                           **********

```

The above random variable summed with itself

```
                                *
                               ***
                               ***
                              *****
                             *******
                            *********
                           ***********
                           ***********
                          *************
                         ***************
                        *****************
                       *******************

```

The uniform random variable summed with itself 7 times.

```
                                *
                             *******
                           ***********
                          *************
                         ***************
                        *****************
                       *******************
                     ***********************
                    *************************
                   ***************************
                 *******************************
              *************************************

```
> 2 votes

# Answer
# J

```
load 'plot'
plot (3+i.58)([:+/=)"0 1]3+([:+/?,?,?)"0]1e6#20

```

Not very creative, but still fun!

Throws three twenty sided dice 1000000 times, summing the result each time. Then to get it in a `plot`-ready format, we take the array `[3..60]` and replace each element by the number of times it occures in the random sums.

`plot` then creates a PDF:
> 2 votes

# Answer
## Python (Box-Muller) - 6 lines

This short code uses the Box-Muller transform for simulating a normally distributed variable:

```
from math import cos, log, pi
from random import random

f = open("normDist.txt",'w')
for i in xrange(10**6):
    f.write(str(cos(2*pi*random())*(-2*log(random()))**.5)+'\n')
f.close()

```

You can plug the values on GNUPLOT or use this script

```
f=open("normDist.txt",'r')

v = [0 for i in xrange(51)]
for i in f:
    v[int(float(i)*10) if float(i)<5 and float(i)>-5 else 0]+=1

m=0
for i in v:
    if i>m:
        m=i
for i in v[3:]:
    for j in xrange(int(70.*i/m)):
        print '*',
    print

```

to produce something like this:

```
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* * *
* *
* *
* *
* *
* *
* *
* * *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

```
> 1 votes

# Answer
# awk

```
#!/ust/bin/awk -f
BEGIN {
  #
  # do WALKS random walks with OOPS times left or right per walk
  #
  WALKS=100000
  OOPS=39
  #
  # output will be H lines
  # the line width will be 2*OOPS+1
  #
  H=23
  #
  # shake awk's pseudorandom generator
  #
  srand()
  #
  # do the walks
  #
  for(i=0;i<WALKS;i++) {
    x=0
    for(j=0;j<OOPS;j++) rand()<0.5?--x:++x
    X[x]++
  }
  #
  # scan for maximum height
  #
  M=0
  for(x=-OOPS;x<=OOPS;x++) {
    if(X[x]>M) M=X[x]
  }
  #
  # "draw" into S[x]: strings of H*X[x]/M "*"s
  #
  for(x=-OOPS;x<=OOPS;x++) {
    s=sprintf("%*s",H*X[x]/M," ")
    gsub(/./,"*",s)
    S[x]=s
  }
  #
  # print S[x] transposed
  #
  for(y=H;y>0;y--) {
    for(x=-OOPS;x<=OOPS;x++) {
      if(c=substr(S[x],y,1)) printf c
      else printf " "
    }
    print ""
  }
}

```

Output:

```
                                        *
                                      * *
                                      * *
                                    * * * *
                                    * * * *
                                    * * * *
                                    * * * *
                                  * * * * * *
                                  * * * * * *
                                  * * * * * *
                                  * * * * * *
                                * * * * * * * *
                                * * * * * * * *
                                * * * * * * * *
                                * * * * * * * *
                              * * * * * * * * * *
                              * * * * * * * * * *
                              * * * * * * * * * *
                            * * * * * * * * * * *
                            * * * * * * * * * * * *
                            * * * * * * * * * * * *
                          * * * * * * * * * * * * * *
*******************************************************************************

```
> 1 votes

# Answer
# Stax, 20 bytes

```
⌐∞¶J♠fr"▐cS╥aÆ~a╚∩┌I

```

Run and debug it

This isn't code-golf but I still want to give Stax a try. Calculates frequency of sum of dices rolled 6 times. Note there are no support for random numbers in Stax.

ASCII equivalent:

```
6R6|^{|+m{o:G{AJ/'**mMrm

```

Output:

```
               *
              ***
              ***
              ***
             *****
             *****
             *****
             *****
             *****
            *******
            *******
            *******
            *******
            *******
            *******
           *********
           *********
           *********
           *********
           *********
           *********
          ***********
          ***********
          ***********
          ***********
          ***********
          ***********
         *************
         *************
         *************
         *************
         *************
        ***************
        ***************
        ***************
        ***************
       *****************
       *****************
       *****************
      *******************
      *******************
     *********************
    ***********************

```
> 1 votes

# Answer
# Charcoal

```
≔⟦Ｘφ±⁹⟧θＦ⁹⁹≔Ｅ⊞Ｏθ⁰⁺κ§θ⊖λθ↑θ

```

Verbose version:

```
Assign([Power(1000, Negate(9))], q);
for (99) Assign(Map(PushOperator(q, 0), Plus(k, AtIndex(q, Decremented(l)))), q);
Print(:Up, q);

```

Try it online! Output:

```
             ||
             ||
            ||||
            ||||
            ||||
            ||||
           ||||||
           ||||||
           ||||||
           ||||||
           ||||||
          ||||||||
          ||||||||
          ||||||||
          ||||||||
          ||||||||
          ||||||||
         ||||||||||
         ||||||||||
         ||||||||||
         ||||||||||
         ||||||||||
         ||||||||||
        ||||||||||||
        ||||||||||||
        ||||||||||||
        ||||||||||||
        ||||||||||||
        ||||||||||||
       ||||||||||||||
       ||||||||||||||
       ||||||||||||||
       ||||||||||||||
       ||||||||||||||
      ||||||||||||||||
      ||||||||||||||||
      ||||||||||||||||
      ||||||||||||||||
      ||||||||||||||||
     ||||||||||||||||||
     ||||||||||||||||||
     ||||||||||||||||||
    ||||||||||||||||||||
    ||||||||||||||||||||
    ||||||||||||||||||||
   ||||||||||||||||||||||
   ||||||||||||||||||||||
  ||||||||||||||||||||||||
 ||||||||||||||||||||||||||
||||||||||||||||||||||||||||

```
> 1 votes

---
Tags: popularity-contest, graphical-output
---


title: Tips for Golfing in Brain-Flak

text:
# Question
Title: Tips for Golfing in Brain-Flak
Brain-flak is a stack-based turing-tarpit language, written collaboratively between me, DJMcMayhem, and 1000000000.

Some users are very experienced in the mysterious ways of Brain-Flak. So I thought it a good idea to set up this question as a way for us, and hopefully others too, to share our knowledge with the community and lower the bar of entry to this language "designed to be painful to use". And perhaps even teach those of us with more experience some new tricks.

So what tips do you have for golfing in brain-flak? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to brain-flak (e.g. "remove comments" is not an answer).

Please post one tip per answer.

# Answer
# Use the Third Stack

If you have read the title you might be a bit confused. Surely there are only two stacks in Brain-Flak? However I assure you that it exists and it is one of the most powerful if not the most powerful tool in writing and golfing Brain-Flak.

---

## What is the "Third Stack"?

Every Brain-Flak program uses the third stack in one way or another but most of the use goes on behind the scenes and it is often useful to simply ignore the fact that it exists. Each parenthesis in the program either adds or removes one item from the stack. Three of the open braces `([<` all add an item to the stack while their three conjugates `)]>` all remove an item from the stack. The value of the item on the stack is the value of the current scope of the program and using nilads will modify this value in certain ways. The close parenthesis `)` has the unique function of moving an element from the Third Stack to the current stack; a push.

Hopefully this is becoming clear to you. The Third Stack is some sort of stack that remembers the return values of code that has already been executed. Let's walk through an example of a simple program keeping track of the two normal stacks and the Third Stack.

### Example

We will walk through the following program. This program pushes `-3, 1, -2` to the stack.

```
(([()()()])(()))

```

We start with three open braces, which all push a zero to the third stack.

Our stacks now look like this, the Third Stack is the one on the right and the active stack has a `^` under it:

```
        0
        0
  0  0  0
  ^

(([()()()])(()))
   ^

```

Now we have three `()` nilads. These do not do anything to the normal two stacks, however they do each add one to the top of the Third Stack making our stacks look like:

```
        3
        0
  0  0  0
  ^

(([()()()])(()))
         ^

```

Now we encounter a `]` as stated before close braces remove an item from the Third Stack, but `]` has the function of subtracting the element it removes from the top of the stack. Thus our new stacks will look like:

```
       -3
  0  0  0
  ^

(([()()()])(()))
          ^

```

This makes sense; `[...]` does negation so `]` should subtract downwards.

Now we must execute a `)`. As you likely recall `)` is the place in the program where stuff gets pushed to the stack so we will be moving the top of the Third Stack to the current stack, in addition we will be adding the `-3` to the next element in the third stack.

```
 -3  0 -3
  ^

(([()()()])(()))
           ^

```

Once again we encounter one of our three open braces so we will add another element to our Third Stack.

```
        0
 -3  0 -3
  ^

(([()()()])(()))
            ^

```

As we said earlier `()` will increment the top of our third stack by one.

```
        1
 -3  0 -3
  ^

(([()()()])(()))
              ^

```

And `)` will move the top of the Third Stack onto the active stack and add downwards

```
  1
 -3  0 -2
  ^

(([()()()])(()))
               ^

```

The last `)` moves the Third Stack onto the active stack and since there are no elements left on the Third Stack for it to add, does nothing else.

```
 -2
  1
 -3  0
  ^

(([()()()])(()))
                ^

```

The program is over so we terminate and output.

---

This example is intended to give you a feel for what the Third Stack is and does. It does not include all of the operations, but hopefully you can figure out what each of them does on its own. If you are still struggling I have included a "cheatsheet" at the bottom of this answer to help you along.

## Ok, So what?

Ok, now you understand the Third Stack, but "So what"? You were already using it even if you didn't call it the "Third Stack", how does thinking in terms of the Third Stack help you golf?

Lets look at a problem. You want to take the Triangle of a number. This is the sum of all numbers less than n.

One approach might be to create an accumulator on the offstack and add to it as you count down. This creates code that looks like this:

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

```

Try it Online!

This code is pretty compact and one might think that it can't get much smaller. However if we approach it from a third stack point of view it become clear that this is grossly inefficient. Instead of putting our accumulator on the offstack we can put it on the third stack with a `(` and retrieve it at the end we use `)`. We will once again loop through all the numbers, but this time we don't have to do much of anything to increment our Third Stack, the program does it for us. This looks like:

```
({()({}[()])}{})

```

Try it Online

This code is less than half the size of the pretty well golfed version we made before. In fact a computer search has proven that this program is the shortest possible program that can perform this task. This program can be explained using the "sum of all runs" approach, but I think it is a lot more intuitive and clear when explained using a Third Stack approach.

## When do I use the Third Stack?

Ideally whenever you begin work on a new problem in Brain-Flak you should think to yourself how would I do this with the Third Stack in mind. However as a general rule of thumb whenever you have to keep track of some type of accumulator or have a running total it is a good idea to try putting that on your third stack instead of the two real stacks.

Another time that it might be a good idea to consider using your third stack is when you don't have any space to store some value on the other two stacks. This can be particularly useful when you are doing manipulations on two existing stacks and you want to save a value for later use without having to keep track of where it is.

## Limitations of the Third Stack

The Third Stack is very powerful in a lot of ways but it comes with its own limitations and drawbacks.

Firstly, the maximum stack height for the Third Stack at any given point is determined at compile time. This means that if you want to use an amount of space on the stack you have to allocate that space when you are writing the program.

Secondly the Third Stack is not Random Access. This means that you cannot perform any operations on any value but the top most value. In addition you cannot move values around on the stack (say swap the first two elements).

## Conclusion

The Third Stack is a powerful tool and I would consider it essential to every Brain-Flak user. It takes some getting used to and requires a shift in the way your think about programming in Brain-Flak, but when used properly it makes all the difference between a decent and an amazing when it comes to golfing.

## Cheatsheet

Here is a list of operations and how they affect the Third Stack

```
 Operation  |                 Action
====================================================
   (,[,<    | Put a zero on top of the Third Stack
----------------------------------------------------
     )      | Add the top of the Third Stack to the
            | second element and move it to the
            | active stack
----------------------------------------------------
     ]      | Subtract the top of the Third Stack
            | from the second element and pop it
----------------------------------------------------
     >      | Pop the top of the Third Stack
----------------------------------------------------
     ()     | Add one to the top of the Third Stack
----------------------------------------------------
     {}     | Pop the top of the active stack and
            | add it to the top of the Third Stack
----------------------------------------------------
     []     | Add the stack height to the Third
            | Stack
----------------------------------------------------
   <>,{,}   | Nothing

```
> 26 votes

# Answer
## Finding modulus/remainder

Finding *n* modulo *m* is one of the basic arithmetic operations, important for many challenges. For cases *m \> 0* and *n \>= 0*, the following 46-byte snippet may be used. It assumes that *n* is on top of the active stack with *m* the next one down, and replaces them with *n* mod *m*. It leaves the rest of the stacks intact.

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

```

This annotated version shows the stack contents at some points in the program. `;` separates the two stacks and `.` marks the active stack.

```
. n m;
({}(<>))<>
{   . m; r 0   (r = n - km)
    (({}))
    . m m; r 0
    {({}[()])<>}
    {}
}
m-n%m-1 m; . 0
{}<>([{}()]{})
. n%m;

```
> 23 votes

# Answer
# Push-Pop Redundancy

This is a big one. It is also a little bit of a nuanced one.

The idea is that if you push something and then pop it without doing anything you should not have pushed it at all.

For example, if you want to move something to the offstack and then add one to it you might write the following code:

```
({}<>)({}())

```

This can be simpler like this:

```
({}<>())

```

The first program picks up the item moves it, picks it up again and adds one, while the second one does both in one fell swoop.

That example was simple however it can get a lot more complex. Take for instance:

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

```

The reduction is less clear here but the 4th pop in the program can be reduced with the 2nd push, like so:

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

```

This is the most powerful tool in my golfing repertoire but it takes some practice to get good at it. Once you have been doing these for a while you will be able to spot these almost instantly.
> 12 votes

# Answer
## Optimise your integers

Integers are tedious to represent in Brain-Flak. Fortunately we have a question that will help Golf a Brain-Flak Integer for you. (Note that the question is designed to push the integer to the stack, so push-pop redundancy probably applies to more realistic programs.)
> 6 votes

# Answer
# Push extra loop counters

Frequently, you'll want to do something like

> Perform **X** operation on every element in the stack

or

> Perform **X** operation on every pair of adjacent elements in the stack

When the input may contain '0's, or the result of operation **X** may give a 0, this is really inconvenient. Because you'll need to do:

```
([])
{

  {}

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

}

```

To do **X** to each element, and then later

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

```

To reverse the array again.

Even worse, if we're operatiing on pairs of adjacent elements, we'll need to do `([][()])` in place of `([])`. This is really inconvenient. Here's the trick: While you're doing **X** to each element, push a **1** over onto the alternate stack right above the `X(element)`. Then, while you're reversing it, you can simply do

```
<>
{
  {}
  ({}<>)
  <>
}
<>

```

This is 8 bytes shorter, so when you factor in the extra code to push 1, you'll end up saving 4-6 bytes. For a more concrete example, compare the task of getting deltas of an array. Without this trick, you'd need:

```
([][()]){

    {}

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

    ([][()])

}{}{}<>

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

```

For 62. With this trick, you'll have

```
([][()]){

    {}

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

    ([][()])

}{}{}<>

{{}({}<>)<>}<>

```

For 58. If used the right way (for example, reversing first, and removing two `([][()])` from later), this could save even more in speficic scenarios.
> 6 votes

# Answer
# Take advantage of the 'Stack-Height' nilad

Especially in challenges, or challenges where you always know the size of the input, you can take advantage of the 'Stack-Height' nilad `[]` to create integers.

Let's work through this with a hypothetical challenge: output `CAT`. The non-golfy way is to use the online integer golfer to push 67, 65, and 84. This gives:

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

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

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

```

(Newlines for clarity). This is 88 bytes, and not that great. If we instead push the consecutive differences between values, we can save a lot. So we wrap the first number in a *push* call, and subtract 2:

```
(   (((((()()()()){}){}){}()){}())  [()()] )

```

Then, we take this code, wrap it in a *push* call, and add 19 to the end:

```
(  ((((((()()()()){}){}){}()){}())[()()])   ((((()()()){})){}{}()) )

```

This is 62 bytes, for a whopping 26 byte golf!

Now *here* is where we get to take advantage of the stack-height nilad. By the time we start pushing 19, we know that there are already 2 items on the stack, so `[]` will evaluate to `2`. We can use this to create a 19 in fewer bytes. The obvious way is to change the inner `()()()` to `()[]`. This only saves two bytes though. With some more tinkering, it turns out we can push 19 with

```
((([][]){})[]{})

```

This saves us 6 bytes. Now we are down to 56.

You can see this tip being used very effectively on these answers:
> 4 votes

# Answer
# Use the wiki

We have a wiki! It has some short comings, but it is helpful resource. It has lists of useful, well golfed, stack clean programs that you can paste into your code. If you want to do something you think someone might have done before there is a good chance it is on the wiki.
> 3 votes

# Answer
# Better looping

Here's an easy one:

A fairly common construct is:

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

```

Where you want to loop n times but still keep the n. However this can be written as:

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

```

to save 2 bytes.

Another fairly common paradigm is

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

```

Which will loop and accumulate the entire stack. Due to some fancy maths this is the same as:

```
(([]){[{}]...([])}{})

```
> 3 votes

# Answer
# Check your negatives

Sometimes you can golf a few bytes by strategically choosing what to negate with the `[...]` monad.

A simple example is in nested `[...]`s. For example `[()()()[()()]]` could just be `[()()()]()()`

Say you want to check whether a value is any of the start brackets `(<{[`. The initial attempt is to push the difference between each character and loop over subtracting it

```
({}<(((((       #Push the differences between start bracket characters
(((()()()()){}){}){})   #Push 32
[()])                   #Push 31
[((()()())()){}{}])     #Push 20
){})><>)                #Push 40
<>({<(([{}]<>{}))>(){[()](<{}>)}<>})

```

However, you can save 4bytes by pushing the negative versions of the differences instead!

```
({}<(((((       #Push the differences between start bracket characters
((([()()()()]){}){}){}) #Push -32
())                     #Push -31
((()()())()){}{})       #Push -20
){})><>)                #Push -40
<>({<(({}<>{}))>(){[()](<{}>)}<>})

```

Generally, this doesn't save you very much, but it also costs very little effort to change around what the `[...]` is surrounding. Be on the lookout for situations where you can push the negative of a counter instead of the positive to save on incrementing multiple times instead of decrementing later. Or swapping out `(a[b])` with `([a]b)` to make the difference between two numbers negative instead of positive.
> 2 votes

---
Tags: code-golf, tips, brain-flak
---


title: These are the Frequencies, Kenneth

text:
# Question
Title: These are the Frequencies, Kenneth
# The Challenge

Generate 1 sec of an 8 bit tone sampled at 256 samples per second. The tone will be made up of a number of sine waves. The frequency of each sine wave will be determined from the input data.

These are deep tones, too low for a human to perceive, but I've chosen 8 bit numbers here since it's code-golf.

# The Input

You will receive an array (or a list) of (non-negative) 8 bit signed integer values (0-127), each number will represent a frequency. An empty list is allowed and numbers may appear more than once in the list. All input frequencies must be assumed to be equal in amplitude.

# The Output

Your program or function must output an array (or list) of 8 bit signed integer values that represents the signal generated.

Some graphical examples follow, but the actual output of your program is to be a list of integers. ***Not*** a graph and ***not*** a stream of bytes.

Also, your output must be *normalized*. That is, it must fill the window of possible values from -128 to 127. In other words, if you calculate a signal and its \[min,max\] is \[-64,63\], then you must amplify (multiply) the entire signal ×2. A flat signal will be all zeros. There should be no DC component in any output signal (ie. the average value should be 0). Since most (practically all) generated signals will be symmetrical then most likely your normalized signal will never contain a -128.

The actual expected output of these datasets are as follows:

```
[]                                    => [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
[2]                                   => [0,6,12,18,24,30,36,42,48,54,59,65,70,75,80,85,89,94,98,102,105,108,112,114,117,119,121,123,124,125,126,126,127,126,126,125,124,123,121,119,117,114,112,108,105,102,98,94,89,85,80,75,70,65,59,54,48,42,36,30,24,18,12,6,0,-6,-12,-18,-24,-30,-36,-42,-48,-54,-59,-65,-70,-75,-80,-85,-89,-94,-98,-102,-105,-108,-112,-114,-117,-119,-121,-123,-124,-125,-126,-126,-127,-126,-126,-125,-124,-123,-121,-119,-117,-114,-112,-108,-105,-102,-98,-94,-89,-85,-80,-75,-70,-65,-59,-54,-48,-42,-36,-30,-24,-18,-12,-6,0,6,12,18,24,30,36,42,48,54,59,65,70,75,80,85,89,94,98,102,105,108,112,114,117,119,121,123,124,125,126,126,127,126,126,125,124,123,121,119,117,114,112,108,105,102,98,94,89,85,80,75,70,65,59,54,48,42,36,30,24,18,12,6,0,-6,-12,-18,-24,-30,-36,-42,-48,-54,-59,-65,-70,-75,-80,-85,-89,-94,-98,-102,-105,-108,-112,-114,-117,-119,-121,-123,-124,-125,-126,-126,-127,-126,-126,-125,-124,-123,-121,-119,-117,-114,-112,-108,-105,-102,-98,-94,-89,-85,-80,-75,-70,-65,-59,-54,-48,-42,-36,-30,-24,-18,-12,-6]
[1,3]                                 => [0,8,16,24,32,39,47,54,61,68,75,81,87,93,98,103,107,111,115,118,120,123,124,126,126,126,126,126,125,123,121,119,116,113,110,106,102,98,94,89,84,79,74,69,64,59,54,49,44,39,35,30,26,22,18,15,12,9,7,4,3,1,0,0,0,0,0,1,3,4,7,9,12,15,18,22,26,30,35,39,44,49,54,59,64,69,74,79,84,89,94,98,102,106,110,113,116,119,121,123,125,126,126,127,126,126,124,123,120,118,115,111,107,103,98,93,87,81,75,68,61,54,47,39,32,24,16,8,0,-8,-16,-24,-32,-39,-47,-54,-61,-68,-75,-81,-87,-93,-98,-103,-107,-111,-115,-118,-120,-123,-124,-126,-126,-127,-126,-126,-125,-123,-121,-119,-116,-113,-110,-106,-102,-98,-94,-89,-84,-79,-74,-69,-64,-59,-54,-49,-44,-39,-35,-30,-26,-22,-18,-15,-12,-9,-7,-4,-3,-1,0,0,0,0,0,-1,-3,-4,-7,-9,-12,-15,-18,-22,-26,-30,-35,-39,-44,-49,-54,-59,-64,-69,-74,-79,-84,-89,-94,-98,-102,-106,-110,-113,-116,-119,-121,-123,-125,-126,-126,-126,-126,-126,-124,-123,-120,-118,-115,-111,-107,-103,-98,-93,-87,-81,-75,-68,-61,-54,-47,-39,-32,-24,-16,-8]
[15,14,13,12,11,10,9,8,7,6,5,4,3,2,1] => [0,32,63,89,109,122,126,124,114,100,82,62,43,26,13,4,0,0,3,9,16,24,30,35,37,36,33,27,21,14,8,3,0,-1,0,2,6,10,15,18,21,21,21,18,15,10,6,2,0,-1,-1,0,1,5,8,11,13,15,15,14,11,8,5,2,0,-1,-2,-1,0,1,4,6,9,10,11,11,9,7,5,2,0,-1,-2,-3,-2,0,1,3,6,7,8,9,8,6,4,2,0,-1,-3,-3,-3,-2,0,1,3,5,6,7,7,6,4,2,0,-2,-3,-4,-4,-4,-2,0,1,3,4,5,5,5,4,2,0,-2,-4,-5,-5,-5,-4,-3,-1,0,2,4,4,4,3,2,0,-2,-4,-6,-7,-7,-6,-5,-3,-1,0,2,3,3,3,1,0,-2,-4,-6,-8,-9,-8,-7,-6,-3,-1,0,2,3,2,1,0,-2,-5,-7,-9,-11,-11,-10,-9,-6,-4,-1,0,1,2,1,0,-2,-5,-8,-11,-14,-15,-15,-13,-11,-8,-5,-1,0,1,1,0,-2,-6,-10,-15,-18,-21,-21,-21,-18,-15,-10,-6,-2,0,1,0,-3,-8,-14,-21,-27,-33,-36,-37,-35,-30,-24,-16,-9,-3,0,0,-4,-13,-26,-43,-62,-82,-100,-114,-124,-127,-122,-109,-89,-63,-32]
[3,5,7,11,13,17,23]                   => [0,47,88,115,126,123,107,86,65,48,38,35,36,38,38,35,29,21,14,12,14,22,32,40,45,43,34,20,3,-10,-19,-22,-17,-10,-2,0,-3,-14,-30,-48,-60,-64,-56,-36,-7,22,49,66,70,60,40,14,-11,-31,-42,-44,-38,-29,-20,-14,-12,-14,-19,-23,-25,-23,-19,-14,-12,-14,-20,-29,-38,-44,-42,-31,-11,14,40,60,70,66,49,22,-7,-36,-56,-64,-60,-48,-30,-14,-3,0,-2,-10,-17,-22,-19,-10,3,20,34,43,45,40,32,22,14,12,14,21,29,35,38,38,36,35,38,48,65,86,107,123,126,115,88,47,0,-47,-88,-115,-126,-123,-107,-86,-65,-48,-38,-35,-36,-38,-38,-35,-29,-21,-14,-12,-14,-22,-32,-40,-45,-43,-34,-20,-3,10,19,22,17,10,2,0,3,14,30,48,60,64,56,36,7,-22,-49,-66,-70,-60,-40,-14,11,31,42,44,38,29,20,14,12,14,19,23,25,23,19,14,12,14,20,29,38,44,42,31,11,-14,-40,-60,-70,-66,-49,-22,7,36,56,64,60,48,30,14,3,0,2,10,17,22,19,10,-3,-20,-34,-43,-45,-40,-32,-22,-14,-12,-14,-21,-29,-35,-38,-38,-36,-35,-38,-48,-65,-86,-107,-123,-127,-115,-88,-47]
[1,1,2,3,5,8,13,21,34]                => [0,52,88,99,90,75,68,73,84,92,88,74,60,56,67,87,104,104,85,55,30,25,43,73,101,112,105,85,66,57,58,59,51,34,14,4,15,46,87,118,127,112,84,60,50,56,68,73,64,45,27,18,23,32,36,24,1,-21,-28,-11,26,70,103,114,103,83,66,61,63,63,53,34,13,4,13,36,59,68,54,23,-8,-27,-24,-6,14,23,15,-2,-20,-28,-25,-19,-21,-34,-52,-62,-51,-17,31,77,103,104,88,68,57,60,69,74,67,49,32,24,31,45,54,47,23,-7,-29,-29,-6,26,55,64,54,32,12,1,0,-1,-12,-32,-54,-64,-55,-26,6,29,29,7,-23,-47,-54,-45,-31,-24,-32,-49,-67,-74,-69,-60,-57,-68,-88,-104,-103,-77,-31,17,51,62,52,34,21,19,25,28,20,2,-15,-23,-14,6,24,27,8,-23,-54,-68,-59,-36,-13,-4,-13,-34,-53,-63,-63,-61,-66,-83,-103,-114,-103,-70,-26,11,28,21,-1,-24,-36,-32,-23,-18,-27,-45,-64,-73,-68,-56,-50,-60,-84,-112,-126,-118,-87,-46,-15,-4,-14,-34,-51,-59,-58,-57,-66,-85,-105,-112,-101,-73,-43,-25,-30,-55,-85,-104,-104,-87,-67,-56,-60,-74,-88,-92,-84,-73,-68,-75,-90,-99,-88,-52]

```

# Additional Rules

All component frequencies are to begin at 0° phase. Basically, that means that they should start at 0 proceed to +127 at 90°, 0 again at 180°, -127 at 270° and then back to 0 at 360°.

It is acceptable if your outputs are slightly different due to rounding, from the examples posted here. They should be normalized to fill (or nearly fill) the range of possible signed ints (-128..127).

The usual loopholes are prohibited.

This is , shortest code wins.

# IMPORTANT!

Practically everybody has made the same mistake in this challenge. 128 is NOT a valid signed 8 bit integer. You should not have output that contains this number or any number over 128.

# Answer
# Jelly, ~~23~~ 28 bytes

```
Ṁ1Ṁ?
⁹Ḷµ×³×ØP÷⁹ḤÆSSµ€µ×127:Ç

```

Try it online!

*+5 bytes for handling input \[\]*

All rounding errors are within +/- 2.

**How it works**

```
Ṁ1Ṁ?  - helper link, returns the maximum of a list unless the maximum is 0, where it returns 1
  Ṁ?  - if the maximum is truthy:
Ṁ     - return the maximum. Else:
 1    - return 1.

⁹Ḷµ×³×ØP÷⁹ḤÆSSµ€µ×127:Ṁ - main link, nilad
⁹Ḷ                      - the literal [0,1,2,3,...,254,255]
  µ           µ€        - compute the relative amplitude for each using the chain:
   ×³                   - multiply each element frequency by x
     ×ØP÷⁹Ḥ             - scale because the sine function uses degrees.
           ÆS           - take the sine
             S          - return the sum of the list of sines of component waves.
                µ×127:Ç - scale to 127, with divison by 0 handled by the helper link

```
> 3 votes

# Answer
# Python 3, 119 bytes

```
from math import*
def f(a):b=[sum(sin(m*i*pi/128)for m in a)for i in range(256)];return[127*x//(max(*b)or 1)for x in b]

```

Try it online!
> 3 votes

# Answer
# MATL, 34 bytes

```
Oh!8W:q7W/YP**Y,XstX:X>|a?1M/127*k

```

Try at MATL online!. Or add code `XG` to see a plot.
> 2 votes

# Answer
# Mathematica, 75 bytes

```
(m=MaxValue[f=Tr[Sin[x/128Pi#]&/@#],x]+.1^9;Round[127f/m]~Table~{x,0,255})&

```

Try the code online at https://sandbox.open.wolframcloud.com.

Explanation:

```
            f=Tr[Sin[x/128Pi#]&/@#]                                         Define expression f contains variable x equal to the frequency
                                                                               as x runs from 0 to 256 (x/128Pi runs from 0 to 2Pi)
 m=MaxValue[                       ,x]                                      Find the maximum of f
                                      +.1^9                                 Avoid case of empty list when m=0
                                            Round[127f/m]                   Normalize value of f to correct range
                                                         ~Table~{x,0,255}   and make a table of the value.

```

Notes:

1. Using `MaxValue` instead of `NMaxValue` may have some symbolic issues, which is displayed as warning.
2. It can be proved that the function have `MaxValue + MinValue == 0`, so it is not necessary to calculate `MinValue`.
3. To run the code, put `[{1,3}]` for example after the code for input `{1,3}` and press `Shift+Enter` on Wolfram Sandbox.
4. Although the code produce exact result, it is not mathematically correct due to the bad way of handle empty input case. This version (**78 bytes**) is better.

---

```
(m=MaxValue[f=Tr[Sin[x/128Pi#]&/@#],x];Round[127f/m]~Table~{x,0,255}/.0/0->0)&

```

or (**80 bytes**)

```
(m=MaxValue[f=Tr[Sin[x/128Pi#]&/@#],x];If[m<1,0,Round[127f/m]]~Table~{x,0,255})&

```

This works because it can be proven that the maximum is at least 1 for all non-empty input.
> 1 votes

# Answer
# TI-BASIC, ~~47~~ ~~41~~ 48 bytes

*-6 thanks to @Octopus*

*+7 for handling `0`*

```
:Prompt Y                         //Get list of inputs, 3 bytes
:"sum(sin(XʟY→Y₁                  //Store sum of sines function to Y₁, 10 bytes
:Y₁(128ֿ¹πseq(B,B,0,255           //Use the function to compute the values at 256 points, 20 bytes
:iPart(127Ans/max({1ᴇ~9,max(Ans   //Normalize values and round, 8 bytes

```

This will not work for empty input, since **TI-BASIC** will never accept empty input (see here).

**GIF:**
> 1 votes

# Answer
# Perl 6, 101 bytes

```
{my @w=[Z+] |(0 xx 256 xx 2),|.map:
(^256 »/»(128/π/*))».sin;(@w »*»(127/(@w.max||1)))».floor}

```

The frequencies are taken from the single list passed to this anonymous function.
> 1 votes

# Answer
# Ruby, 102 bytes

```
->r{(o=(0..255).map{|i|r.sum{|n|Math::sin(0.024544*i*n)}}).map{|f|(f*127/[1,*o].map(&:abs).max).to_i}}

```

Try it online!

I know this is a slightly old one, but it looked like fun. The margin of error (for the given tests, anyway) is within ±1.
> 1 votes

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


# Question
Title: Several bases but not twice the same digit
## Input

A non-empty array of positive integers.

## Task

Convert each integer to either binary, octal, decimal or hexadecimal in such a way that each digit (**0** to **F**) is used at most once.

## Output

The list of bases that were used to solve the puzzle.

## Detailed example

The expected output for **\[ 16, 17 \]** is **\[ octal, decimal \]**.

Here is why:

* We can't simply use decimal for both numbers, because they both contains a **1**.
* **16** cannot be converted to binary, because its representation in this base (**10000**) contains several **0**'s.
* **17** cannot be converted to binary either, because its representation in this base (**10001**) contains several **0**'s and several **1**'s.
* **17** cannot be converted to hexadecimal, because its representation in this base (**11**) consists of two **1**'s.
* Let's consider all remaining possibilities:

```
               +---------+---------+--------+
               | oct(16) | dec(16) | hex(16)|
               | = 20    | = 16    | = 10   |
+--------------+---------+---------+--------+
| oct(17) = 21 | 20,21   | 16,21   | 10,21  |
| dec(17) = 17 | 20,17   | 16,17   | 10,17  |
+--------------+---------+---------+--------+

```

The only possible solution is to convert **16** in octal (**20**) and to keep **17** in decimal (**17**). This way, the digits **0**, **1**, **2** and **7** are used exactly once.

## Clarifications and rules

* **The input is guaranteed to lead to a unique solution.** Your code is not supposed to support arrays that give several solutions or no solution at all.
* You may output the bases in any reasonable format, such as **\[ "bin","oct","dec","hex" \]**, **\[ 'b','o','d','h' \]**, **"BODH"**, **\[ 2,8,10,16 \]**, **\[ 0,1,2,3 \]** etc. But it should be clearly explained in your answer.
* The order of the bases in the output must match the order of the input integers.
* If that helps, you may assume that the input is sorted from lowest to highest, or from highest to lowest.
* This is , so the shortest answer in bytes wins!

## Test cases

You do not have to output the conversion results listed below. They are purely informational.

```
Input                                  | Output          | Conversion result
---------------------------------------+-----------------+------------------------
[ 119 ]                                | O               | 167
[ 170 ]                                | D               | 170
[ 64222 ]                              | H               | FADE
[ 16, 17 ]                             | O/D             | 20/17
[ 14, 64, 96 ]                         | H/H/D           | E/40/96
[ 34, 37, 94 ]                         | O/D/H           | 42/37/5E
[ 2, 68, 82 ]                          | B/D/H           | 10/68/52
[ 22, 43, 96 ]                         | O/O/O           | 26/53/140
[ 3639, 19086, 57162 ]                 | H/D/H           | E37/19086/DF4A
[ 190, 229, 771 ]                      | O/H/O           | 276/E5/1403
[ 2, 44, 69, 99 ]                      | B/H/H/H         | 10/2C/45/63
[ 75, 207, 218, 357, 385 ]             | H/H/H/D/O       | 4B/CF/DA/357/601
[ 12, 28, 46, 78, 154, 188, 222, 240 ] | D/O/O/D/H/H/H/H | 12/34/56/78/9A/BC/DE/F0

```

The raw input list **is available here**.

# Answer
> 4 votes
# JavaScript (Node.js),192,155,154,152,151,145,136,113,99,92 90 bytes

* thanks to @Arnauld for reminding me that i can return \[0,1,2,3\] -\> which is \[2,8,10,16\] saves 8 bytes, and for the brilliant idea (which help to reduce by 23+ bytes)
* thanks to @Kevin Cruijssen for reducing by 1 bytes

```
f=([c,...a],t="")=>c?[1,4,5,8].find(b=>T=!/(.).*\1/.test(n=t+c.toString(b*2))&&f(a,n))+T:a

```

Try it online!

# Explanation:

`[c,...a]` \- @Arnauld trick for taking one item at a time `c?***:" "` -\>if c is undefined we managed to get to the end result- \[\] - if i would put "" than the find would not considered that legit. (\[\]+5="5" JS FTW) `[1,4,5,8].find` every time we find the correct base (the output will be of this array (1,4,5,8)-\>(2,8,10,16) its legit. now how the find works -\> if it finds something it returns the element (1-8) and than i add the result of the inner solution. if it doesnt find then it returns undefined + T is now false -\> NaN which in the parent call will be considered false

`!/(.).*\1/.test(n=t+b)` determine if the string has duplicates, if so:

`f(a,n))` just go the the next number(a is now array.slice(1)) with the new string(n)

we assign result to T(temp) of the result because find stops when it finds and so we know that the last result will be f() which is result B

# Answer
> 3 votes
# Perl 5 `-alp`, 55 bytes

Uses `%x` for hex, `%d` for decimal, `%o` for octal and `%b` for binary

```
#!/usr/bin/perl -alp
($_)=grep{sprintf($_,@F)!~/(.).*\1/}glob"%{d,o,b,x}"x@F

```

Try it online!

# Answer
> 3 votes
# Ruby, ~~72~~ 71 bytes

```
->a{a.map{%w[b o d x]}.inject(&:product).find{|c|/(.).*\1/!~[p,c]*?%%a}}

```

Output format is some kind of reverse S-expression monstrosity:

```
f[[12, 28, 46, 78, 154, 188, 222, 240]]
=> [[[[[[["d", "o"], "o"], "d"], "x"], "x"], "x"], "x"]

```

Slash-separating it instead would cost 3 more bytes (appending `*?/`).

This format comes from the loop structure, slightly shorter than the more idiomatic `repeated_combination(a.size)`, which generates an array of arrays of characters and then reduces it over the cross-product function.

Edit: Saved 1 byte thanks to Lynn.

# Answer
> 2 votes
# Jelly, ~~17~~ 16 bytes

```
⁴⁽%ʠḃṗL³bF⁼Q$ƲÐf

```

Try it online!

Return a list of bases.

```
 == Explanation ==
⁴⁽%ʠḃṗL³bF⁼Q$ƲÐf  Main link.
 ⁽%ʠ              A number.
    ḃ             convert it to bijective base...
⁴                   16. The result is [2,8,10,16].
     ṗL           Cartesian power by the input length.
             ƲÐf  Filter, keep those that satisfies...
       ³            the input
        b           convert to that base
         F          when flatten (join all the digits of \
                      different numbers together)
          ⁼Q$       equal to itself uniquified.

```

# Answer
> 2 votes
# Pyth, ~~21~~ 20 bytes

```
f{Is.bjYNTQ^[8T2y8)l

```

Returns a list of all possible lists of bases (which always has length 1).
Try it here

### Explanation

```
f{Is.bjYNTQ^[8T2y8)l
           ^[8T2y8)lQ  Get the tuples of bases of the same length as the input.
f                      Filter to get those...
    .bjYNTQ            ... where converting bases elementwise...
   s                   ... and joining together...
 {I                    ... has no repeats.

```

# Answer
> 2 votes
# Wolfram Language (Mathematica), 71 bytes

```
Cases[2{1,4,5,8}~Tuples~Tr[1^#],b_/;UnsameQ@@Join@@IntegerDigits[#,b]]&

```

Return a list of bases.

Try it online!

# Answer
> 2 votes
# Python 2, 128 bytes

```
from itertools import*
a=input()
for b in product(*['bdxo']*len(a)):
 s=''.join(map(format,a,b))
 if len(s)==len(set(s)):print b

```

Try it online!

# Answer
> 2 votes
# 05AB1E, 17 bytes

```
2žv8T)sgãʒIsв˜DÙQ

```

Try it online!

# Answer
> 2 votes
# Python 2, ~~121~~ ~~117~~ ~~113~~ 111 bytes

```
def f(a,d='',s=''):
 if a:
	for c in'bodx':t=format(a[0],c)+s;len(t)-len(set(t))or f(a[1:],d+c,t)
 else:print d

```

Try it online!

Tip of the hat to Lynn for `format`, which I had forgotten!

# Answer
> 1 votes
# Husk, 19 bytes

```
fȯS=UΣz`B¹πmDd1458L

```

Try it online!

Returns lists of bases

### Explanation

```
fȯS=UΣz`B¹πmDd1458L  Implicit input
                  L  Length of input
          π          Cartesian power of
             d1458     The digits of 1458  [1,4,5,8]
           mD          Double the digits   [2,8,10,16]
fȯ                   Filter by
      z`B¹             Zip with input by converting to its base
     Σ                 Concatenate
  S=U                  Equal to itself with unique elements

```

---
Tags: code-golf, base-conversion
---