title: Sum in 2540 sums

text:
# Question
Title: Sum in 2540 sums
This is my attempt to pair with .

You need to write a full program or function that sums all codepoints of the input string. If there is no input, you can output any number, including `0`.

## Rules

* The input will always be in printable ASCII.
* The sum of the codepoints of your source must be exactly 2540.

+ If your language uses its own code page, you should use it to calculate your program's codepoints.
    + If you used Unicode in your code you *have* to use Unicode bytes to calculate your program's length.
* Null bytes (which don't contribute to your codepoint sum) are banned.
* The program must **not** work with any consecutive substring removed.
* The conversion of codepoints are required.
* This is . Your score is the length of your source code, the shorter being better.

# Answer
> 10 votes
# Python 3, ~~11 10~~ 9 bytes

*Thanks @MariaMiller for finding the right Unicode character, saving 1 byte!*

```
ࠂ,=sum,

```

Try it online!

This is essentially just `sum`, padded with extra characters to reach the sum of `2540`. Usage is `ࠂ(s)` where `s` is a byte string (which acts like both string and integer array). Feels kinda cheaty, but ¯\\\_(ツ)\_/¯.

The first character in source code is the Unicode character with codepoint `2050` (Samaritan letter Gaman). This character might not be displayable depending on your browser.

---

The previous solution is longer but has nice Unicode characters:

**11 bytes**

```
ϕ,ϴ=sum,9

```

Try it online!

# Answer
> 12 votes
# Haskell, 25 bytes

```
b~zw=sum(fromEnum`map`zw)

```

Try it online!

The `~` is not an infix operator, but a marker for a lazy pattern match on argument `zw` of `b`, while conveniently being the largest-valued ASCII character at 126. The infix-ized ``map`` is also used because the backtick has a large ASCII value of 96. With both of these, we can avoid any spaces or other whitespace, which have low ASCII values.

The dense 24-byter

```
z~zz=sum$fromEnum`map`zz

```

comes just short in its sum of 2525, 15 too small. Its average ASCII value is 105.21, with the only values below 97 (for `a`) being `=` at 61, `$` at 36, and `E` at 69. An improvement would like involve finding an alternative for one of these.

(Non-ASCII characters can surely do better by having higher character values, but I'm not doing that because this is more interesting.)

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

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

```

Try it online!

## Explanation

First the observations I made my first time around (that solution and its explanation is below) continue to be important here. We need and even number of `()` pairs for a valid answer.

This time however we are going to use a starting program that already has an even number of `()`s.

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

```

This program first increments every element by 1 then calculates the sum of 1 less than every element. If we look at all possible ways to delete from this without causing a bracket mismatch here are what they do:

```
{(()<>)<>}<>({{}[()]}) # Never halts
{({}<>)<>}<>({{}[()]}) # Sums 1 less than every element
{({}())<>}<>({{}[()]}) # One more than above
{({}()<>)}<>({{}[()]}) # Never halts
{({}()<>)<>}({{}[()]}) # No output
{({}()<>)<>}<>({[()]}) # Never halts
{({}()<>)<>}<>({{}[]}) # Complex output still incorrect
{(<>)<>}<>({{}[()]})   # Never halts
{({})<>}<>({{}[()]})   # Sums 1 less than every element
{({}()<>)<>}<>({{}})   # Sums 1 more than every element
{()<>}<>({{}[()]})     # Sums 1 less than every element
{({}()<>)<>}<>({})     # Adds 1 to every element
{<>}<>({{}[()]})       # Sums 1 less than every element
{({}()<>)<>}<>()       # Adds 1 to every element
{}<>({{}[()]})         # Outputs 0
{({}()<>)<>}<>         # Adds 1 to every element
<>({{}[()]})           # Outputs 0
{({}()<>)<>}           # Outputs nothing
({{}[()]})             # Sums 1 less than every element

```

So this is a good starting place. To make it the correct sum I use the same method I outlined for the first attempt.

> Now we just need the proper combination of `[..]`s `<..>`s and `((..){}){}`s to hit 2540. Unfortunately while `[..]`s would be ideal seeing as they have the highest codepoint average I can't seem to get it to work with any of them present.

This time we are luckier and the winning combination is `<[[[..]]]>`.

# Brain-Flak, 34 bytes

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

```

Try it online!

## Explanation

The code that does the task is `({{}})`. But we need to pad it to 2540. The main issue is that apart from `()` every pair has an even total. This means we need and even number of `()` pairs, and at the same time our starting code uses only 1 `()` pair.

On top of this unlike `[]` or `<>` `()` pairs are not so easy to add. The one way we can do that is to wrap the entire program in `(..){}`, so to rectify our issue we alter the base program to

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

```

Now we just need the proper combination of `[..]`s `<..>`s and `((..){}){}`s to hit 2540. Unfortunately while `[..]`s would be ideal seeing as they have the highest codepoint average I can't seem to get it to work with any of them present. The one that works is the one used above.

# Answer
> 4 votes
# C# (Visual C# Interactive Comρiler), 13 bytes

I *had* to abuse the IO so that C# can be comρetitive once in its entire existence. Takes char codes as `int`s as inρut. To make this seem less terrible, this acceρts any `IEnumerable<int>` instead of only an array.

```
ρ=>ρ.Sum();

```

Try it online!

Alternatively, for less byte savings (30 bytes):
This includes the most descriptive variable name ever on this website.

```
strS=>strS.Select(p=>+p).Sum()

```

Try it online!

# Answer
> 3 votes
# 05AB1E, 17 bytes

```
žĆs"þþþþþx"g6QôkO

```

Try it online!

This was made by Kevin Cruijssen.

## Explanation

```
žĆ                # Push codepage
  s               # Swap
   "þþþþþx"       # Push a string of length 6
           g      # Get the length of the string (6)
            6Q    # And compare it with 6 (True -> 1)
              ô   # Split into chunks
               k  # Index into the codepage
                O # Sum

```

# Original idea, ~~63~~ ~~48~~ ~~36~~ 29 bytes

-15 bytes by using `1!` and replacing the `!`.

-12 bytes by dropping the factorial entirely, and using  instead of `1`.

-7 bytes by using `тн` and replacing the `н`. I'm not sure if this is allowed though, because with no input, it just outputs 49.

```
тžĆ"ʒʒʒʒʒʒʒʒʒʒKþþþ"gè.VôžĆskO

```

Try it online!

## Explanation

```
т                             # Push 100
 žĆ                           # Push the codepage
   "ʒʒʒʒʒʒʒʒʒʒKþþþ"           # Push a string of length 14
                   g          # Get the length of the string
                    è         # Index into the codepage (н)
                     .V       # Run н (first digit of 100)
                       ô      # Split into chunks of 1
                        žĆ    # Push codepage
                          s   # Swap with input
                           k  # Find each char in codepage
                            O # Sum

```

# Answer
> 3 votes
# brainfuck, ~~41~~ 39 bytes

(I haven't tested exhaustively)
Uses 3 strategies for wasting the codepoint sum: repeating all `<` and `>`, nesting the innermost `[` and `]` unneccessarily, and adding and later removing the same number to/from the output.

Runs in an interpreter with large cells and wrapping/bidirectional memory, which TIO isn't :(. Outputs by charcode.

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

```

# Answer
> 3 votes
# Java (JDK), 25 bytes

```
Ƌ->Ƌ.codePoints().sum()

```

Try it online!

All alternatives I tried failed:

```
s->s.chars().sum() // Function<String,Integer>
s->s.sum()         // Function<IntStream,Integer>
java.util.stream.IntStream::sum
...

```

# Answer
> 2 votes
# Python 3, 26 bytes

```
lambda ŏ:sum(ŏ.encode())

```

Try it online!

---

# Python 2, 28 bytes

```
lambda	eZ:sum(bytearray(eZ))

```

Try it online!

# Answer
> 2 votes
# Python 2, 28 bytes

```
lambda	zva:sum(map(ord,zva))

```

Try it online!

Uses a tab after the `lambda`.

# Answer
> 2 votes
# Ruby `-nl`, ~~28~~ 26 bytes

-2 bytes from GB.

```
p $_.chars.sum{|ay|ay.ord}

```

Try it online!

# Answer
> 2 votes
# Perl 5, 29 bytes

```
for(split//,<>){$u+=ord}say$u

```

Try it online!

# Answer
> 2 votes
# PHP, 35 bytes

```
FOR(;$zz=$argn[$u++];)$a+=ORD($zz);

```

Try it online!

OK I'm cheating a little bit here, but the shorter code I found for PHP having too much codepoints sum already (2549), I'll interpret the question in a litteral sense:

* "program or function that sums all codepoints of the input string" -\> it is not said I have to display the result, above code actually sums it :D (yeah I know, implicit rules.. well!)
* "you can output any number, including 0" -\> well I can, but if not forced to, I won't :P

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

```
A[J_]:=Tr@ToCharacterCode[J]

```

Try it online! Defines a named function `A` that takes a string as input and returns the sum of its ASCII codepoints. `ToCharacterCode` converts a character to its codepoint (and outputs a list of codepoints when fed a string of characters) and `Tr` sums them.

# Answer
> 1 votes
# GolfScript, 28 bytes

```
'zzzzzzzzzzzh'+{}/]{+}*1446-

```

Try it online!

# Answer
> 1 votes
# APL (Dyalog Unicode), 15 bytes

```
üüd←⎕UCS⍞⋄+/üüd

```

Try it online!

A full program that takes a single line from STDIN as input.

The ASCII characters are shuffled around within the default codepage (along with APL symbols and accented characters), and many useful characters appear at the high half (character value \> 128). Accented characters are valid to use in an identifier, and `ü` has the highest character value among them.

This code achieves "The program must not work with any consecutive substring removed" by separating the Unicode conversion `⎕UCS` and sum `+/` into two statements.

The character  alone is *over nine thousand* (pun intended) in Unicode, so APL can't compete using Unicode scoring.

### How it works

```
üüd←⎕UCS⍞⋄+/üüd
        ⍞        ⍝ Take a line of input from stdin
    ⎕UCS         ⍝ Convert to Unicode codepoints
üüd←             ⍝ Assign to variable
         ⋄       ⍝ Statement separator
          +/üüd  ⍝ Sum

```

# Answer
> 1 votes
# Python, 30 bytes

Works in Python 2 and 3.

```
lambda abZ:(sum(map(ord,abZ)))

```

Try it online!

Alternative 30-byter:

```
lambda aN,b=ord:sum(map(b,aN))

```

Try it online!

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

```
Ă=>eval(Buffer(Ă).join`+`)

```

Try it online!

Submission only works on ASCII. Although it source code contains non-ASCII.

This one based on code by Arnauld.

---

# JavaScript (Node.js), 31 bytes

```
s=>Buffer(s).map(c=>w+=c,w=0)|w

```

Try it online!

---

Another trivial one.

# Answer
> 1 votes
# Red, 37 bytes

```
func[-][!: 0 forall -[!: ADD ! -/1]!]

```

Try it online!

Nothing original. `-` is the input string, `!` is the sum. For each character in the input string I add its value to the sum. Red is case insensitive, so I use `ADD` instead of `add` (and isntead of the `+` operator) in order to match 2540. `forall` iterates over the entire series (list) and at each iteration returns the remaining series - just like `cdr` in LISP or `rest` in Racket. That's why I use `/1` to obtain the first element in the series.

# Answer
> 1 votes
# Charcoal, 15 bytes

```
ＩΣＥＳ⁺⊗⊗⊗⊗ＬPP⌕γι

```

Try it online! Link is to verbose version of code. Only works on printable ASCII, so I can't feed it its own source code, even if I could create it in the right code page. Explanation:

```
   Ｓ            Input string
  Ｅ             Map over characters
              ι Current character
            ⌕   Find index in
             γ  Printable ASCII
    ⁺           Plus
          PP    Literal string `PP`
         Ｌ      Length
     ⊗⊗⊗⊗       Doubled four times
 Σ              Take the sum
Ｉ               Cast to string
                Implicitly print

```

Hex dump in Charcoal's code page:

```
C9 91 C5 D3 AB 9E 9E 9E 9E CC 50 50 9B E7 E9

```

# Answer
> 1 votes
## Common Lisp, 42 bytes

```
(LAMBDA(%)(APPLY'+(MAP'CONS'CHAR-CODE %)))

```

This was found by trial and error using the following test: basically the code is printed to string, with some spaces removed (but not all, otherwise it parses badly), then it is read back to lisp and evaluated with its own representation.

```
(let ((string (remove #\space
                      (princ-to-string
                       '(lambda(%)(apply'+(map'cons'char-code %))))
                      :count 6)))
  (values string
          (funcall (eval (read-from-string string)) string)))

```

This returns both the code as string, and its sum:

```
"(LAMBDA(%)(APPLY'+(MAP'CONS'CHAR-CODE %)))"
2540

```

Usually you call `map` as follows, `(map 'list function sequence)`, where `list` is the type of result you want to build with map. Any Lisp type can be given, but obviously it should be a sequence. Here I used `cons` (lists are made of cons cells) to change the count, but the consequence if that is that there will be an error if the input is an empty sequence, since it cannot be expressed as a cons cell.

# Answer
> 1 votes
# Ruby, ~~19~~ ~~13~~ 12 bytes

```
->΃{΃.sum}

```

Try it online!

The weird char probably isn't displayed, so it's ASCII 899.

# Answer
> 0 votes
# \>\<\>, 22 bytes

```
"̛̜"-&57i:&+&1+?.&n;

```

Try it online!

Contains two two-byte unicode characters, which can't be removed since they are used to set the initial value of the accumulator. Relies on the official interpreter's quirk of normalizing jump coordinates back to 0 if they are outside the code box (for parity).

---
Tags: code-golf, restricted-source, code-shuffleboard
---


# Question
Title: Convert Brainfuck to a Non-Golfing Language
### Input:

**Any** Brainfuck program. This includes brainfuck programs with comments such as `+++COMMENT[>+++<-].`.

### Output:

A program in one of the below languages that produces the same output as the Brainfuck program on **all inputs**. It should produce the same output exactly as the interepreter on this website There are no or performance restrictions on the **output program**; the outputted program doesn't need to be optimized in any way. In other words, the quality of the outputted program does not affect score, only the translation program. To clarify: you may write **your answer** in any language that is normally valid for answers on PCG. The restriction on output languages is **only for the outputted program.**

The outputted program **only receives the same input that would be received by the Brainfuck** program. The outputted program **does not receive the Brainfuck program as input**.

### Valid Output Languages

* C#
* C++
* C
* Java 8
* Javascript ES6 (it is both okay to receive all of stdin in a single prompt, or multiple prompts per character)
* Perl
* Python 2.7
* Python 3.4.2
* Ruby

### Fine Print

You may write a program or function which takes the Brainfuck program as a String argument or on STDIN or closest alternative, and which returns the output as a String or printing it to STDOUT (or closest alternative). You may optionally include a single trailing newline in the output.

Additionally, standard loopholes which are no longer funny are **banned**. You may not use external libraries or external data files, the code must be self contained.

This is , shortest program wins.

# Answer
> 5 votes
# K, ~~143~~ ~~129~~ 113 bytes

```
1!"}int a[99];int*p=a;main(){",,/{("p++;";"p--;";"*p++;";"*p--;";"*p=getchar();if(*p<0)*p=0;";"putchar(*p);";"while(*p){";"}";"")"><+-,.[]"?x}'

```

This is an extremely straightforward approach which generates C source code by emitting a preamble, a C snippet for each BF command and then a postscript. Non-BF characters are translated into empty strings in the concatenated output.

The translation into C is as follows:

* preamble: `int a[99];int*p=a;main(){`
* `>`: `p++;`
* `<`: `p--;`
* `+`: `*p++;`
* `-`: `*p--;`
* `,`: `*p=getchar();if(*p<0)*p=0;`
* `.`: `putchar(*p);`
* `[`: `while(*p){`
* `]`: `}`
* postscript: `}`

I suspect that there is room for improvement here by using more mangled abuses of C or compressing the C fragments.

The K part of the program by itself would look like the following, where `c` is the C translations of each BF instruction and `p` is the preamble/postscript:

```
1!p,,/{c"><+-,.[]"?x}'

```

Using the venerable BF string reverser program `>,[>,]<[.<]` as my test case I generate code which looks like the following after a bit of whitespace for readability:

```
int a[99];
int*p=a;

main(){
    p++;
    *p=getchar();if(*p<0)*p=0;
    while(*p){
        p++;
        *p=getchar();if(*p<0)*p=0;
    }
    p--;
    while(*p){
        putchar(*p);
        p--;
    }
}

```

## edit:

A few tweaks. Firstly, more compliant tape declaration as suggested by alexander-brett. The `int` part can be left off:

`int a[99];` -\> `a[1<<15];` (-1 byte)

Also, it seems that EOF behavior in BF can return 0, -1 or cause no change as a result of `,`. EOF=-1 seems to be what other solutions are going with, so for the sake of uniformity I will do the same:

`*p=getchar();if(*p<0)*p=0;` -\> `*p=getchar();` (-13 bytes)

Note that this means my string reverser program will choke if you simply cat it a file ending in EOF(!), but as above it seems to be fair.

The new complete 129 byte solution:

```
1!"}a[1<<15];int*p=a;main(){",,/{("p++;";"p--;";"*p++;";"*p--;";"*p=getchar();";"putchar(*p);";"while(*p){";"}";"")"><+-,.[]"?x}'

```

## edit 2, much, much later:

I randomly stumbled upon this old answer and, being older and wiser, realized there are several ways to make this shorter:

* exploit the fact that it's completely syntactically valid C to include semicolons after *every* fragment instead of just those who need them, and thus remove them from the lookup table entries.
* use the k5/k6 or oK dialects, which have overloads for `\` and `/` which split a string apart on a character or join a list of strings with a character, respectively, to use a more compact representation of the lookup table and accomplish the above.
* take advantage of the fact that find (dyadic `?`) in the above dialects naturally conforms to a listy right argument, and thus does not need an explicit lambda + each

The one downside is that in these dialects there is no "rotate" primitive, so we have to add the `"}"` suffix in a less elegant manner. The overall structure of our solution:

```
1!     p, ,/{c"><+-,.[]"?x}'   / old
,[;"}"]p,";"/c"><+-,.[]"?      / new

```

The complete (and now totally points-free!) solution:

```
,[;"}"]"a[1<<15];int*p=a;main(){",";"/("|"\"p++|p--|*p++|*p--|*p=getchar()|putchar(*p)|while(*p){|}|")"><+-,.[]"?

```

Which shaves us down to 113 bytes.

# Answer
> 4 votes
# Javascript (*ES7 Draft*), 170 bytes

Function which compiles BF source code into Javascript. The resulting code accepts input via `prompt()` and outputs via `alert()`, both one character at a time.

```
f=x=>'x=[i=0];'+[for(y of x)'z=x[i]|=0,x[i]'+'0++0--0,i++0,i--0,alert(String.fromCharCode(z))0=prompt().charCodeAt()0;for(;x[i];){x0}x'.split(0)['+-><.,[]'.indexOf(y)+1]]

```

The result is composed of:

Preamble: `x=[i=0];` \- Initializes `x` as an object to store memory cells and `i` as `0` for the initial index.

Each command is prefixed with: `z=x[i]|=0,x[i]` \- Forces undefined memory cells to 0, starts all commands with `x[i]` to reduce repetition in the translation map. Stores value at current index in `z`.

Each command is also seperated by `,` commas due to implicit casting of the array to a string.

Command translation map:

* `(unknown)` =\> empty string
* `+` =\> `++` \- increment value at `x[i]`
* `-` =\> `--` \- decrement value at `x[i]`
* `>` =\> `,i++` \- increment index pointer `i`
* `<` =\> `,i--` \- decrement index pointer `i`
* `.` =\> `,alert(String.fromCharCode(z))` \- alert character from value at `x[i]`
* `,` =\> `=prompt().charCodeAt()` \- store converted character code from prompt at `x[i]`
* `[` =\> `;for(;x[i];){x` \- Loop while value at `x[i]` is truthy (non-zero).
* `]` =\> `}x` \- End loop. Unused x appended to prevent errors from commas.

# Answer
> 4 votes
# Python 2, ~~250~~ 244 bytes

```
def B(b):
 I=0;print"from ctypes import*;R,p,c=[0]*9999,0,CDLL('libc.so.6')"
 for c in b:
     try:print' '*I+'p+=1|p-=1|R[p]+=1|R[p]-=1|c.putchar(R[p])|R[p]=c.getchar()|while R[p]!=0:|'.split('|')['><+-.,[]'.index(c)];I+=']&['.index(c)-1
     except:0

#first indentation level=space, 2nd indentation level=tab

```

(thks to @undergroundmonorail for helping me save 4 extra bytes)

The B function takes bf code as parameter and generates... a Python script.

Brainfuck's "tape" is seen a an array called R, which owns ~~32768~~ 9999 items, and the pointer is stored in a variable called p.

The lack of a native equivalent to C's getchar function in python forced me to load it using ctypes at runtime, which makes the generated script unusable on Windows (untested, I guess that a Windows version should load mscvrt.dll instead of libc.so.6)

## Example

The infamous 'hello world':

```
B('++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.')

```

Generates the following script:

```
from ctypes import*;R,p,c=[0]*9999,0,CDLL('libc.so.6')
R[p]+=1
R[p]+=1
R[p]+=1
R[p]+=1
R[p]+=1
R[p]+=1
R[p]+=1
R[p]+=1
R[p]+=1
R[p]+=1
while R[p]!=0:
 p+=1
 R[p]+=1
 R[p]+=1
 R[p]+=1
 R[p]+=1
 R[p]+=1
 R[p]+=1
 R[p]+=1
 p+=1
 R[p]+=1
 R[p]+=1
 R[p]+=1
 R[p]+=1
 R[p]+=1
 R[p]+=1
 R[p]+=1
 R[p]+=1
 R[p]+=1
 R[p]+=1
 p+=1
 R[p]+=1
 R[p]+=1
 R[p]+=1
 p+=1
 R[p]+=1
 p-=1
 p-=1
 p-=1
 p-=1
 R[p]-=1

p+=1
R[p]+=1
R[p]+=1
c.putchar(R[p])
p+=1
R[p]+=1
c.putchar(R[p])
R[p]+=1
R[p]+=1
R[p]+=1
R[p]+=1
R[p]+=1
R[p]+=1
R[p]+=1
c.putchar(R[p])
c.putchar(R[p])
R[p]+=1
R[p]+=1
R[p]+=1
c.putchar(R[p])
p+=1
R[p]+=1
R[p]+=1
c.putchar(R[p])
p-=1
p-=1
R[p]+=1
R[p]+=1
R[p]+=1
R[p]+=1
R[p]+=1
R[p]+=1
R[p]+=1
R[p]+=1
R[p]+=1
R[p]+=1
R[p]+=1
R[p]+=1
R[p]+=1
R[p]+=1
R[p]+=1
c.putchar(R[p])
p+=1
c.putchar(R[p])
R[p]+=1
R[p]+=1
R[p]+=1
c.putchar(R[p])
R[p]-=1
R[p]-=1
R[p]-=1
R[p]-=1
R[p]-=1
R[p]-=1
c.putchar(R[p])
R[p]-=1
R[p]-=1
R[p]-=1
R[p]-=1
R[p]-=1
R[p]-=1
R[p]-=1
R[p]-=1
c.putchar(R[p])
p+=1
R[p]+=1
c.putchar(R[p])
p+=1
c.putchar(R[p])

```

# Answer
> 3 votes
# Common Lisp & JavaScript - 425 bytes

**N.B.** *I am using the Parenscript library, so this is just for the fun.*

```
(defun b(i &aux(s(coerce i'list)))(labels((c()(do(r x)((or x(not s))(reverse r))(push(case(pop s)(#\>`(incf p))(#\<`(decf p))(#\+`(setf(aref a p)(1+#1=(or(aref a p)0))))(#\-`(setf(aref a p)(1- #1#)))(#\.`((ps:@ console log)((ps:@ *String from-char-code)#1#)))(#\,`(setf(aref a p)((ps:@(prompt)char-code-at)0)))(#\[`(loop until(= 0 #1#)do ,@(c))))(#\](setf x t)(go /))(t(go /)))r)/)))(ps:ps*`(let((a(make-array))(p 0)),@(c)))))

```

# Ungolfed

```
(defun bf(i)
  (let ((s (coerce i'list)))
    (labels((lbf ()
              (do(r x)((or x(not s))(reverse r))
                      (push (case (pop s)
                              (#\> `(incf p))
                              (#\< `(decf p))
                              (#\+ `(setf(aref a p)(1+(or (aref a p)0))))
                              (#\- `(setf(aref a p)(1-(or (aref a p)0))))
                              (#\. `((ps:@ console log)((ps:@ *String from-char-code) (or(aref a p)0))))
                              (#\, `(setf(aref a p) ((ps:@ (prompt) char-code-at) 0)))
                              (#\[ `(loop until(= 0(or(aref a p)0))do ,@(lbf)))
                              (#\] (setf x t) (go /))
                              (t (go /)))
                            r)/)))
      `(let ((a (make-array))
             (p 0))
         ,@(lbf)))))

```

# Explanations

* Convert input string as list of characters `s`
* The recursive function `lbf` pop elements from `s` and build a local list of expressions `r`
* Whenever we encounter a `[` character, the function recurse in order to create a nested block of instructions
* Whenever we encounter a `]` character, the function exits, returning to one higher level of invocation. Note that when returning from the function, the variable `s` has been modified to hold the rest of the characters to be processed, thanks to `pop`.
* The whole S-expr being built is expressed in a sub-language of Common Lisp that can be converted to Javascript thanks to Parenscript.

# Optimized version

I made a slightly optimized version that is too long to post here, with the following changes:

* Parsing only produces an AST containing the following symbols: `print`, `read`, `left`, `right`, `inc`, `dec`, `bracketed` (nested tree) and `brainfuck` (root tree).
* The AST is analyzed to group all increment and decrement operations, as well as move operations, in order to build `(add x)` and `(move y)` terms.
* Finally, the AST is converted into Parenscript code.
* That code is emitted as a Javascript string

The resulting Javascript for Hello World is:

```
(function () {
   var a = new Array();
   var p = 0;
   a[p] = (a[p] || 0) + 10;
   while (0 !== (a[p] || 0)) {
       ++p;
       a[p] = (a[p] || 0) + 7;
       ++p;
       a[p] = (a[p] || 0) + 10;
       ++p;
       a[p] = (a[p] || 0) + 3;
       ++p;
       a[p] = (a[p] || 0) + 1;
       p += -4;
       a[p] = (a[p] || 0) + -1;
   };
   ++p;
   a[p] = (a[p] || 0) + 2;
   console.log(String.fromCharCode(a[p] || 0));
   ++p;
   a[p] = (a[p] || 0) + 1;
   console.log(String.fromCharCode(a[p] || 0));
   a[p] = (a[p] || 0) + 7;
   console.log(String.fromCharCode(a[p] || 0));
   console.log(String.fromCharCode(a[p] || 0));
   a[p] = (a[p] || 0) + 3;
   console.log(String.fromCharCode(a[p] || 0));
   ++p;
   a[p] = (a[p] || 0) + 2;
   console.log(String.fromCharCode(a[p] || 0));
   p += -2;
   a[p] = (a[p] || 0) + 15;
   console.log(String.fromCharCode(a[p] || 0));
   ++p;
   console.log(String.fromCharCode(a[p] || 0));
   a[p] = (a[p] || 0) + 3;
   console.log(String.fromCharCode(a[p] || 0));
   a[p] = (a[p] || 0) + -6;
   console.log(String.fromCharCode(a[p] || 0));
   a[p] = (a[p] || 0) + -8;
   console.log(String.fromCharCode(a[p] || 0));
   ++p;
   a[p] = (a[p] || 0) + 1;
   console.log(String.fromCharCode(a[p] || 0));
   ++p;
   return console.log(String.fromCharCode(a[p] || 0));
})();

```

# Answer
> 3 votes
# QuadR, ~~106~~ ~~100~~ 99 bytes

**Edit:** finally below 100 bytes! -1 thanks to ceilingcat (`⌈,`)

Creates C code.

```
^
>
<
[+-]
\.
,
\[
]|$
a[1<<15];*p=a;main(){
p++;
p--;
&&*p;
putchar(*p);
read(0,p,1);
while(*p){
}

```

Try it online!

The first nine lines are PCRE regexes. Matches throughout the input are replaced with the corresponding string from the last 9 lines. The only noteworthy "hacks" are transpiling `[+-]` to `&&*p;` where `&` means the matched plus/minus symbol, and combining end-of-loop with end-of-main through mapping `]|$` to `}`

# Answer
> 2 votes
# Perl, ~~127~~ 120B + 2

```
%h=qw#> ++p;
< --p;
+ ++*p;
- --*p;
. putchar(*p);
, *p=getchar();
[ while(*p){
] }#;say"a[1<<15],*p=a;main(){@h{/./g}}"

```

The magic happens in `@h{/./g}`: `/./g` splits the input into characters, `@h{}` is a hash slice, and the `""` interpolation joins hash elements using a space (by default). The target is C using exactly the spec on the Brainfuck website. 2 point penalty for -0n: run with

```
perl -M5.10.0 -0n scratch.pl > test.c < input.bf && gcc -ansi test.c && ./a.out

```

7B saving thanks to CL- and the prevailing opinion on variable declarations.

# Answer
> 2 votes
# rs, 214 bytes

Outputs Ruby 1.9 code.

```
[^+\-[\]<>.,]/
\[/while tape[i
\]/end;
\[i/[i] != 0 do
\./print tape[i].chr;
if !defined?tape then require "io\x2Fconsole";tape=[0]*9999;i=0;end;
\+/tape[i]+=1;
-/tape[i]-=1;
</i+=1;
>/i-=1;
,/tape[i]=STDIN.getch;

```

Try it here!

## Sample runs

### Hello, world!

Input:

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

```

Output:

```
if !defined?tape then require "io\x2Fconsole";tape=[0]*9999;i=0;end;tape[i]+=1;tape[i]+=1;tape[i]+=1;tape[i]+=1;tape[i]+=1;tape[i]+=1;tape[i]+=1;tape[i]+=1;while tape[i] != 0 do i-=1;tape[i]+=1;tape[i]+=1;tape[i]+=1;tape[i]+=1;while tape[i] != 0 do i-=1;tape[i]+=1;tape[i]+=1;i-=1;tape[i]+=1;tape[i]+=1;tape[i]+=1;i-=1;tape[i]+=1;tape[i]+=1;tape[i]+=1;i-=1;tape[i]+=1;i+=1;i+=1;i+=1;i+=1;tape[i]-=1;end;i-=1;tape[i]+=1;i-=1;tape[i]+=1;i-=1;tape[i]-=1;i-=1;i-=1;tape[i]+=1;while tape[i] != 0 do i+=1;end;i+=1;tape[i]-=1;end;i-=1;i-=1;print tape[i].chr;i-=1;tape[i]-=1;tape[i]-=1;tape[i]-=1;print tape[i].chr;tape[i]+=1;tape[i]+=1;tape[i]+=1;tape[i]+=1;tape[i]+=1;tape[i]+=1;tape[i]+=1;print tape[i].chr;print tape[i].chr;tape[i]+=1;tape[i]+=1;tape[i]+=1;print tape[i].chr;i-=1;i-=1;print tape[i].chr;i+=1;tape[i]-=1;print tape[i].chr;i+=1;print tape[i].chr;tape[i]+=1;tape[i]+=1;tape[i]+=1;print tape[i].chr;tape[i]-=1;tape[i]-=1;tape[i]-=1;tape[i]-=1;tape[i]-=1;tape[i]-=1;print tape[i].chr;tape[i]-=1;tape[i]-=1;tape[i]-=1;tape[i]-=1;tape[i]-=1;tape[i]-=1;tape[i]-=1;tape[i]-=1;print tape[i].chr;i-=1;i-=1;tape[i]+=1;print tape[i].chr;i-=1;tape[i]+=1;tape[i]+=1;print tape[i].chr;

```

### Mandelbrot

Input:

```
      A mandelbrot set fractal viewer in brainf*** written by Erik Bosman
+++++++++++++[->++>>>+++++>++>+<<<<<<]>>>>>++++++>--->>>>>>>>>>+++++++++++++++[[
>>>>>>>>>]+[<<<<<<<<<]>>>>>>>>>-]+[>>>>>>>>[-]>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>[-]+
<<<<<<<+++++[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>>>+>>>>>>>>>>>>>>>>>>>>>>>>>>
>+<<<<<<<<<<<<<<<<<[<<<<<<<<<]>>>[-]+[>>>>>>[>>>>>>>[-]>>]<<<<<<<<<[<<<<<<<<<]>>
>>>>>[-]+<<<<<<++++[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>>+<<<<<<+++++++[-[->>>
>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>>+<<<<<<<<<<<<<<<<[<<<<<<<<<]>>>[[-]>>>>>>[>>>>>
>>[-<<<<<<+>>>>>>]<<<<<<[->>>>>>+<<+<<<+<]>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>
[>>>>>>>>[-<<<<<<<+>>>>>>>]<<<<<<<[->>>>>>>+<<+<<<+<<]>>>>>>>>]<<<<<<<<<[<<<<<<<
<<]>>>>>>>[-<<<<<<<+>>>>>>>]<<<<<<<[->>>>>>>+<<+<<<<<]>>>>>>>>>+++++++++++++++[[
>>>>>>>>>]+>[-]>[-]>[-]>[-]>[-]>[-]>[-]>[-]>[-]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>-]+[
>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<<<<<<[<<<<<<<<<]>>>[-]+>>>>>>[>>>>>>
>>>]>[-]+<]]+>[-<[>>>>>>>>>]<<<<<<<<]>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>[-]<<<++++
+[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>->>>>>>>>>>>>>>>>>>>>>>>>>>>-<<<<<<[<<<<
<<<<<]]>>>]

```

Output (I'm glad it isn't scored!) is available on Pastebin because it was too long to put here!

# Answer
> 2 votes
# Javascript (ES6), ~~202~~ ~~196~~ 192 bytes

Outputs C code. Tested with Node.js 14.7.0 and GCC 10.1.0.

Try it online

```
f=i=>"a[99];main(){int*p=a;"+Array.prototype.map.call(i,x=>({">":"p++","<":"p--","+":"++*p","-":"--*p","[":"while(*p){","]":"}",",":"read(0,p,1)||(*p=0)",".":"putchar(*p)"})[x]).join(";")+"}";

```

The only clever thing here is using `Array.map` on a string rather than an array. I expected this to be golfier than it was; the 24 characters for `Array.prototype.map.call` were brutal.

I copied some of the C code from nderscore's answer. As far as I can tell, the C is as golfed as it can be, other than perhaps the preamble. Potentially I could tease out some undefined behaviour to point `p` to somewhere lower down on the stack for fewer bytes than defining an array outright.

-6 bytes: replace `*p=getchar();if(*p<0)*p=0` with `read(0,p,1)||(*p=0)`. Thanks to ceilingcat -4 bytes: replace `(*p)++` and `(*p)--` with `++*p` and `--*p`. Thanks to Bubbler

---
Tags: code-golf, brainfuck, code-generation
---


title: The 1+ Metagolf Challenge

text:
# Question
Title: The 1+ Metagolf Challenge
I'm letting this one out of the sandbox. Hopefully it is well-written and make sense, feel free to improve.

So in order to make 1+ more popular (and ease the creation of golfed 1+ text-printing programs) here comes the metagolf challenge:

## The 1+ Language

1+ is a fun deque-based esolang where 1 is the only literal, and other numbers are constructed with operators

It is also "monotonic", that is, it only has the `+` and `*` operators, and not `-` or `/`

The deque is often referred to as a "stack", and one end of the deques is often referred to as the "top"

Here are the commands:

* `1` pushes 1
* `+` and `*` pop 2 numbers, and push their sum and product respectively
* `"` duplicates the top number
* `/` and `\` rotate the stack upwards and downwards respectively. That is, `/` moves the top number to the bottom and `\` does the exact reverse
* `^` swaps the top two numbers
* `<` is the only comparison operator (although it probably won't do much in Kolmogorov-complexity challenges)
* `.` and `,` input an integer and a Unicode character respectively, and push it onto the stack. You are not allowed to take input here
* `:` and `;` output an integer and a Unicode character respectively. In the original interpreter, the `:` command outputs with a trailing newline, but here we allow both with a trailing newline and without a trailing newline
* `#` is a goto-command that pops the top value n, and sends program flow to immediately after the nth # in the current line of execution (where numbering starts from 0)
* Functions are defined with `(name|code)` and are called with `(name)`. The name can be empty and the point where they are defined causes their execution too. They are separate lines of execution, so the numbering of #'s in them starts from 0

Original interpreter

Slightly modified interpreter to remove integer output trailing newline

## Challenge

Your challenge is to write a program that inputs some text and outputs a 1+ program that outputs the text. The program can be in any language (lesser-known ones preferably), but it must output valid programs for any text.

Do not golf the test cases manually, otherwise I'll change them.

## Winning criteria

Your score for a particular test case is your output length divided by the input length. The total score is the sum of the scores of all test cases. The lower, the better.

The test cases are:

1. "Hello, World!"
2. We're no strangers to code golf, you know the rules, and so do I
3. A keyboard so real you can almost TASTE it
4. Pascal's Tree-angle

# Answer
# JavaScript (Node.js),  ~~16.26 ... 12.30~~  12.19

## 8.31 + 1.13 + 0.91 + 1.84

*Saved 1.69 by optimizing the initial code, as suggested by @JoKing*
*Saved 1.31 by using a precomputed table of code snippets, as suggested by @Mukundan314*
*Saved 0.11 by counting the patterns more accurately, as suggested by @JoKing*

## Source

```
const CHAR_SET =
  " !\"#$%&'*+,-./0123456789:;<=>?@" +
  "ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`" +
  "abcdefghijklmnopqrstuvwxyz{}";

const CHAR_MAP = {
  10 : '11+1+"*1+',
  32 : '11+"*"*"+',
  33 : '11+"*"*"+1+',
  34 : '11+"*"*1+"+',
  35 : '11+"*1+"1+1+*',
  36 : '11+1+"+"*',
  37 : '11+1+"+"*1+',
  38 : '11+"1+"+"*+',
  39 : '11+1+""+"*+',
  40 : '11+"*"1+*"+',
  41 : '11+"*1+"1+"*+',
  42 : '11+1+"+"1+*',
  43 : '11+1+"+"1+*1+',
  44 : '11+"*"1+"+1+*',
  45 : '11+1+""1+1+**',
  46 : '11+1+""1+1+**1+',
  47 : '11+"*1+"1+"1+*+',
  48 : '11+1+"1+"**',
  49 : '11+1+"+1+"*',
  50 : '11+"*1+"*"+',
  51 : '11+1+"1+"*1+*',
  52 : '11+1+""+1+"*+',
  53 : '11+1+"1+1+"*"++',
  54 : '11+1+""**"+',
  55 : '11+1+"+"1+"*+',
  56 : '11+1+"+1+"1+*',
  57 : '11+1+""*"+1+*',
  58 : '11+"*"1+"*+"+',
  59 : '11+1+""+1+"1+*+',
  60 : '11+1+"1+"1+**',
  61 : '11+1+"1+"1+**1+',
  62 : '11+1+"+"1+"1+*+',
  63 : '11+1+"""+1+**',
  64 : '11+"*"+"*',
  65 : '11+"*"+"*1+',
  66 : '11+""*"+"*+',
  67 : '11+1+"1+"+"*+',
  68 : '11+"*""*1+*',
  69 : '11+"*""*1+*1+',
  70 : '11+""*""*1+*+',
  71 : '11+1+"+1+"1+"*+',
  72 : '11+1+"+"*"+',
  73 : '11+1+"+"*"+1+',
  74 : '11+1+"+"*1+"+',
  75 : '11+1+"1+1+"**',
  76 : '11+"*""+"1+*+',
  77 : '11+"1+"1+1+"**+',
  78 : '11+1+"+""+1+*',
  79 : '11+1+"+""+1+*1+',
  80 : '11+"*""1+**',
  81 : '11+1+"*"*',
  82 : '11+1+"*"*1+',
  83 : '11+"1+"*"*+',
  84 : '11+1+""*"*+',
  85 : '11+1+""*"*+1+',
  86 : '11+"1+""*"*++',
  87 : '11+1+"""*"*++',
  88 : '11+"*"+"1+1+1+*',
  89 : '11+"*"+"1+"*+',
  90 : '11+1+"*"1+*',
  91 : '11+1+"*"1+*1+',
  92 : '11+"1+"*"1+*+',
  93 : '11+1+""*"1+*+',
  94 : '11+1+""*"1+*+1+',
  95 : '11+"1+""*"1+*++',
  96 : '11+1+"1+"**"+',
  97 : '11+1+"1+"**"+1+',
  98 : '11+1+"+1+"*"+',
  99 : '11+1+"*"1+1+*',
  100: '11+1+"*1+"*',
  101: '11+1+"*1+"*1+',
  102: '11+"1+"*1+"*+',
  103: '11+1+""*1+"*+',
  104: '11+"*"1+"*1+*',
  105: '11+"*1+""+"*+',
  106: '11+1+"""*1+"*++',
  107: '11+""*1+""+"*++',
  108: '11+1+""+"**',
  109: '11+1+"*"1+"*+',
  110: '11+1+"*1+"1+*',
  111: '11+1+""+"*1+*',
  112: '11+1+"+1+"1+*"+',
  113: '11+1+""*1+"1+*+',
  114: '11+1+""+"*1+1+*',
  115: '11+"*1+""+"1+*+',
  116: '11+"*""1+"*+*',
  117: '11+1+"""+"*+*',
  118: '11+1+"*""1+"*++',
  119: '11+1+"*"1+"1+*+',
  120: '11+"*"1+"1+**',
  121: '11+"1+"*+"*',
  122: '11+"1+"*+"*1+',
  123: '11+""1+"*+"*+',
  124: '11+1+""*1+1+"*+',
  125: '11+"*1+""**',
  126: '11+1+""+"1+**'
}

const MAX_WINDOW = 100;

function encode(str) {
  let out = '', cmd = [], stk = [], pos = [];

  Buffer.from(str).forEach((c, i) => {
    let j = stk.indexOf(c);

    if(~j) {
      cmd[pos[j]] = cmd[pos[j]].replace(/;/, '";');
      cmd.push(';');
      stk = stk.slice(0, j);
      pos = pos.slice(0, j);
    }
    else {
      cmd.push(CHAR_MAP[c] + ';');
    }
    stk.push(c);
    pos.push(i);
  });

  out += cmd.join('');

  for(let n = 0;; n++) {
    let id = (function genId(n) {
      return n ? CHAR_SET[n % CHAR_SET.length] + genId(n / CHAR_SET.length | 0) : ''
    })(n);

    let max = 0, best = null, stat = {};

    for(let i = 0; i < out.length; i++) {
      let sub = '', p = 0, c;

      for(let w = 0; w < MAX_WINDOW && (c = out[i + w]); w++) {
        sub += c;
        p += (c == '(') - (c == ')');

        if(p < 0 || c == '|') break;

        if(!p) {
          (stat[sub] = stat[sub] || []).push(i);
        }
      }
    }

    let A = Object.keys(stat).map(sub => {
      let w = sub.length,
          b = ~w,
          cnt = stat[sub].reduce((t, a) => a < b + w ? t : (b = a, t + 1), 0),
          saved = cnt * w - ((cnt - 1) * (id.length + 2) + w + id.length + 3);

      return [ saved, sub, w ];
    })
    .sort((a, b) => b[0] - a[0]);

    if(!A.length) break;

    let [ saved, sub ] = A[0];

    if(saved < 1) break;

    if(saved > max) {
      max = saved;
      best = sub;
    }

    if(best === null) break;

    out =
      out.split(best).map((s, i) =>
        i ? i == 1 ? `(${id}|` + best + ')' + s : `(${id})` + s : s
      ).join('');
  }

  return out;
}

```

Try it online!

## Outputs

## How?

### Building the code snippets

The table of code snippets `CHAR_MAP` was built with the following program. This is a brute-force search that keeps the shortest snippet for each character, or the one that contains the most `1`'s in case of a tie. The idea behind this last rule is to use similar building strategies whenever possible to improve the final compression.

```
let snippet = {};

(function search(stk, cmd) {
  let n = stk[0];

  if(stk.length == 1 && n < 127) {
    snippet[n] =
      !snippet[n] || (
        snippet[n].length > cmd.length || (
          snippet[n].length == cmd.length &&
          snippet[n].split('1').length < cmd.split('1').length
        )
      ) ?
        cmd
      :
        snippet[n];
  }
  if(cmd.length < 15) {
    if(stk.length >= 2) {
      let a = stk[stk.length - 2], b = stk[stk.length - 1];

      search([...stk.slice(0, -2), a * b], cmd + '*');
      search([...stk.slice(0, -2), a + b], cmd + '+');
    }
    search([...stk, 1], cmd + '1');
    search([...stk, stk[stk.length - 1]], cmd + '"');
  }
})([1, 1], '11');

console.log(snippet);

```

Try it online!

### Optimizing the initial code

The initial code is first optimized by re-using characters that were previously generated whenever possible. For instance, `Hello, World!` is optimized as:

```
[H];[e];[l]";";[o]";[,];[ ];[W];;[r];;[d];[!];

```

where each character within brackets is one of the code snippets generated above.

### Compressing the code with functions

We then iteratively look for the sub-string in the code that leads to the highest savings when replaced with a function call.

We make sure that the selected sub-strings have balanced parentheses and do not contain a `|`.

Below are all the compression steps for "Hello, World!".

Initial code:

```
11+1+"+"*"+;11+1+"*1+"*1+;11+1+""+"**";";11+1+""+"*1+*";11+"*"1+"+1+*;11+"*"*"+;11+1+"""
*"*++;;11+1+""+"*1+1+*;;11+1+"*1+"*;11+"*"*"+1+;

```

We replace `;11+1+"` with a function with an empty name:

```
11+1+"+"*"+(|;11+1+")*1+"*1+()"+"**";"()"+"*1+*";11+"*"1+"+1+*;11+"*"*"+()""*"*++;()"+"*
1+1+*;()*1+"*;11+"*"*"+1+;

```

We replace `;11+"*"` with a function named `!`:

```
11+1+"+"*"+(|;11+1+")*1+"*1+()"+"**";"()"+"*1+*"(!|;11+"*")1+"+1+*(!)*"+()""*"*++;()"+"*
1+1+*;()*1+"*(!)*"+1+;

```

We replace `()"+"*` with a function named `"`:

```
11+1+"+"*"+(|;11+1+")*1+"*1+("|()"+"*)*";"(")1+*"(!|;11+"*")1+"+1+*(!)*"+()""*"*++;(")1+
1+*;()*1+"*(!)*"+1+;

```
> 18 votes

# Answer
# Python 2, 13.62 + 3.18 + 3.17 + 2.90 = 22.87

```
def gen_prog(inp):
    prog = ''
    inp = map(ord, inp)
    vals = sorted(set(inp))[::-1]
    funcnames = ([''] + sorted(set(map(chr,range(32, 127))) - set('()|~')))[:len(vals)]
    val2funcname = {k:v for (k,v) in zip(sorted(vals, key=lambda c:-inp.count(c)), funcnames)}
    func_defined = {f: False for f in funcnames + ['~']}
    for n in inp:
        f = val2funcname[n]
        frag = '(' + f
        if not func_defined[f]:
            frag += '|1'
            for b in bin(n)[3:]:
                frag += ('(~)' if func_defined['~'] else '(~|"+1+)') if b == '1' else '"+'
                if b == '1': func_defined['~'] = True
            frag += ';'
            func_defined[f] = True
        frag += ')'
        if inp.count(n) == 1: frag = frag[2+len(f):-1]
        prog += frag
    return prog

```

Hello, World!

We're no strangers...

A keyboard...

Pascal's...

Improved the average score for large test cases by embedding the print command into the functions.

---

# Python 2, 13.62 + 4.00 + 3.87 + 3.65 = 25.14

```
def gen_prog(inp):
    prog = '1(~|"+1+)'
    inp = map(ord, inp)
    vals = sorted(set(inp))[::-1]
    funcnames = ([''] + sorted(set(map(chr,range(32, 127))) - set('()|~')))[:len(vals)]
    val2funcname = {k:v for (k,v) in zip(sorted(vals, key=lambda c:-inp.count(c)), funcnames)}
    for i,v in enumerate(vals): prog += '(' + val2funcname[v] + '|' + '1'*(i==len(vals)-1)
    for i,v in enumerate(vals[::-1]):
        diff = v - (vals[::-1] + [1])[i-1]
        prog += '1' + bin(diff)[3:].replace('0', '"+').replace('1', '(~)') + '+)'
    for n in inp: prog += '(' + val2funcname[n] + ');'
    return prog

```

Hello, World!

We're no strangers...

A keyboard...

Pascal's...

Basically wraps every char that appears in the output into a named function. Almost every ASCII printable character is OK for function name, so we don't need any two-char names, and one of them can be zero-char, which is assigned to the most frequent character.
> 8 votes

# Answer
# C++, Score = Whatever

```
#include <iostream>
#include <vector>
#include <stack>
#include <cstdio>
#include <cctype>

using namespace std;
vector<char> a[256], code;
stack<unsigned long long> st;
int max_depth;
void constant_gen(int depth) {
    if (depth == max_depth) {
        if (st.top() < 256 && a[st.top()].empty()) {
            a[st.top()] = code;
        }
        return;
    }
    st.push(1); code.push_back('1');
    constant_gen(depth+1);
    st.pop(); code.pop_back();
    if (st.size() >= 1) {
        st.push(st.top()); code.push_back('"');
        constant_gen(depth+1);
        st.pop(); code.pop_back();
    }
    if (st.size() >= 2) {
        int h = st.top(); st.pop();
        int r = st.top(); st.pop();
        st.push(h + r); code.push_back('+');
        constant_gen(depth+1);
        st.pop(); code.pop_back();
        st.push(r); st.push(h);

        h = st.top(); st.pop();
        r = st.top(); st.pop();
        st.push(h * r); code.push_back('*');
        constant_gen(depth+1);
        st.pop(); code.pop_back();
        st.push(r); st.push(h);
    }
}
int main() {
    char ch;
    max_depth = 1;
    for (int i=0; i<5; i++) {
        a[0].push_back("11+1<"[i]);
    }
    while (max_depth < 16) {
        constant_gen(0);
        max_depth += 2;
    }
    while ((ch = getchar()) != EOF) {
        if (isdigit(ch)) {
            ch = ch - '0';
        }
        for (int i=0; i<a[ch].size(); i++) {
            cout << a[ch][i];
        }
        if (ch < 10) {
            cout << ":";
        } else {
            cout << ";";
        }
    }
    return 0;
}

```

Most of the code generates the constant table.
> 3 votes

# Answer
# Python 2, 14.15 + 13.40 + ~~13.61~~ 13.55 + ~~11.85~~ 10.01 = ~~53.01~~ 51.11

```
def gen_prog(inp):
    prog = '1(|"+1+)'

    parts = []
    prev_int = False

    for c in inp:
        if prev_int and c.isdigit():
            parts[-1] += c
        elif c.isdigit() and c != '0':
            prev_int = True
            parts.append(c)
        else:
            prev_int = False
            parts.append(c)

    for c in parts:
        if c == '0':
            prog += "11+1<:"
        elif c[0].isdigit():
            prog += '1' + bin(int(c))[3:].replace('0', '"+').replace('1', '()') + ':'
        else:
            prog += '1' + bin(ord(c))[3:].replace('0', '"+').replace('1', '()') + ';'

    return prog

```

Hello, World!
We're no strangers to code golf, you know the rules, and so do I
A keyboard so real you can almost TASTE it
Pascal's Tree-angle
> 2 votes

# Answer
# MAWP, 173.69 + ? + ? + ? points

```
%[25W|]%%0~%[{![1A1:]%1A[1A76W1M;]%69W5M;}]

```

This submission only uses the `1` and `+` and `;` instructions. Not very efficient, but works reliably.

`Hello, World!` all by itself took 10 minutes to run and give output. The result was 2258 bytes, and the rest of the strings are way bigger.

I think it's better for my computer not to run any more of the test cases.

Try it!
> 2 votes

# Answer
# Python 3, 10.08 + ? + ? + 5.36 points

Code is a bit slow, still running tests.

```
import itertools
from difflib import SequenceMatcher

string = '''Hello, World!'''

def create_constants(string):
    chars = ['1','"','+','*']
    g = list(set(string))
    combinations = []
    consts = []
    nums = []
    for i in range(2,13):
        combinations.extend(list(map(''.join, itertools.product(chars, repeat=i))))

    print('Generated combinations')
    codes = [ord(i) for i in g]
    for combination in combinations:
        stack = [2]
        for char in combination:
            try:
                if char == '1':
                    stack.append(1)
                elif char == '+':
                    stack.append(stack.pop() + stack.pop())
                elif char == '*':
                    stack.append(stack.pop() * stack.pop())
                elif char == '"':
                    stack.append(stack[-1])
            except:
                pass
            if stack != [] and stack[-1] in codes:
                nums.append(stack[-1])
                codes.remove(stack[-1])
                consts.append('11+'+combination)
                if codes == []:
                    return consts, nums

in_order = []
consts, nums = create_constants(string)
for i in string:
    in_order.append(consts[nums.index(ord(i))])
code = ";".join(in_order) + ';'
substring_counts={}

f=lambda s,n:max(l:=[s[j:j+n]for j in range(len(s))],key=l.count)
k = {}
for i in list(range(2,len(code)))[::-1]:
    d = f(code,i)
    if code.count(d) > 1:
        saved = len(d) * code.count(d) - 4 - ((code.count(d) + 1) * 2)
        if saved > 0:
            k[d] = saved
try:
    most_occuring = max(k, key=k.get)
    code = code.replace(most_occuring, '()')
    code = code.replace('()','(|' +  most_occuring + ')',1)
except:
    pass
print(code)

```

This is my first answer to a question of such kind. I'm also quite inexperienced, but with the combined forces of my knowledge and stackoverflow I managed to make something half-decent :D
> 1 votes

---
Tags: code-challenge, metagolf, test-battery
---


# Question
Title: Breaking Bad - ize any string (compression)
The TV series "Breaking Bad" replaced the letters Br and Ba with a periodic-table like representation, printing `[Br35]eaking [Ba56]d`.

Create a program that takes a string input, does a replacement and prints an output. The replacement shall subsidize any substring that matches an element symbol with the notation demonstrated in `[Br35]eaking [Ba56]d`. That is, add the atomic number to the element symbol and enclose in square brackets.

All elements start with a capital letter and consist of either one or two letters. The highest element to be considered is Og118. From wikipedia:

> 1 H, 2 He, 3 Li, 4 Be, 5 B, 6 C, 7 N, 8 O, 9 F, 10 Ne, 11 Na, 12 Mg, 13 Al, 14 Si, 15 P, 16 S, 17 Cl, 18 Ar, 19 K, 20 Ca, 21 Sc, 22 Ti, 23 V, 24 Cr, 25 Mn, 26 Fe, 27 Co, 28 Ni, 29 Cu, 30 Zn, 31 Ga, 32 Ge, 33 As, 34 Se, 35 Br, 36 Kr, 37 Rb, 38 Sr, 39 Y, 40 Zr, 41 Nb, 42 Mo, 43 Tc, 44 Ru, 45 Rh, 46 Pd, 47 Ag, 48 Cd, 49 In, 50 Sn, 51 Sb, 52 Te, 53 I, 54 Xe, 55 Cs, 56 Ba, 57 La, 58 Ce, 59 Pr, 60 Nd, 61 Pm, 62 Sm, 63 Eu, 64 Gd, 65 Tb, 66 Dy, 67 Ho, 68 Er, 69 Tm, 70 Yb, 71 Lu, 72 Hf, 73 Ta, 74 W, 75 Re, 76 Os, 77 Ir, 78 Pt, 79 Au, 80 Hg, 81 Tl, 82 Pb, 83 Bi, 84 Po, 85 At, 86 Rn, 87 Fr, 88 Ra, 89 Ac, 90 Th, 91 Pa, 92 U, 93 Np, 94 Pu, 95 Am, 96 Cm, 97 Bk, 98 Cf, 99 Es, 100 Fm, 101 Md, 102 No, 103 Lr, 104 Rf, 105 Db, 106 Sg, 107 Bh, 108 Hs, 109 Mt, 110 Ds, 111 Rg, 112 Cn, 113 Nh, 114 Fl, 115 Mc, 116 Lv, 117 Ts, 118 Og

Additional rules:

* As this challenge is about compression as much as about code golf, so you have to provide the element list yourself. You **must not use any build in periodic tables** provided by our language.
* Work case-sensitive. That means "Breaking Bad" has 2 replacements, "Breaking bad" has one. The input can be arbitrary and won't always follow English grammar. fOoBar shall become f\[O8\]o\[Ba56\]r.
* Search greedy, \[He\] takes precedence over \[H\].

**Shortest code in bytes wins.**

# Answer
# JavaScript (ES6), 327 bytes

```
s=>s.replace(RegExp([...a="HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg".match(/.[a-z]?/g)].sort(s=>-!!s[1]).join`|`,'g'),s=>`[${s+-~a.indexOf(s)}]`)

```

Try it online!

### How?

The data string consists of all element symbols concatenated together, from lowest to highest atomic number.

```
"HHeLiBeBCNOFNeNaMg...LvTsOg"

```

We split it into a list `a[]` of 118 entries with the following regular expression:

```
 +------> any character (always a capital letter)
 |   +--> optionally followed by a letter in lower case
 | __|_
 |/    \
/.[a-z]?/g

```

We create a copy of `a[]`, put all single-character elements at the end of the list and join with pipes:

```
[...a].sort(s => -!!s[1]).join('|')

```

Which gives:

```
"Og|Ts|Lv|Mc|Fl|Nh|...|He|H|B|C|N|O|F|P|S|K|V|Y|I|W|U"

```

We turn this string into a regular expression and apply it to the input string. Each matched sub-string `s` is replaced with the pattern:

```
`[${s + -~a.indexOf(s)}]`

```
> 6 votes

# Answer
# Python 3.8, <sup>~~454~~ \\$\cdots\\$~~409~~</sup> 385 bytes

Saved a whopping ~~38~~ ~~40~~ ~~45~~ 69 bytes (and fixed a bug) thanks to ovs!!!

```
eval("lambda s:_]and_<b][-1]".replace('_',"[(s:=re.sub(f'(?<!\[){b}',f'[{b}{e}]',s))for e,b in p if b[1:]"))
import re
p=[*enumerate(re.split("(?=[A-Z])","HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg"))][1:]

```

Try it online!

First goes through all two letter chemicals and then single letter ones.
> 4 votes

# Answer
# Charcoal, 217 bytes

```
Ｆ⪪”}∨"²Ｑ/QH▷⊕Ff←ＳγＧ¤º＆ρωＶφ∨]›¶⁻Nr*Sψ⦄π⁶&Ｕ⊞jεＪκκＨ‹ι7◧"↷⌊Ｒι¦◧◧‽3▷↨↑´^@➙⊙×π+sQ⌈⊙▷ＴQ|ⅉB{_Π"⪪η(⁵AxＱＷＷ/⁻∨8▶u…κ¹*ＩTλ_⟧‽Ｈj.⊞；r⬤|›∧7ψjêÞζp⸿⊖¿⊖Ｑ℅↷Hb↨“↔=bＹ⁵⌈↷¬δ⎚⪫:D₂↓;≦？⁺[‴.t4r±,s^)↗τ”²⊞υΦι›κ ≔⪪⮌Ｓ¹θＷ∧θ⭆⊕№υ⭆²§⮌θκ⊟θ¿№υι«[ιＩ⊕⌕υι]»ι

```

Try it online! Link is to verbose version of code. Explanation:

```
Ｆ⪪”...”²⊞υΦι›κ

```

Split a list of element names into pairs of letters and delete the spaces.

```
≔⪪⮌Ｓ¹θ

```

Reverse the input and split it into characters.

```
Ｗ∧θ⭆⊕№υ⭆²§⮌θκ⊟θ

```

While there is still input, remove the last 2 characters if there is a matching element, otherwise remove the last character.

```
¿№υι«

```

If there is a match in the array, then...

```
[ιＩ⊕⌕υι]

```

...print the match and its atomic number inside `[]`s.

```
»ι

```

Otherwise just print the current character.
> 4 votes

# Answer
# 05AB1E, ~~183~~ 181 bytes

```
.œʒ.•2вy>ÖΘZθÒ7ßΩ¨ÑÝ
(Îiþ∍ćf=ÆΛ}’.мιoiFδC¸Γ=¢`Ÿíнp»ΛÑzðÿ®ÄÄ‘Â@Âη+(Óûò‘8нKKK#â<Ù#<“râµ5£”м}ÓæuüåÈZµ-ΔÈ;VzeY¯õnK§ÁÚ¡[θƶη„Gp©6›mðÿāε1ΛÎíγJò~Ü‰cT¢Œƶʒ˜•2ô™ðм©såüαP}Σ€g{ygš}θ®DεN>«…[ÿ]}‡J

```

Pretty slow for long inputs.

Try it online or verify a few more short test cases.

**Explanation:**

```
.œ               # Get all partitions of the (implicit) input-string
  ʒ              # Filter these list of parts by:
   .•2вy...ƶʒ˜•  #  Push compressed string "h helibeb c n o f nenamgalsip s clark casctiv crmnfeconicuzngageassebrkrrbsry zrnbmotcrurhpdagcdinsnsbtei xecsbalaceprndpmsmeugdtbdyhoertmybluhftaw reosirptauhgtlpbbipoatrnfrraacthpau nppuamcmbkcfesfmmdnolrrfdbsgbhhsmtdsrgcnnhflmclvtsog"
     2ô          #  Split it into parts of size 2: ["h ","he","li","be","b "...]
       ™         #  Titlecase each string: ["H ","He","Li","Be","B ",...]
        ðм       #  Remove all spaces from each string: ["H","He","Li","Be","B",...]
          ©      #  Store this list in variable `®` (without popping)
           s     #  Swap so the current partition is at the top of the stack
            å    #  Check for each inner part whether it's in the element-list
                 #  (1 if truthy; 0 if falsey)
             ü   #  For each overlapping pair:
              α  #   Get the absolute difference
               P #  Get the product of those to check if all are truthy (1)
                 #  (partitions in the form of [0,1,0,1,...] or [1,0,1,0,...] are left)
  }Σ             # After the filter: sort any remaining partition by:
    €            #  Map each part in the list to:
     g           #   Pop and push its length
      {          #  Sort this list of lengths
       y         #  Push the current partition again
        g        #  Pop and push its length to get the amount of parts in this partition
         š       #  And prepend it at the front of the other lengths
   }θ            # After the sort by: only leave the last partition,
                 # which will have the most parts, as well as the longest individual parts
     ®           # Push the list of elements from variable `®` again
      D          # Duplicate it
       ε         # Map the copy to:
        N>       #  Push the 0-based map index, and increase it by 1
          «      #  Append it to the element-string
           …[ÿ]  #  Push string "[ÿ]", where the `ÿ` is automatically filled with the
                 #  element name and number
       }‡        # After the map: transliterate all elements to the formatted elements in
                 # the partition
         J       # And join it back together to a single string
                 # (after which it is output implicitly as result)

```

See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*) to understand why `.•2вy>ÖΘZθÒ7ßΩ¨ÑÝ\n(Îiþ∍ćf=ÆΛ}’.мιoiFδC¸Γ=¢`Ÿíнp»ΛÑzðÿ®ÄÄ‘Â@Âη+(Óûò‘8нKKK#â<Ù#<“râµ5£”м}ÓæuüåÈZµ-ΔÈ;VzeY¯õnK§ÁÚ¡[θƶη„Gp©6›mðÿāε1ΛÎíγJò~Ü‰cT¢Œƶʒ˜•` is `"h helibeb c n o f nenamgalsip s clark casctiv crmnfeconicuzngageassebrkrrbsry zrnbmotcrurhpdagcdinsnsbtei xecsbalaceprndpmsmeugdtbdyhoertmybluhftaw reosirptauhgtlpbbipoatrnfrraacthpau nppuamcmbkcfesfmmdnolrrfdbsgbhhsmtdsrgcnnhflmclvtsog"`.
> 1 votes

# Answer
# Perl 5 `-p`, 313 bytes

```
map$k{$_}=++$j,HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg=~/.[a-z]?/g;for$a(sort{$b=~y///c-length$a}keys%k){s/(?<!\[)$a/[$a$k{$a}]/g}

```

Try it online!
> 0 votes

---
Tags: code-golf, compression
---


title: Secret ">" Stacking Challenge: grading

text:
# Question
Title: Secret ">" Stacking Challenge: grading
## Background

Tetris Grand Master 3 has a hidden grading system based on the shape of the stack at the end of the game, which is called **Secret "\>" Stacking Challenge**. It consists of entirely filling the lowest rows except for the zigzag pattern which starts at the left bottom cell and spans the entire width:

```
#
.#########
#.########
##.#######
###.######
####.#####
#####.####
######.###
#######.##
########.#
#########.
########.#
#######.##
######.###
#####.####
####.#####
###.######
##.#######
#.########
.#########

```

The board is graded by how many lines follow this exact pattern from the bottom line. Note that the topmost hole in the pattern must be blocked by an extra piece of block. If you consider the `#`s and `.`s as the mandatory pattern (blanks can be anything), you can get the score of 19 only if the exact pattern above is matched from the bottom line. Analogously, if the board matches this pattern

```
   #
###.######
##.#######
#.########
.#########

```

but not

```
    #
####.#####
###.######
##.#######
#.########
.#########

```

then the score is 4.

For this challenge, consider a board of arbitrary size (other than 20 cells high and 10 cells wide). We can grade the board for the same pattern: for example, if the board has width 4, this is the pattern for score 3:

```
  #
##.#
#.##
.###

```

and this is the pattern for score 10:

```
   #
###.
##.#
#.##
.###
#.##
##.#
###.
##.#
#.##
.###

```

## Challenge

Given the final state of the Tetris board of arbitrary size, grade the board using the system above.

You can take the board using any sensible format for a rectangular matrix, where every cell contains one of two distinct values (for empty and filled respectively). You can assume the grid is a valid Tetris board (no row is entirely filled). Also, the width of the grid is at least 2.

Standard rules apply. The shortest code in bytes wins.

## Test cases

In order to prevent possible confusion, the test cases here use `O` for the blocks and `.` for empty spaces.

```
Input:
..O.O
OOOO.
OOO..
OO.OO
O.OOO
.OOOO
Output: 3

Input:
..
O.
.O
.O
O.
.O
O.
.O
Output: 4

Input:
.OOO
O.OO
OO.O
OO.O
OO.O
O.OO
.OOO
Output: 2 (any lines above the first non-conforming line are ignored;
           doesn't get 3 because 3rd line's hole is not capped)

Input:
OOO.
.OOO
O.OO
OO.O
OOO.
OO.O
O.OO
Output: 0 (Wrong starting hole)

Input:
.OOO
O.OO
OO.O
OOO.
Output: 0 (Wrong starting hole)

Input:
.OOO
.OOO
Output: 0 (Hole is not covered)

Input:
OOO...O..O
.OOOOOOOOO
O.OOOOOOOO
OO.OOOOOOO
OOO.OOOOOO
OOOO.OOOOO
OOOOO.OOOO
OOOOOO.OOO
OOOOOOO.OO
OOOOOOOO.O
OOOOOOOOO.
OOOOOOOO.O
OOOOOOO.OO
OOOOOO.OOO
OOOOO.OOOO
OOOO.OOOOO
OOO.OOOOOO
OO.OOOOOOO
O.OOOOOOOO
.OOOOOOOOO
Output: 19

```

# Answer
> 4 votes
# Husk, 18 bytes

```
Lδ↑€…¢ŀT¹↑εΨ↑-↔m¥0

```

Try it online!

Takes a 0-1 matrix.

## Explanation

There are three occurrences of  in this program, and they all work differently thanks to the modifier functions `δ` and `Ψ`. By default, `↑α` expects `α` to be a unary function, takes a list and returns the longest prefix of elements for which `α` returns a truthy value. `Ψ↑α` expects `α` to be binary, and returns the longest prefix of elements `x` for which `α x y` is truthy, where `y` is the next element. `δ↑α` expects `α` to be binary and takes two lists instead of one. It returns the longest prefix of the second list whose elements `y` satisfy `α x y`, where `x` is the corresponding element of the first list.

```
Input is a list of lists of integers.
Example: [[0,1,1],[1,0,1],[1,1,0],[1,0,1],[1,1,0],[0,0,1],[0,1,1]]

m     Map
 ¥0   indices where 0 occurs:
        [[1],[1,2],[3],[2],[3],[2],[1]]
↔     Reverse:
        [[1],[2],[3],[2],[3],[1,2],[1]]

 ↑    Take while
Ψ     this element and the next
  -   have nonempty set difference:
        [[1],[2],[3],[2],[3],[1,2]]

↑     Take while
 ε    this element is a singleton:
        [[1],[2],[3],[2],[3]]
      Call this list X.

ŀT¹   Indices of input transposed:
        [1,2,3]
¢     Cycle infinitely:
        [1,2,3,1,2,3,..]
…     Rangify:
        [1,2,3,2,1,2,3,2,1,..]
 ↑    Take from X while
δ     the corresponding integer in this list
  €   is an element of it:
        [[1],[2],[3],[2]]
L     Length: 4

```

# Answer
> 3 votes
# , 57 42 bytes

Takes in 0 for blocked, 1 for empty.

```
[:#.~(|.@$2^|@}:@i:@<:)/@$=2#.[*[+_1|.!.2]

```

Try it online!

### How it works

```
[*[+_1|.!.2]

```

Shift the board down by one (2 gets pushed in at the top to make sure the top spots don't count.) Then it adds to the original board and multiplies with itself. This basically boils down to: a valid open spot stays 1, while invalid ones become 2.

```
 (|.@$2^|@}:@i:@<:)/@$

```

Given the dimensions, get the exclusive range `-x … x - 1` for the width, for e.g. 4: `_3 _2 _1 0 1 2`, and get their absolute values `3 2 1 0 1 2`. Resize that list to the height of the board, rotate it so the starting 3 aligns to the last row, and `2^x` the list: `8 4 2 1 2 4 8 4 2…`

```
 =2#.

```

Interpret the rows as a base 2 number and compare it to the zig-zag list.

```
 [:#.~

```

And by reflexive base conversion we can count the leading 1's, so the leading rows that are valid.

# Answer
> 3 votes
# JavaScript (ES6), 84 bytes

Expects a list of strings, with `1` for empty spaces and `0` for blocks.

```
f=(a,i=j=1<<a[k=0].length)=>(v='0b'+a.pop()+0)^i?v&i/k&&-1:1+f(a,i*=k=i&j?.5:i&2||k)

```

Try it online!

### How?

Each string in the input array is padded with an extra `0` and interpreted as a binary number. The variable `j` is initialized to `2**W`, where `W` is the width of the board. We use a bit mask `i` initialized to `j` to keep track of the expected position of the hole in the pattern.

After each iteration, `i` is multiplied by `k`. We update the value of `k` whenever `(i & j) != 0` (bouncing on the leftmost side) or `(i & 2) != 0` (bouncing on the rightmost side).

Example for `W = 5`:

```
j = 0b100000

i = 0b100000 // -> set k to 1/2
i = 0b010000 // \
i = 0b001000 //  }-> leave k unchanged
i = 0b000100 // /
i = 0b000010 // -> set k to 2
i = 0b000100 // \
i = 0b001000 //  }-> leave k unchanged
i = 0b010000 // /
i = 0b100000 // -> set k to 1/2
...

```

### Commented

```
f = (                // f is a recursive function taking:
  a,                 //   a[] = input array
  i = j =            //   i = hole bit mask, initialized to ...
    1 << a[k = 0]    //   ... j = 2 ** W, where W is the width of the board
         .length     //   k = bit mask multiplier, initialized to 0
) =>                 //
( v =                // pop the last value from a[], append a '0' and interpret
  '0b' + a.pop() + 0 // it as a binary number saved in v
) ^ i ?              // if v is not equal to i:
  v & i / k          //   use the previous bit mask i / k to test whether there's
  && -1              //   a hole in v above the last hole of the pattern, in
                     //   which case we subtract 1 from the final result
:                    // else:
  1 +                //   add 1 to the final result
  f(                 //   do a recursive call:
    a,               //     pass a[] unchanged
    i *=             //     multiply i by:
      k =            //       the new value of k:
        i & j ?      //         if we've reached the leftmost side:
          .5         //           set k to 1/2
        :            //         else:
          i & 2      //           set k to 2 if we've reached the rightmost side,
          || k       //           or leave k unchanged otherwise
  )                  //   end of recursive call

```

# Answer
> 2 votes
# Charcoal, 52 bytes

```
ＷＳ⊞υι≔⮌υυＰ⪫υ¶Ｗ∧⁼.O⪫ＫＤ²↓ω⁼¹№§υⅉ.Ｍ✳⁻⁷⊗÷﹪ⅉ⊗⊖Ｌθ⊖Ｌθ≔ⅉθ⎚Ｉθ

```

Try it online! Link is to verbose version of code. Takes input as a newline-terminated list of strings of `.` and `O` characters. Explanation:

```
ＷＳ⊞υι

```

Input the list.

```
≔⮌υυ

```

Reverse the list.

```
Ｐ⪫υ¶

```

Print the list without moving the cursor.

```
Ｗ∧

```

Repeat while both...

```
⁼.O⪫ＫＤ²↓ω

```

... the character under the cursor is a `.` and the character below (because the list was reversed) is an `O`, and...

```
⁼¹№§υⅉ.

```

... the current list line contains exactly one `.`:

```
Ｍ✳⁻⁷⊗÷﹪ⅉ⊗⊖Ｌθ⊖Ｌθ

```

Move the cursor diagonally down and either right or left depending on the row.

```
≔ⅉθ⎚Ｉθ

```

Capture the first invalid row index (0-indexed, so equal to the number of valid rows), clear the canvas, and print it as a string.

# Answer
> 1 votes
# Jelly, 25 bytes

```
ZJŒḄṖṁLW€⁻"ⱮṚT€,Ḋ$ƊZḄCTḢ’

```

A monadic Link accepting a list of lines where each line is a list of `1`s (empty) and `0`s (filled) which yields a non-negative integer (the score).

**Try it online!** Or see the test-suite.

### How?

Builds a list of the expected empty indices for each line from the bottom and compares it to each of two lists, (a) the actual empty indices and (b) the actual empty indices dequeued. The results of this comparison are then processed to find the score.

```
ZJŒḄṖṁLW€⁻"ⱮṚT€,Ḋ$ƊZḄCTḢ’ - Link: list of lines, A
Z                         - transpose
 J                        - range of length     -> [1,2,...,w=#Columns]
  ŒḄ                      - bounce              -> [1,2,...,w-1,w,w-1,...,2,1]
    Ṗ                     - pop                 -> [1,2,...,w-1,w,w-1,...,2]
      L                   - length (A)          -> h=#Lines
     ṁ                    - mould like (repeat Ṗ result such that it is length h)
       W€                 - wrap each of these integers in a list (call this x)
                  Ɗ       - last three links as a monad - i.e. f(A):
            Ṛ             -   reverse (A)
             T€           -   for each (line) get the list of truthy ("empty") indices
                 $        -   last two links as a monad - i.e. f(z=that):
                Ḋ         -     dequeue (drop the leftmost)
               ,          -     (z) pair (that)
           Ɱ              - map across (the two results of f(A)) applying:
          "               -   (x) zip with (result) applying:
         ⁻                -     not equal?
                   Z      - transpose - now we have leading [0,1]'s for valid rows
                                        from the bottom up
                    Ḅ     - convert from binary - now leading 1s for valid rows
                     C    - complement (subtract (each) from one)
                      T   - truthy indices
                       Ḣ  - head
                        ’ - decrement

```

# Answer
> 1 votes
# 05AB1E, 32 bytes

```
R©εDgÝ¨û¨NèDU._ƶO®N>èX.__н*Θ}γнO

```

Input as a matrix of 1s and 0s, where the 1s are empty spaces and 0s are filled cells.

Try it online. or verify all test cases.

**Explanation:**

```
R             # Reverse the rows of the (implicit) input-matrix
 ©            # Store it in variable `®` (without popping)
  ε           # Map over each row:
   Dg         #  Get the width of the matrix
     Ý        #  Push a list in the range [0,width]
      ¨       #  Remove the last element to change the range to [0,width-1]
       û      #  Palindromize it: [0,1,2,...,w-2,w-1,w-2,...,2,1,0]
        ¨     #  Remove the last value: [0,1,2,...,w-2,w-1,w-2,...,2,1]
         Nè   #  Index the map-index into this list
           DU #  Store a copy in variable `X`
    ._        #  Rotate the current row that many times to the left
      ƶ       #  Multiply each value by its 1-based index
       O      #  And sum this list
   ®          #  Push the reversed input-matrix again from variable `®`
    N>è       #  Index the map-index + 1 into this to get the next row
       X._    #  Also rotate it `X` amount of times towards the left
          _   #  Invert all booleans (1s becomes 0s, and vice-versa)
           н  #  And only leave the first value
   *          #  Multiply both together
    Θ         #  And check that it's equal to 1 (1 if 1; 0 otherwise)
  }γ          # After the map: split the list into groups of adjacent equivalent values
    н         # Only leave the first group
     O        # And take the sum of that
              # (after which it is output implicitly as result)

```

---
Tags: code-golf, grid, binary-matrix
---


title: Combinatorial Decomposition

text:
# Question
Title: Combinatorial Decomposition
In the body of this challenge, \\$\begin{pmatrix}n\\k\end{pmatrix}\\$ is used to represent the number of combinations of \\$k\\$ elements of \\$n\\$, also written as \\$\frac{n!}{k!(n-k)!}\\$ or \\$n\mathrm{C}r\\$.

Any nonnegative integer \\$m\\$, for arbitrary natural (positive) \\$r\\$, can be written as a unique series of \\$r\\$ combinations such that $$m=\sum\limits\_{i=1}^{r}\begin{pmatrix}C\_i\\i\end{pmatrix}$$ provided the sequence \\$C\\$ both strictly increases (i.e. \\$C\_{\ell-1}\lneq C\_\ell\\$) and consists solely of nonnegative integers. \\$C\\$ is not necessarily unique without these restrictions.

---

# Example

Consider \\$m=19\\$ and \\$r=4\\$. Values of \\$C\_4\\$, \\$C\_3\\$, \\$C\_2\\$ and \\$C\_1\\$ must be found for the equation $$19=\sum\limits\_{i=1}^4\begin{pmatrix}C\_i\\i\end{pmatrix}\\\$$ which can be rewritten as $$\begin{pmatrix}C\_4\\4\end{pmatrix}+\begin{pmatrix}C\_3\\3\end{pmatrix}+\begin{pmatrix}C\_2\\2\end{pmatrix}+\begin{pmatrix}C\_1\\1\end{pmatrix}=19$$ Begin by finding the largest value of \\$C\_4\\$ which satisfies the inequality \\$\begin{pmatrix}C\_4\\4\end{pmatrix}\leq 19\\$. \\$C\_4\\$ is six: $$\begin{pmatrix}6\\4\end{pmatrix}+\begin{pmatrix}C\_3\\3\end{pmatrix}+\begin{pmatrix}C\_2\\2\end{pmatrix}+\begin{pmatrix}C\_1\\1\end{pmatrix}=19\\15+\begin{pmatrix}C\_3\\3\end{pmatrix}+\begin{pmatrix}C\_2\\2\end{pmatrix}+\begin{pmatrix}C\_1\\1\end{pmatrix}=19\\\begin{pmatrix}C\_3\\3\end{pmatrix}+\begin{pmatrix}C\_2\\2\end{pmatrix}+\begin{pmatrix}C\_1\\1\end{pmatrix}=4$$ The problem has been reduced to \\$m=4\\$ and \\$r=3\\$. The largest value of \\$C\_3\\$ which satisfies the inequalities \\$\begin{pmatrix}C\_3\\3\end{pmatrix}\leq4\\$ and \\$C\_3\lneq C\_4\\$ must be found. \\$C\_3\\$ is four: $$\begin{pmatrix}4\\3\end{pmatrix}+\begin{pmatrix}C\_2\\2\end{pmatrix}+\begin{pmatrix}C\_1\\1\end{pmatrix}=4\\4+\begin{pmatrix}C\_2\\2\end{pmatrix}+\begin{pmatrix}C\_1\\1\end{pmatrix}=4\\\begin{pmatrix}C\_2\\2\end{pmatrix}+\begin{pmatrix}C\_1\\1\end{pmatrix}=0$$ Any combination of the form \\$\begin{pmatrix}n\\k\end{pmatrix}\\$ with \\$n\<k\\$ is zero, and so \\$C\_2=1\\$ and \\$C\_1=0\\$: $$\begin{pmatrix}1\\2\end{pmatrix}+\begin{pmatrix}0\\1\end{pmatrix}=0\\0+0=0\\0=0\checkmark$$

Note that \\$C\_2\\$ cannot be zero because then \\$C\\$ would not strictly increase unless \\$C\_1\\$ were negative, which cannot be the case due to the condition that \\$C\\$ consists solely of nonnegative integers. The solution is summarized with the statement \\$C=(0,1,4,6)\\$ (here, 1-based indexing is used). The process followed here is guaranteed to produce the correct \\$C\\$.

---

# The Challenge

Given \\$m\\$ and \\$r\\$, find the elements of \\$C\\$.

# Rules

* This is so the shortest answer in bytes wins.
* Assume only valid input will be given.
* Input and output may assume whatever form is most convenient. This can include outputting the elements of \\$C\\$ in any order, because \\$C\\$ strictly increases and so the actual order of the elements is trivially found by sorting them.
* Terms whose combinations evaluate to zero, e.g. \\$C\_2\\$ and \\$C\_1\\$ in the example, cannot be neglected in output.
* A program should theoretically work for arbitrarily large values of \\$m\\$ and \\$r\\$, but is still acceptable if it is limited by memory constraints.

# Test Cases

Here \\$m\\$ is the first number and \\$r\\$ is the second, and the output begins with \\$C\_1\\$.

```
In: 19 4
Out: 0 1 4 6

In: 0 4
Out: 0 1 2 3

In: 40000 6
Out: 6 8 9 11 12 20

In: 6 6
Out: 1 2 3 4 5 6

In: 6 5
Out: 0 1 2 3 6

In: 6 20
Out: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 15 16 17 18 19 20 (note 14 is skipped)

In: 6 1
Out: 6

```

# Answer
> 7 votes
# JavaScript (ES6),  ~~95 93 86~~  82 bytes

Expects `(r)(m)`.

```
r=>F=(m,x=r)=>r?(g=k=>!k||g(--k)*(k-x)/~k)(r)>m?[...F(m-g(r--,--x)),x]:F(m,x+1):[]

```

Try it online!

## How?

### Helper function

The helper function \\$g\\$ is used to compute:

$$\binom{x}{r}=\frac{x(x-1)\dots(x-r+1)}{r!}=\prod\_{k=1}^{r}\frac{x-k+1}{k}$$

```
(g = k =>     // g is a recursive function taking k
  !k          // if k = 0, stop the recursion and return 1
  ||          // otherwise:
    g(--k)    //   decrement k and do a recursive call with the updated value
    * (k - x) //   multiply the result by k - x
    / ~k      //   divide by -k - 1
              //   which is equivalent to g(k - 1) * (x - k + 1) / k
)(r)          // initial call to g with k = r

```

### Main function

```
r =>                      // r = requested number of combinations
F = (m, x = r) =>         // F is a recursive function taking the target number m
                          // and a counter x, initialized to r
  r ?                     // if r is not equal to 0:
    g(r) > m ?            //   if C(x, r) is greater than m:
      [ ...F(             //     append the result of a recursive call to F:
          m - g(r--, --x) //       with m - C(x - 1, r) and r - 1
        ),                //     end of recursive call
        x                 //     append x (which was decremented above)
      ]                   //
    :                     //   else:
      F(m, x + 1)         //     increment x until C(x, r) > m
  :                       // else:
    []                    //   stop the recursion

```

# Answer
> 6 votes
# 05AB1E, ~~13~~ 11 bytes

```
∞<æIù.ΔācOQ

```

Inputs in the order \\$r,m\\$.

Try it online or verify all test cases.

**Explanation:**

```
∞           # Push an infinite positive list: [1,2,3,4,5,...]
 <          # Decrease it by 1 to include 0: [0,1,2,3,4,...]
  æ         # Get the powerset of this infinite list
   Iù       # Only leave sublists of a size equal to the first input `r`
     .Δ     # Find the first list which is truthy for:
       ā    #  Push a list in the range [1,length] (without popping the list itself)
        c   #  Get the binomial coefficient of the values at the same indices in the lists
         O  #  Sum those
          Q #  And check if it's equal to the (implicit) second input `m`
            # (after which the found list is output implicitly as result)

```

# Answer
> 4 votes
# Jelly, 12 bytes

I feel there may well be shorter, possibly by first creating an outer-product using the binomial function, \\$m\\$\\$r\\$.

```
»Żœc⁸cJ$S⁼ɗƇ

```

A full-program accepting \\$r\\$ and \\$m\\$ which prints the result.
(Or a dyadic Link yielding a list containing the unique result.)

**Try it online!**

### How?

```
»Żœc⁸cJ$S⁼ɗƇ - Main Link: r, n
»            - maximum (r,n)
 Ż           - zero range -> [0,1,2,...,max(r,n)]
    ⁸        - chain's left argument, r
  œc         - all (r-length) choices (of the zero range)
           Ƈ - filter keep those for which:
          ɗ  -   last three links as a dyad - f(selection, n)
       $     -     last two links as a monad - g(selection)
      J      -       range of length -> [1,2,...,r]
     c       -       binomial (vectorises) [s1C1, s2C2,...,srCr]
        S    -     sum
         ⁼   -     equals (n)?
             - implicit print (a list containing a single element prints that element)

```

# Answer
> 2 votes
# , ~~98~~ 96 bytes

```
s=function(m,r,j=choose(1:(m+r),r))if(r)`if`(!m,1:r-1,c(s(m-max(j[j<=m]),r-1),max(which(j<=m))))

```

Try it online!

Commented:

```
choose_series=
s=function(m,r,         # recursive function s
 j=choose((m+r):1,r))   # j = all relevant values of choose(c,r)
 if(r)                  # if r==0 don't return anything else
  `if`(!m,              # if m==0 ...
   1:r-1,               # ...just return the remaining r-series minus 1
   c(                   # otherswise return ...
    s(                  # recursive call to self, with
     m-                 #   new m = current m minus ...
      max(j[j<=m])      #   ... highest value of j less than or equal to m
     ,r-1),             #   new r = r-1;
    ((m+r):1)[j<=m][1]  # appended to the highest value of c for which...
   )                    # ...j is less than or equal to m
  )

```

(but, frustratingly, my approach here still comes-out longer than an **84 byte** port of Arnauld's approach...)

# Answer
> 2 votes
# Python 3.8 (pre-release), ~~125~~ ~~121~~ ~~114~~ ~~111~~ ~~108~~ 107 bytes

```
import math
c=math.comb
f=lambda n,r,k=0:n and(n<c(k+1,r)and f(n-c(k,r),r-1)+[k]or f(n,r,k+1))or[*range(r)]

```

Try it online!

Explanation: Start from `k=0` and keep increasing `k` as long as `comb(k, r)` does not exceed `n`. Update `n` accordingly. Once the current value of `n` is 0, simply return the first `r` integers starting from 0.

# Answer
> 1 votes
# Wolfram Language (Mathematica), 92 bytes

```
(S=Select)[Subsets[S[0~Range~Max[a=#,b=#2],#~(B=Binomial)~b<a+1&],{b}],Tr@B[#,Range@b]==a&]&

```

Try it online!

# Answer
> 1 votes
# Charcoal, 39 bytes

```
ＮθＦ⮌ＥＮＥ⊕ιλ«≔Π⊕ιηＷ¬›Π⊕ι×θη≦⊕ι≧⁻÷ΠιηθＩ⟦⊟ι

```

Try it online! Link is to verbose version of code. Outputs in descending order. Explanation:

```
Ｎθ

```

Input `m`.

```
Ｆ⮌ＥＮＥ⊕ιλ«

```

Loop over the `n` ranges `[0..n-1]`, `[0..n-2]`, ... `[0, 1]`, `[0]`. These represent `Cᵢ` for `i` from `n` down to `1` but also the product calculates `Cᵢ!/(Cᵢ-i)!` for the binomial term.

```
≔Π⊕ιη

```

Take the product of the incremented range, which is just `i!`. This is used to complete the calculation of the binomial term.

```
Ｗ¬›Π⊕ι×θη≦⊕ι

```

Increment the range, effectively incrementing `Cᵢ`, until the next binomial term would exceed `m`. (I don't often get to increment a whole range in Charcoal!)

```
≧⁻÷Πιηθ

```

Subtract the current binomial term from `m`.

```
Ｉ⟦⊟ι

```

Output `Cᵢ` (which is always the last element in the range) on its own line.

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


title: Translate ASCII text to braille

text:
# Question
Title: Translate ASCII text to braille
Write a program that translates ASCII text to braille output. Requirements:

* Input may come from stdin, command line, or some other external input source.
* Output should be recognisable as braille, the form of output is up to you. An example would be `o` for a raised dot and `.` for a non-raised dot. Textual pattern representation such as `1-3-4` is not acceptable. Long line wrapping is not required.
* Only the 26 alphabet characters and space are required for a minimal solution. All input characters not supported by your solution should be ignored.

Scoring is by number of characters in the source code. Penalties and bonuses are:

* +50 penalty for using Unicode braille characters as output.
* -50 bonus for supporting capitals, numbers, and punctuation.
* -200 bonus for supporting ligatures and one-letter contractions from English (Grade-2) Braille. (Will make this a separate challenge since it's quite a different problem.)

Sample invocation and output (minimal solution):

```
$ braille Hello world
o .  o .  o .  o .  o .  . .  . o  o .  o .  o .  o o
o o  . o  o .  o .  . o  . .  o o  . o  o o  o .  . o
. .  . .  o .  o .  o .  . .  . o  o .  o .  o .  . .

```

# Answer
> 6 votes
## Python, 162

```
l=map((" a c,bif/e d:hjg'k m;lsp o n!rtq%12s. w -u x v   z y"%'').find,raw_input().lower())
for i in 1,4,16:print'  '.join('.o.o    ..oo'[(n&i*3)/i::4]for n in l)

```

Currently supports lowercase letters and some punctuation, but it's still a work in progress.

Example:

```
$ python braille.py
Hello, world!
o .  o .  o .  o .  o .  . .  . .  . o  o .  o .  o .  o o  . .
o o  . o  o .  o .  . o  o .  . .  o o  . o  o o  o .  . o  o o
. .  . .  o .  o .  o .  . .  . .  . o  o .  o .  o .  . .  o .

```

# Answer
> 6 votes
# Python - 90 75 + 50 = 125

Use lower case letters.

```
for l in input():
 a=ord(l)-96
 if a<0:a=0
 print("⠀⠁⠃⠉⠙⠑⠋⠛⠓⠊⠚⠅⠇⠍⠝⠕⠏⠟⠗⠎⠞⠥⠧⠺⠭⠽⠵"[a],end="")

```

One-liner (thanks to ɐɔıʇǝɥʇuʎs)

```
for l in input():print("⠀⠁⠃⠉⠙⠑⠋⠛⠓⠊⠚⠅⠇⠍⠝⠕⠏⠟⠗⠎⠞⠥⠧⠺⠭⠽⠵"[max(0,ord(l)-96)],end="")

```

# Answer
> 5 votes
# BBC Basic 103 ASCII characters or 92 tokens

```
A$="HXIKJY[ZQShxikjy{zqsl|Wmon"FORK=1TO26A=ASC(MID$(A$,K))VDU23,K+96,A AND9;0,A/2AND9;0,A/4AND9;:NEXT

```

Possibly not quite what the OP intended, this redefines the font for the lowercase characters. `VDU 23,n,a,b,c,d,e,f,g,h` assigns an 8x8 bitmap to character n, consisting of eight bytes. Following a parameter with a semicolon instead of a comma causes it to be treated as a two-byte little-endian number.

The braille patterns for letters `a` through `z` are stored in A$, according to the following bit pattern. This is extracted by masks with 9=binary`1001` and rightshifts (division by 2 and 4 is used as standard BBC basic has no shift operator.)

```
 8 1
16 2
32 4

```

**Ungolfed code**

```
A$="HXIKJY[ZQShxikjy{zqsl|Wmon"
FORK=1TO26
  A=ASC(MID$(A$,K))
  VDU23,K+96,A AND9;0,A/2AND9;0,A/4AND9;
NEXT

```

**Usage example**

This is done in screen mode 6 for clarity (type MODE6 as soon as you open the command line emulator.)

Actually, after running the code, any lowercase letters (including keyboard input) appear in Braille.

Emulator at http://bbcbasic.co.uk/bbcwin/bbcwin.html.

See also this similar answer of mine: https://codegolf.stackexchange.com/a/28869/15599

# Answer
> 3 votes
# C, 269

```
#define C char
#define O*p++=(*t&1)*65+46;*t>>=1;
main(int c,C**v){C b[99]={1,5,3,11,9,7,15,13,6,14},o[99],*q=o,*p=v[1],*t;while(c=*p++)*q++=c=='w'?46:c>='a'&&c<='z'?c-='a'+(c>'w'),b[c%10]|(c>9)*16|(c>19)*32:0;for(c=3;c;c--){p=b;for(t=o;t<q;t++){O;O*p++=32;}puts(b);}}

```

This implementation requires that its argument, if it contains spaces, must be quoted:

```
# braille "hello world"

```

# Answer
> 3 votes
# Bash + coreutils

### Minimal solution - lowercase only, 83 (33 unicode chars + 50 penalty):

```
tr a-z ⠁⠃⠉⠙⠑⠋⠛⠓⠊⠚⠅⠇⠍⠝⠕⠏⠟⠗⠎⠞⠥⠧⠭⠽⠵⠺

```

### Capitals, numbers and punctuation, 120 (120 unicode chars + 50 penalty - 50 bonus):

```
a=⠁⠃⠉⠙⠑⠋⠛⠓⠊⠚⠅⠇⠍⠝⠕⠏⠟⠗⠎⠞⠥⠧⠭⠽⠵⠺
sed 's/\([0-9]\)/⠼&/g;s/\([A-Z]\)/⠠&/g'|tr ",;':\-⎖.!“?”()/a-zA-Z1-90" ⠂⠆⠄⠒⠤⠨⠲⠖⠦⠦⠴⠶⠶⠌$a$a$a

```

Example output:

```
$ echo {A..Z} {a..z} {0..9} ".,;:" | ./braille.sh
⠠⠁ ⠠⠃ ⠠⠉ ⠠⠙ ⠠⠑ ⠠⠋ ⠠⠛ ⠠⠓ ⠠⠊ ⠠⠚ ⠠⠅ ⠠⠇ ⠠⠍ ⠠⠝ ⠠⠕ ⠠⠏ ⠠⠟ ⠠⠗ ⠠⠎ ⠠⠞ ⠠⠥ ⠠⠧ ⠠⠭ ⠠⠽ ⠠⠵ ⠠⠺ ⠁ ⠃ ⠉ ⠙ ⠑ ⠋ ⠛ ⠓ ⠊ ⠚ ⠅ ⠇ ⠍ ⠝ ⠕ ⠏ ⠟ ⠗ ⠎ ⠞ ⠥ ⠧ ⠭ ⠽ ⠵ ⠺ ⠼⠚ ⠼⠁ ⠼⠃ ⠼⠉ ⠼⠙ ⠼⠑ ⠼⠋ ⠼⠛ ⠼⠓ ⠼⠊ ⠲⠂⠆⠒
$

```

# Answer
> 2 votes
# CJam - 51

```
q{i32%"@`hptdx|lX\bjrvfz~nZ^ck]swg"=i2b1>2/}%zSf*N*

```

Try it at http://cjam.aditsu.net/

Example input:

```
braille is strange

```

Example output:

```
10 10 10 01 10 10 10 00 01 01 00 01 01 10 10 11 11 10
10 11 00 10 10 10 01 00 10 10 00 10 11 11 00 01 11 01
00 10 00 00 10 10 00 00 00 10 00 10 10 10 00 10 00 00

```

It only supports lowercase letters and space. Other characters are mapped to supported characters (in particular uppercase letters to lowercase).

**Explanation:**

Braille characters are encoded using 1 for a raised dot and 0 for a non-raised dot, left to right and top to bottom. This gives 6 base-2 digits; a 1 is prepended to avoid stripping leading zeros, then the number is converted to base 10 then to the corresponding ASCII character.
Example: t -\> ⠞ -\> 01/11/10 -\> 1011110 -\> 94 -\> ^

The program converts back each character to the triplet of pairs of bits (such as `[[0 1][1 1][1 0]]`) obtaining a matrix of bit pairs. The matrix is then transposed and separators are added (spaces within rows, newlines between rows).

`q` reads the input into a string = array of characters
`{…}%` applies the block to each character
`i32%` gets the ASCII code mod 32 (space-\>0, a-\>1, b-\>2, z-\>26)
`"@`hptdx|lX\bjrvfz~nZ^ck]swg"` is a string containing the braille characters encoded as explained before
`=` gets the corresponding encoded braille character from the string
`i2b` gets the ASCII code then converts to base 2 (obtaining an array of 7 digits)
`1>` removes the leading 1 digit
`2/` splits the array into (3) pairs
`z` transposes the matrix
`Sf*` joins each row with spaces
`N*` joins the rows with newlines

# Answer
> 2 votes
# APL (Dyalog Extended), 81 + 50 - 50 = 81 bytes

```
(i,'⠚⠁⠃⠉⠙⠑⠋⠛⠓⠊⠲⠂⠒⠆⠦⠖ ',⍨i←'⠁⠃⠉⠙⠑⠋⠛⠓⠊⠚⠅⠇⠍⠝⠕⠏⠟⠗⠎⠞⠥⠧⠺⠭⠽⠵')[(⎕A,⎕C⎕A,⎕D,'.,:;?! ')⍳⍞]

```

Try it online uses Dyalog 17, so `⎕C` is not supported in it. The alternative, `819⌶` (suggested by dzaima), has been used for demonstration purposes.

Braille symbols taken from dcode.

## Explanation

```
                                                  ⍳⍞ Find index of each character of the input in the string..
                            (⎕A,⎕C⎕A,⎕D,'.,:;?! ')   A-Z, a-z, 0-9, and punctuation.
                           [                      ]  Pick characters from those indices..
(i,'⠚⠁⠃⠉⠙⠑⠋⠛⠓⠊....⠧⠺⠭⠽⠵')                          In the braille representation of the Alphanumeric and punctuation characters.
(last line is shortened to take up less space.)

```

Try it online!

# Answer
> 1 votes
# JavaScript - 286

```
w=prompt().split('');for(i=0;i<w.length;i++){z=w[i];o="o",p=".";b=[1,5,3,11,9,7,15,13,6,14];e=[c="",1,3];g=z.charCodeAt(0)-97;if(g>22)g--;f=e[g/10|0];d=b[g%10];if(g==22){d=14;f=2;}c+=d&1?o:p;c+=d&2?o:p;c+="\n";c+=d&4?o:p;c+=d&8?o:p;c+="\n";c+=f&1?o:p;c+=f&2?"o\n":".\n";console.log(c);}

```

First attempt. No bonuses.

# Answer
> 1 votes
# PHP, 331

```
<?php $d=split("/",gzinflate(base64_decode("NYzBDQBACIM26o3G/r+LRf2QYAOZe4SCLKgU7A9lEWVOzrQVrAiwghWhLKLMyZlawTTGMIYxPg==")));$d[-65]="......";$i=str_split(preg_replace("/[^a-z ]/","",trim(fgets(STDIN))));$o=["","",""];$S="substr";foreach($i as $c){$v=ord($c)-97;for($x=0;$x<3;$x++)$o[$x].=$S($d[$v],$x*2,2)." ";}echo join($o,"\n");

```

No bonuses for now.

# Answer
> 1 votes
# C, ~~249~~ 244

```
#define B?111:46
#define P(a,b)printf("%c%c ",a B,b B):
a,i;main(int c,char**v){for(char*p;p=v[1],a<3;puts(""),++a)while(i=*p++)i==32?P(0,0)i/97&122/i?c=(i+=(i==119)*17-97-(i>119))%10,a?a^1?P(i/10%3,i/20)P(c>4|c==1,c/3&&c%3-2)P(c<8,5*c/8%2)0;}

```

Input is a command-line argument, which must be escaped or quoted if the string contains spaces. Supported characters are lowercase letters and space. Unsupported characters are silently dropped.

**Edit:** Shaved 5 bytes by simplifying a condition

# Answer
> 0 votes
## perl, 195+2-50=147

**This handles capital, number and punctuation, without relying on unicode** (195 bytes + 2 bytes (for `-pl`) - 50 bonus)

```
~s/([A-Z])/|$1/g,~s/(\d)/#$1/g,tr/1-90/a-ij/;for$i(1,2,4){map{for$j(1,8){$s.=index(" a,b'k;l^cif/msp_e:h*o!r_djg_ntq|_?_-u(v_____x____._)z\"___w_#y",l$
"}$_=$s

```

With indentation:

```
~s/([A-Z])/|$1/g,
~s/(\d)/#$1/g,
tr/1-90/a-ij/;
for$i(1,2,4){
  map{
    for$j(1,8){
     $s.=index(" a,b'k;l^cif/msp_e:h*o!r_djg_ntq|_?_-u(v_____x____._)z\"___w_#y",lc($_))&$j*$i?o:_
    }
   $s.=_
  }split//;
  $s.="
"}
$_=$s

```

Sample output

```
perl -pl brail.pl
Hello, 99!
___o__o__o__o__o_________o__o__o__o____
___oo__o_o__o___o_o______o_o___o_o__oo_
_o_______o__o__o________oo____oo____o__

```

# Answer
> 0 votes
# Javascript ES6 - 282 309 297 283 270 - 50 = 232 259 233 220 bytes

This would be shorter, but checking for capital letters *hurt*.

```
f=_=>{z='toLowerCase';k=(a,b)=>a%b>~-b/2?1:0;t=(a,b)=>k(a,b)+`${k(a,b/2)} `;b=c=d='';for(v of _){v==v[z]()?0:(b+=0,c+=0,v=v[z](d+=1));$=` ,'-";9015283467@./+^_>#i[s!jwt)a*kue:ozb<lvh\\r(c%mxd?nyf$p&g]q=`.search(v);b+=t($,64);c+=t($,16);d+=t($,4)}alert(`${b}
${c}
${d}`)}

```

**EDIT:** Thanks to mbomb007 for saving me two bytes - unfortunately, I found that a little bit of previous golfing had ruined everything, so I had to add 27 characters back in.

**EDIT:** Aaand 12 bytes saved by moving the spaces.

**EDIT:** Realized it was silly to output as characters, and saved quite a few bytes. I also saved a few characters by swapping k=(a,b)=\>a%(2\*b)\>b-1?1:0 for k=(a,b)=\>a%b\>~-b/2?1:0.

---
Tags: code-golf
---