[Question]
      [
Today's challenge is to draw a [binary tree](https://en.wikipedia.org/wiki/Binary_tree) as beautiful [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") like this example:
```
                               /\
                              /  \
                             /    \
                            /      \
                           /        \
                          /          \
                         /            \
                        /              \
                       /                \
                      /                  \
                     /                    \
                    /                      \
                   /                        \
                  /                          \
                 /                            \
                /                              \
               /\                              /\
              /  \                            /  \
             /    \                          /    \
            /      \                        /      \
           /        \                      /        \
          /          \                    /          \
         /            \                  /            \
        /              \                /              \
       /\              /\              /\              /\
      /  \            /  \            /  \            /  \
     /    \          /    \          /    \          /    \
    /      \        /      \        /      \        /      \
   /\      /\      /\      /\      /\      /\      /\      /\
  /  \    /  \    /  \    /  \    /  \    /  \    /  \    /  \
 /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
```
You will be given a positive integer as input. This input is the [height of the tree](https://stackoverflow.com/a/2603707/3524982). The above example has a height of six.
You may submit either a full-program or a function, and you are free to use any of our [default IO methods](http://meta.codegolf.stackexchange.com/q/2447/31716). For example, printing the tree, returning a string with newlines, returning a 2d char array, saving the tree to a file, etc. would all be allowed.
Trailing spaces on each line are permitted.
Here are some examples of inputs and their corresponding outputs:
```
1:
/\
2:
 /\
/\/\
3:
   /\
  /  \
 /\  /\
/\/\/\/\
4:
       /\
      /  \
     /    \
    /      \
   /\      /\
  /  \    /  \
 /\  /\  /\  /\
/\/\/\/\/\/\/\/\
5:
               /\
              /  \
             /    \
            /      \
           /        \
          /          \
         /            \
        /              \
       /\              /\
      /  \            /  \
     /    \          /    \
    /      \        /      \
   /\      /\      /\      /\
  /  \    /  \    /  \    /  \
 /\  /\  /\  /\  /\  /\  /\  /\
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
```
Unfortunately, the output grows exponentially, so it's hard to show larger examples. [Here is a link](https://gist.github.com/DJMcMayhem/77a25b711283bf844698edb032dc924c) to the output for 8.
As usual, this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so standard loopholes apply, and try to write the shortest program possible in whatever language you choose.
Happy golfing!

[Answer]
## Python 2, 77 bytes
```
S=s=i=2**input()
while s:print S/s*('/'+' '*(s-i)+'\\').center(s);i-=2;s/=s/i
```
Prints with trailing spaces, terminating with error.
I took this code from [my submission](http://golf.shinh.org/reveal.rb?Branching%20tree/xnor_1477113229&py) to [a challenge I posed on Anarchy Golf](http://golf.shinh.org/p.rb?Branching+tree), plus a [one-byte improvement](http://golf.shinh.org/reveal.rb?Branching+tree/xsot+%28xnor%29_1478252053&py) found by xsot. The hardcoded value of 128 was changed to `2**input()`.
The idea is that each row of the output is a segment copied one or more times. The half after the input split has one copy of each segment, the quarter after the next split has two copies, and so on, until the last line with many segments of `/\`.
Each segment had a `/` and `\`, with spaces in between, as well as on the outside to pad to the right length. The outer padding is done with `center`.
The variable `s` tracks the current with of each segment, and the number of segments is `S/s` so that the total width is the tree width `S`. The line number `i` counts down by 2's, and whenever the value `s` is half of it, a split occurs, and the segment width halves. This is done via the expression `s/=s/i`. When `i` reaches `0`, this gives an error that terminates the program.
Since anagolf only allows program submissions, I didn't explore the possibility of a recursive function, which I think is likely shorter.
[Answer]
# [V](https://github.com/DJMcMayhem/V), 32 bytes
```
é\é/ÀñLyPÄlx$X>>îò^llÄlxxbPò
|
```
[Try it online!](https://tio.run/nexus/v#@394ZczhlfqHGw6tPbxRzKcy4HBLToVKhJ3d4XWHN8Xl5IC4FUkBhzdx1fz/DwA "V – TIO Nexus")
Hexdump:
```
00000000: e95c e92f c0ad f116 4c79 50c4 6c78 2458  .\./....LyP.lx$X
00000010: 3e3e eef2 5e6c 6cc4 6c78 7862 50f2 0a7c  >>..^ll.lxxbP..|
```
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 11 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
/║╶╷［ｌ＼；∔↔║
```
[Try it here!](https://dzaima.github.io/Canvas/?u=LyV1MjU1MSV1MjU3NiV1MjU3NyV1RkYzQiV1RkY0QyV1RkYzQyV1RkYxQiV1MjIxNCV1MjE5NCV1MjU1MQ__,i=NQ__,v=2)
Explanation:
```
/║          push `/\` ("/" palindromized so this is a Canvas object)
  ╶╷[       repeat input-1 times
     l        get the width of the ToS
      \       create a diagonal that long
       ;∔     prepend that to the item below
         ↔    reverse the thing horizontally
          ║   and palindromize it horizontally
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~140 138~~ 135 bytes
```
e n=[1..n]>>" "
n!f=(e n++).(++e n)<$>f
f 0=[]
f n=1!f(n-1)++['/':e(2*n-2)++"\\"]
b n|n<2=f 1|t<-b$n-1,m<-2^(n-2)=m!f m++zipWith(++)t t
```
[Try it online!](https://tio.run/nexus/haskell#FY1Ba4QwEIXv/oq3Iqw2TboKhVKMUHrpsdBDD64F3U0wNI6isYWy/92Op/fNzDc8N0zjHPA6UphHr16mybtLG9yPgZSw44wyqfDbu0sPt8CRX6/myon32eyM0eKtXb6N93hSp2ho@aYxreEjzFBYyTsyC1OHBI@bAek6V4qaqooRR3SwOuWlEJlKhWDKuNFGFiddNxyk80NqE5J5JkR9fDg@m7S4I1nwGJ/PcRN1oBuVhbbIb6GU3e7eD6UsvtJd0wP/Y2D9z02fLvRckwWEbfsH "Haskell – TIO Nexus") Call with `b 5`, returns a list of strings.
**Pretty print usage:**
```
*Main> putStr . unlines $ b 5
               /\
              /  \
             /    \
            /      \
           /        \
          /          \
         /            \
        /              \
       /\              /\
      /  \            /  \
     /    \          /    \
    /      \        /      \
   /\      /\      /\      /\
  /  \    /  \    /  \    /  \
 /\  /\  /\  /\  /\  /\  /\  /\
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
```
(some) **Explanation:**
* `e n` generates a string of `n` spaces
* `n!f` pads each string in the list of strings `f` with `n` spaces left and right
* `f n` draws a "peak" in a `n` by `2n` rectangle
* `b n` draws the binary tree by concatenating two smaller trees and centers a new peak above them
Edit: -3 bytes thanks to Zgarb!
[Answer]
## [J](http://jsoftware.com/), ~~49 43~~ 42 bytes
```
' /\'{~(|.,-)"1@(=@i.@#,-)^:(<:`(,:@,&*-))
```
This evaluates to a verb that takes a number and returns a 2D character array.
[Try it online!](https://tio.run/nexus/j#@5@uYGuloK6gH6NeXadRo6ejq6lk6KBh65Cp56AM5MRZadhYJWjoWDnoqGnpamr@T03OyFdIVzD5DwA "J – TIO Nexus")
## Explanation
I first construct a matrix of the values -1, 0 and 1 by iterating an auxiliary verb, and then replace the numbers by characters.
The auxiliary verb constructs the right half of the next iteration, then mirrors it horizontally to produce the rest.
In the following explanation, `,` concatenates 2D arrays vertically and 1D arrays horizontally.
```
' /\'{~(|.,-)"1@(=@i.@#,-)^:(<:`(,:@,&*-))  Input is n.
                          ^:(            )  Iterate this verb
                             <:             n-1 times
                               `(       )   starting from
                                    ,&*-    the array 1 -1 (actually sign(n), sign(-n))
                                 ,:@        shaped into a 1x2 matrix:
                                             Previous iteration is y.
                      #                      Take height of y,
                   i.@                       turn into range
                 =@                          and form array of self-equality.
                                             This results in the identity
                                             matrix with same height as y.
                       ,-                    Concatenate with -y, pad with 0s.
       (    )"1@(        )                   Then do to every row:
        |.,-                                 Concatenate reversal to negation.
' /\'{~                                     Finally index entry-wise into string.
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
ＦＮ«→↗⌈Ｘ²⊖ι‖Ｍ
```
[Try it online!](https://tio.run/##HYyxCoMwEEBn8xUZL2CXDh10bJcOigh@gE1PPYg5OaIdpN9@DX3jg/f8MornMahOLBaecdtTu68vFHDOnqZo@ECoepqX5GpTdEIxQTVsf1PaO1KgOEPHn5xcS/tAL7hiTPgGcpkc9TgF9KkhEc7f2nxVb3o5wg8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
 Ｎ              Input as a number
Ｆ «             Loop over implicit range
   →            Move right (because mirroring moves the cursor)
         ι      Current index
        ⊖       Decremented
      Ｘ²        Power of 2
     ⌈          Ceiling
    ↗           Draw diagonal line
          ‖Ｍ    Mirror image
```
The line lengths are 1, 1, 2, 4, 8 ... 2^(N-2), thus the awkward calculation.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~20~~ 19 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
≡mX░R○k╣∙╒ab^◘⌐╖x▼;
```
[Run and debug it](https://staxlang.xyz/#p=f06d58b052096bb9f9d561625e08a9b7781f3b&i=1%0A3&a=1&m=2)
[Answer]
## JavaScript (ES6), 105 bytes
```
f=n=>n<2?"/\\":" "+f(n-1).split`/`[0].replace(/|/g,"$`$'$'/$`$`\\$'$'$` \n")+f(n-1).replace(/.*/g,"$&$&")
```
Works by building the result up recursively from the base case `/\`. The bottom half is just the previous case with each line duplicated. The top half was a little trickier; it looks as if you want to take the previous case and only keep the two sides but you also have to worry about padding the strings to double the width, so instead I do some regex magic. By taking the leading spaces from the previous case and splitting at every point, I can consider the spaces before and after that point. At each match the spaces before increase by 1 and the spaces after decrease by 1; this can be used to position the `/` and `\` in the correct places. The newlines and padding are also added here; this takes care of all the padding except a trailing space on each line and a leading space on the first line which I have to add manually. (Leading spaces on subsequent lines come from the matched string).
[Answer]
## Batch, 218 bytes
```
@echo off
set/a"n=1<<%1"
set s=set t=
%s%/\
set l=for /l %%i in (2,1,%n%)do call
%l% %s% %%t%%
%l%:l
:l
echo %t%
set/an-=1,m=n^&n-1
%s%%t: /=/ %
%s%%t:\ = \%
if %m% neq 0 exit/b
%s%%t:/ =/\%
%s%%t: \=/\%
```
Note: Line 6 ends in a space. Works by moving the branches left and right appropriately each time, except on rows that are 2n from the end, in which case the branches get forked instead.
[Answer]
# Haxe, 181 bytes
```
function g(n):String return(n-=2)==-1?"/\\":[for(y in 0...1<<n)[for(x in 0...4<<n)x+y+1==2<<n?"/":x-y==2<<n?"\\":" "].join("")].concat([for(y in g(n+1).split("\n"))y+y]).join("\n");
```
Or, with some optional whitespace:
```
function g(n):String
  return
    (n -= 2) == -1
    ? "/\\"
    : [ for (y in 0...1 << n)
        [ for (x in 0...4 << n)
          x + y + 1 == 2 << n
          ? "/"
          : x - y == 2 << n
            ? "\\"
            : " "
        ].join("")
      ].concat([ for (y in g(n + 1).split("\n"))
        y + y
      ]).join("\n");
```
I was working for a while on a solution which created an array of space characters of the right size first, then iteratively put the forked paths lower and lower (and more densely at each iteration). It remained 230+ bytes, though. The approach here is pretty much what @Laikoni's Haskell approach is. I couldn't get away with not having `:String`, because Haxe is not smart enough to identify that the return type will always be a String.
This is a function only, here's a full programme to test it:
```
class Main {
    public static function main(){
        function g(n):String return(n-=2)==-1?"/\\":[for(y in 0...1<<n)[for(x in 0...4<<n)x+y+1==2<<n?"/":x-y==2<<n?"\\":" "].join("")].concat([for(y in g(n+1).split("\n"))y+y]).join("\n");
        Sys.println(g(Std.parseInt(Sys.args()[0])));
    }
}
```
Put the above in `Main.hx`, compile with `haxe -main Main.hx -neko frac.n` and test with `neko frac.n 4` (replace `4` with the desired order).
[Answer]
# PHP, 188 Bytes
[Online Version](http://sandbox.onlinephpfunctions.com/code/fb264f1f0ef523faff29b2f0fb25c05cf792a7f0)
```
function f($l,$r=0,$m=1){global$a;for(;$i<$l;$i++)$i<$l/2?$a[$i+$r]=str_repeat(str_pad("/".str_pad("",2*$i)."\\",2*$l," ",2),$m):f($l/2^0,$r+$l/2,2*$m);}f(2**$argv[1]/2);echo join("\n",$a);
```
Expanded
```
function f($l,$r=0,$m=1){
global$a;
for(;$i<$l;$i++)
$i<$l/2
    ?$a[$i+$r]=str_repeat(str_pad("/".str_pad("",2*$i)."\\",2*$l," ",2),$m)
    :f($l/2^0,$r+$l/2,2*$m);
}
f(2**$argv[1]/2);
echo join("\n",$a);
```
]


[Question]
      [
This question is similar to [Biggest Square in a grid](https://codegolf.stackexchange.com/questions/152305/biggest-square-in-a-grid).
**Challenge**
Given a matrix of `1` and `0` in a string format `"xxxx,xxxxx,xxxx,xx.."` or array format `["xxxx","xxxx","xxxx",...]`, You will create a function that determines the area of the largest square submatrix that contains all `1`.
A square submatrix is one of equal width and height, and your function should return the area of the largest submatrix that contains only `1`.
**For Example:**
Given `"10100,10111,11111,10010"`, this looks like the following matrix:
1 0 1 0 0
1 0 1 **1 1**
1 1 1 **1 1**
1 0 0 1 0
You can see the bolded `1` create the largest square submatrix of size 2x2, so your program should return the area which is 4.
**Rules**
* Submatrix must be one of equal width and height
* Submatrix must contains only values `1`
* Your function must return the area of the largest submatrix
* In case no submatrix is found, return `1`
* You can calculate the area of the submatrix by counting the number of `1` in the submatrix
**Test cases**
**Input:** `"10100,10111,11111,10010"` **Output:** `4`
**Input:** `"0111,1111,1111,1111"` **Output:** `9`
**Input** `"0111,1101,0111"` **Output:** `1`
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes win.

[Answer]
# [Haskell](https://www.haskell.org/), ~~113 121 118~~ 117 bytes
```
x!s=[0..length x-s]
t#d=take t.drop d
f x=last$1:[s*s|s<-min(x!0)$x!!0!0,i<-x!!0!s,j<-x!s,all(>'0')$s#i=<<(s#j)x,s>0]
```
[Try it online!](https://tio.run/##HcbBCoMgGADgu0/xS0I1TPQ6tBeJDrJsWWajX5iHvbtbO3zwLRY3F0IpmaIZpBDBxWdaIHc4klRNJtnNQRLTebxgIjNkEywmpu4D3vCDutt9bDKVLcuUSiq5191/yNdryG0ITV/LumVYeaN1g9XaZo69HMtufQQDPiZ32kcCBrgcbxAw/wQfHRaplCJKSUWufQE "Haskell – Try It Online")
-3 bytes thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni?tab=profile)!
-1 byte thanks to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn?tab=profile)!
+8 bytes for the ridiculous requirement of returning 1 for no all-1s sub-matrix..
### Explanation/Ungolfed
The following helper function just creates offsets for `x` allowing to decrement them by `s`:
```
x!s=[0..length x-s]
```
`x#y` will drop `y` elements from a list and then take `x`:
```
t#d=take t.drop d
```
The function `f` loops over all possible sizes for sub-matrices in order, generates each sub-matrix of the corresponding size, tests whether it contains only `'1'`s and stores the size. Thus the solution will be the last entry in the list:
```
--          v prepend a 1 for no all-1s submatrices
f x= last $ 1 : [ s*s
                -- all possible sizes are given by the minimum side-length
                | s <- min(x!0)$x!!0!0
                -- the horizontal offsets are [0..length(x!!0) - s]
                , i <- x!!0!s
                -- the vertical offsets are [0..length x - s]
                , j <- x!s
                -- test whether all are '1's
                , all(>'0') $
                -- from each row: drop first i elements and take s (concatenates them to a single string)
                              s#i =<<
                -- drop the first j rows and take s from the remaining
                                      (s#j) x
                -- exclude size 0...........................................
                , s>0
                ]
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~35~~ ~~34~~ 32 bytes
```
{⌈/{×⍨⍵×1∊{∧/∊⍵}⌺⍵ ⍵⊢X}¨⍳⌊/⍴X←⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pRT4d@9eHpj3pXPOrdeni64aOOrupHHcv1gTRQoPZRzy4gpQDEj7oWRdQeAqra/KinS/9R75aIR20TQEr@/3cDsqhgENejvqlAJtC0iRqGCgYKIGygCWUCIYhpiGAaQJRoAgA "APL (Dyalog Unicode) – Try It Online")
[Adám's SBCS has all of the characters in the code](https://github.com/abrudz/SBCS)
Explanation coming eventually!
[Answer]
# [Haskell](https://www.haskell.org/), ~~99~~ 97 bytes
```
b s@((_:_):_)=maximum$sum[length s^2|s==('1'<$s<$s)]:map b[init s,tail s,init<$>s,tail<$>s]
b _=1
```
Checks if input is a square matrix of just ones with `s==('1'<$s<$s)`, if it is, answer is length^2, else 0. Then recursively chops first/last column/row and takes the maximum value it finds anywhere.
[Try it online!](https://tio.run/##RYtNCoMwEIX3nmIoghFEki7FlF6gJxAbEio11KTiRNpF754mpliYv/e9N6PExzBN3ivAMyGiEWUobuRbm9XkuJpuGuzdjYDX4wc5JwUr2hxDlX1j5Ayq01Y7wMpJPYUVVZufko5HnykQnHkjtQUO4ecigMyLtq5W9eu53LDMAKA7MMZgb0oPkVaJ0o3@yN@BnQWX0ZjZkjT9hBlHyvT@Cw "Haskell – Try It Online")
[Answer]
# [K (ngn/k)](https://github.com/ngn/k), ~~33~~ 28 bytes
```
{*/2#+/|/',/'{0&':'0&':x}\x}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqlpL30hZW79GX11HX73aQE3dSh1EVNTGVNT@L7GqVomurCuySlOosE7Iz7bWSEhLzMyxrrCutC7SjK3lKonWMFQwUABhA2sICwitDRUM4SwDiLymtUksSDmaEnRa09oSQxmQbW0AkzaM/Q8A "K (ngn/k) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 33 27 bytes
-6 bytes thanks to FrownyFrog!
```
[:>./@,,~@#\(#**/)@,;._3"$]
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8D/ayk5P30FHp85BOUZDWUtLX9NBx1ov3lhJJfa/JpeSnoJ6mq2euoKOQq2VQloxF1dqcka@QpqCsYKpiiHQCBCGkIYYECoD02KiYKKCTRkSRJiOqhTJhv8A "J – Try It Online")
## Explanation:
I'll use the first test case in my explanation:
```
    ] a =. 3 5$1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
```
I generate all the possible square submatrices with size from 1 to the number of rows of the input.
`,~@#\` creates a list of pairs for the sizes of the submatrices by stitching `,.` togehter the length of the successive prefixes `#\` of the input:
```
   ,~@#\ a
1 1
2 2
3 3
```
Then I use them to cut `x u ;. _3 y` the input into submatrices. I already have `x` (the list of sizes); `y` is the right argument `]` (the input).
```
 ((,~@#\)<;._3"$]) a
┌─────┬─────┬─────┬───┬─┐
│1    │0    │1    │0  │0│
│     │     │     │   │ │
│     │     │     │   │ │
├─────┼─────┼─────┼───┼─┤
│1    │0    │1    │1  │1│
│     │     │     │   │ │
├─────┼─────┼─────┼───┼─┤
│1    │1    │1    │1  │1│
└─────┴─────┴─────┴───┴─┘
┌─────┬─────┬─────┬───┬─┐
│1 0  │0 1  │1 0  │0 0│ │
│1 0  │0 1  │1 1  │1 1│ │
│     │     │     │   │ │
├─────┼─────┼─────┼───┼─┤
│1 0  │0 1  │1 1  │1 1│ │
│1 1  │1 1  │1 1  │1 1│ │
├─────┼─────┼─────┼───┼─┤
│     │     │     │   │ │
└─────┴─────┴─────┴───┴─┘
┌─────┬─────┬─────┬───┬─┐
│1 0 1│0 1 0│1 0 0│   │ │
│1 0 1│0 1 1│1 1 1│   │ │
│1 1 1│1 1 1│1 1 1│   │ │
├─────┼─────┼─────┼───┼─┤
│     │     │     │   │ │
│     │     │     │   │ │
├─────┼─────┼─────┼───┼─┤
│     │     │     │   │ │
└─────┴─────┴─────┴───┴─┘
```
For each submatrix I check if it consist entirely of 1s:
`(#**/)@,` - flatten the matrix, and mutiply the number of items by their product. If all items are 1s, the result will be their sum, otherwise - 0:
```
   (#**/)@, 3 3$1 0 0 1 1 1 1 1 1
0
   (#**/)@, 2 2$1 1 1 1
4
   ((,~@#\)(+/**/)@,;._3"$]) a
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
0 0 0 0 0
0 0 4 4 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
```
Finally I flatten the list of results for each submatrix and find the maximum:
`>./@,`
```
   ([:>./@,,~@#\(+/**/)@,;._3"$]) a
4
```
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-n`, 63 bytes
```
p (1..l=$_=~/,|$/).map{|i|/#{[?1*i]*i*(?.*(l-i+1))}/?i*i:1}.max
```
[Try it online!](https://tio.run/##KypNqvz/v0BBw1BPL8dWJd62Tl@nRkVfUy83saC6JrNGX7k62t5QKzNWK1NLw15PSyNHN1PbUFOzVt8@UyvTyrAWqLDi/39DA0MDAx0gaWioY2gIJg2AQlxwAQQBEzMw1DEAc//lF5Rk5ucV/9fNAwA "Ruby – Try It Online")
Ruby version of my [Python answer](https://codegolf.stackexchange.com/a/163441/78274). Golfier as a full program. Alternatively, an anonymous lambda:
# [Ruby](https://www.ruby-lang.org/), ~~70~~ 68 bytes
```
->s{(1..l=s=~/,|$/).map{|i|s=~/#{[?1*i]*i*(?.*(l-i+1))}/?i*i:1}.max}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664WsNQTy/Htti2Tl@nRkVfUy83saC6JrMGJKBcHW1vqJUZq5WppWGvp6WRo5upbaipWatvn6mVaWVYC1RbUfu/QCEtWsnQwNDAQAdIGhrqGBqCSQOgkFIsF1gaLo4g0KQMDHUMkEWVYv8DAA "Ruby – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
+2 to handle no-all-1 sublist present output
```
ẆZṡ¥"L€$ẎȦÐfL€Ṁ²»1
```
**[Try it online!](https://tio.run/##y0rNyan8///hrraohzsXHlqq5POoaY3Kw119J5YdnpAG4jzc2XBo0////6OjDXUMdEDYIFYHygZCMNsQiW0AURUbCwA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hrraohzsXHlqq5POoaY3Kw119J5YdnpAG4jzc2XBo06Hdhv8PtwN5//9HR0cb6hjogLBBrA6UDYRgtiES2wCiKjZWh0shOhpDFVYWNrUGYBZMLDYWAA "Jelly – Try It Online")
### How?
```
ẆZṡ¥"L€$ẎȦÐfL€Ṁ²»1 - Link: list of lists of 1s and 0s
Ẇ                  - all slices (lists of "rows") call these S = [s1,s2,...]
       $           - last two links as a monad:
     L€            -   length of each (number of rows in each slice) call these X = [x1, x2, ...]
    "              -   zip with (i.e. [f(s1,x1),f(s2,x2),...]):
   ¥               -     last two links as a dyad:
 Z                 -       transpose (get the columns of the current slice)
  ṡ                -       all slices of length xi (i.e. squares of he slice)
        Ẏ          - tighten (to get a list of the square sub-matrices)
          Ðf       - filter keep if:
         Ȧ         -   any & all (all non-zero when flattened?)
            L€     - length of €ach (the side length)
              Ṁ    - maximum
               ²   - square (the maximal area)
                »1 - maximum of that and 1 (to coerce a 0 found area to 1)
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 143 bytes
```
%`$
,;#
+%(`(\d\d.+;#)#*
$1¶$&¶$&#
\G\d(\d+,)|\G((;#+¶|,)\d)\d+
$1$2
)r`((11)|\d\d)(\d*,;?#*)\G
$#2$3
1,
#
Lv$`(#+).*;\1
$.($.1*$1
N`
-1G`
^$
1
```
[Try it online!](https://tio.run/##RYw9DsIwDIV3X8Mucn6o8sqYgTEL4gQRClIZWBgqxNRz9QC9WEiRAMl@evr8ydPteX9cUTtNpXZFyEcm12nRPOaxd5ENWxKsi@y2Zcopj@3ovJlzUo3s1mX2Jo9tXDNlIDMVVaAJ7YdpsvXxyNbkRMKDHAiemE4vKcrO9DZmkPQqPayAzoX2SIUuQqgVASH4loAHPhkaoh/4x5cF@K29AQ "Retina – Try It Online") Link includes test cases. Takes input as comma-separated strings. Explanation:
```
%`$
,;#
```
Add a `,` to terminate the last string, a `;` to separate the strings from the `#`s and a `#` as a counter.
```
+%(`
)
```
Repeat the block until no more subsitutions happen (because each string is now only one digit long).
```
(\d\d.+;#)#*
$1¶$&¶$&#
```
Triplicate the line, setting the counter to 1 on the first line and incrementing it on the last line.
```
\G\d(\d+,)|\G((;#+¶|,)\d)\d+
$1$2
```
On the first line, delete the first digit of each string, while on the second line, delete all the digits but the first.
```
r`((11)|\d\d)(\d*,;?#*)\G
$#2$3
```
On the third line, bitwise and the first two digits together.
```
1,
#
```
At this point, each line consists of two values, a) a horizontal width counter and b) the bitwise and of that many bits taken from each string. Convert any remaining `1`s to `#`s so that they can be compared against the counter.
```
Lv$`(#+).*;\1
$.($.1*$1
```
Find any runs of bits (vertically) that match the counter (horizontally), corresponding to squares of `1`s in the original input, and square the length.
```
N`
```
Sort numerically.
```
-1G`
```
Take the largest.
```
^$
1
```
Special-case the zero matrix.
[Answer]
# JavaScript, 92 bytes
```
a=>(g=w=>a.match(Array(w).fill(`1{${w}}`).join(`..{${W-w}}`))?w*w:g(w-1))(W=a.indexOf`,`)||1
```
```
f=
a=>(g=w=>a.match(Array(w).fill(`1{${w}}`).join(`..{${W-w}}`))?w*w:g(w-1))(W=a.indexOf`,`)||1
console.log(f('0111,1111,1111,1111'));
console.log(f('10100,10111,11111,10010'));
console.log(f('0111,1101,0111'));
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~21~~ 20 bytes
```
×⍨{1∊⍵:1+∇2×/2×⌿⍵⋄0}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQb/04Dk4emPeldUGz7q6HrUu9XKUPtRR7vR4en6QPyoZz9Q6FF3i0Ht//8lQKXVIG7nwiIgM@1R7y4r9fxsdaC0elpiZo46UAAoXVTLpfGot@/QikdtE9UNDQwNDNQVQLShIYg2hNIGQAl1zRIFEyTFSGrQKKBCS2wKDUCUAVSFIQA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~117~~ 109 bytes
Credit to @etene for pointing out an inefficiency that cost me an additional byte.
```
lambda s:max(i*i for i in range(len(s))if re.search(("."*(s.find(',')-i+1)).join(["1"*i]*i),s))or 1
import re
```
[Try it online!](https://tio.run/##bYyxDgIhEET7@wpCc7uIhLU08UvUAj3w1nhwgSv065FYnImxecW8mZlfy5jirobDqT7cdBmcKPvJPYEVi5CyYMFRZBdvHh4@QkHkILI3xbt8HQGkkQqKCRwH6HWPW94QorknjnCUJBWfFaNuu3ZGHU9zyks7qHPmuIgAkixZqxuJNNGHtkUSu7Wyui/@aEva/hqJ9Q0 "Python 2 – Try It Online")
Takes input as a comma-separated string. This is a regex-based approach that tries matching the input string against patterns of the form `111.....111.....111` for all possible sizes of the square.
In my calculations, doing this with an anonymous lambda is just a tad shorter than defined function or a full program. The `or 1` part in the end is only necessary to handle the strange edge case, where we must output `1` if there are no ones in the input.
[Answer]
# [Python 2](https://docs.python.org/2/), 116 115 117 109 bytes
*Credits to @Kirill for helping me golf it even more and for his clever & early solution*
*Edit*: Golfed 1 byte by using a lambda, I didn't know assigning it to a variable didn't count towards the byte count.
*Edit 2*: Kirill pointed out my solution didn't work for cases where the input only contains `1`s, I had to fix it and lost two precious bytes...
*Edit 3*: more golfing thanks to Kirill
Takes a comma separated string, returns an integer.
```
lambda g:max(i*i for i in range(len(g))if re.search(("."*(g.find(",")+1-i)).join(["1"*i]*i),g))or 1
import re
```
[Try it online!](https://tio.run/##TYzBDoIwDIbvPEXTU4eTrB5JfBL1MIVBDWxkctCnn8Mg2uT/k35pv@k198Efkjue02DHa2Ohq0f7JCkFXIggIB6i9V1LQ@upU0ocxLZ6tDbeeiKssKSucuIbQo1qx3tRqroH8XRCxlIupSid/7KMCxmnEOcsSJsc2bAxOjezZv60yQg14MZ@9YcNa/Ml2bBmWdfjJVgXkGeK4mcQDY5EpTc "Python 2 – Try It Online")
I independently found an answer that is close to Kiril's one, i.e regex based, except that I use `re.search` and a `def`.
It uses a regex built during each loop to match an incrementally larger square and returns the largest one, or 1.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~61~~ ~~60~~ 58 bytes
```
{(^$_ X.. ^$_).max({[~&](.[|$^r||*])~~/$(1 x$r)/&&+$r})²}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WiNOJV4hQk9PAUhr6uUmVmhUR9epxWroRdeoxBXV1GjFatbV6atoGCpUqBRp6qupaasU1Woe2lT7vzixUiFNQ6@4ICezRENdR11TUyEtv4hLydDA0MBAB0gaGuoYGoJJA6CQkg6XElwMQSAJGxjqgFhK1v8B "Perl 6 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~138~~ 128 bytes
```
def f(m):j=''.join;L=j(m);k=map(j,zip(*m));return len(L)and max(len(L)*(len(m)**2*'1'==L),f(k[1:]),f(k[:-1]),f(m[1:]),f(m[:-1]))
```
[Try it online!](https://tio.run/##bY5BDoIwEEX3noLddBo0HZaQ3oAbEBYklEhxSkMwUS9fC9VojKv35/2/GH9fz7MrQujNkA2CsbQa4GTn0VW1tlFUk@bOC5s/Ri8kI1aLWa@Lyy7GiRo712fc3US65E5GKQsJBFrXmA9iaqhsUyiPtCd@K04Kg19Gt8YXGiBFSkG@kWgjvahiAS0ePtOvxQ/@z9QGlfrwBA "Python 2 – Try It Online")
---
Saved
* -10 bytes thanks to ovs
[Answer]
## Clojure, 193 bytes
```
#(apply max(for [f[(fn[a b](take-while seq(iterate a b)))]R(f next %)R(f butlast R)n[(count R)]c(for[i(range(-(count(first R))n -1)):when(apply = 1(for[r R c(subvec r i(+ i n))]c))](* n n))]c))
```
Wow, things escalated :o
Less golfed:
```
(def f #(for [rows (->> %    (iterate next)    (take-while seq)) ; row-postfixes
              rows (->> rows (iterate butlast) (take-while seq)) ; row-suffixes
              n    [(count rows)]
              c    (for[i(range(-(count(first rows))n -1)):when(every? pos?(for [row rows col(subvec row i(+ i n))]col))](* n n))] ; rectangular subsections
          c))
```
]


[Question]
      [
A string can be *shifted* by a number `n` by getting the byte value `c` of each character in the string, calculating `(c + n) mod 256`, and converting the result back to a character.
As an example, shifting `"ABC123"` by 1 results in `"BCD234"`, shifting by 10 in `"KLM;<="`, and shifting by 255 in `"@AB012"`.
### The Task
Pick as many numbers `n` with `0 < n < 256` as you dare and write a program or function that takes a string as input and
* returns the string unchanged when the source code is unchanged, but
* returns the string shifted by `n` when the source code is shifted by `n`.
### Rules
* The score of your submission is the number of supported `n`, with a higher score being better. The maximum score is thus 255.
* Your submission must support at least one shift, so the minimal score is 1.
* In case of a tie the shorter program wins.
* All shifted programs need to be in the same language.

[Answer]
# Brainfuck, score: 31 (2208 bytes)
Base64-encoded program:
```
LFsuLF0oVycnJycqKFkkUyMjIyMjIyMjJiRVIE8fHx8fHx8fHx8fHx8iIFEMOwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLDgw9CDcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcKCDkEMwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMGBDUAL8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w78CADHDrBvDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Ouw6wdw6gXw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Oqw6gZw6QTw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6bDpBXDoA/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Oiw6ARw4zDu8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OOw4zDvcOIw7fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OKw4jDucOEw7PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4bDhMO1w4DDr8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8OCw4DDscKsw5vCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8Krwq7CrMOdwqjDl8KpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqrCqMOZwqTDk8KlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKmwqTDlcKgw4/CocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqLCoMORwozCu8KNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKOwozCvcKIwrfCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJworCiMK5woTCs8KFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwobChMK1woDCr8KBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKCwoDCsWzCm21tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1ubMKdaMKXaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpamjCmWTCk2VlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZmTClWDCj2FhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFiYMKRTHtNTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU5MfUh3SUlJSUlJSUlJSUlJSUlJSUlJSUlJSUlJSUlJSUpIeURzRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRkR1QG9BQUFBQUFBQUFBQUFBQUFBQUFBQUJAcQ==
```
Works for shifts 0, 4, 8, 12, 32, 36, 40, 44, 64, 68, 72, 76, 96, 100, 104, 108, 128, 132, 136, 140, 160, 164, 168, 172, 192, 196, 200, 204, 224, 228, 232 and 236.
For every value between 0 and 255, there is exactly one of those shifts that sends that character to a valid brainfuck instruction.
The program relies on 8-bit cells with wrapping on overflows.
This could probably be golfed quite a bit, as the shift just consists of a repeated `+` or `-` (whichever is shorter).
Python code used to generate this:
```
l = [0, 4, 8, 12, 32, 36, 40, 44, 64, 68, 72, 76, 96, 100, 104, 108, 128, 132, 136, 140, 160, 164, 168, 172, 192, 196, 200, 204, 224, 228, 232, 236]
shift = lambda s,n:"".join(chr((ord(i)+n)%256) for i in s)
code = ""
for i in l:
    code += shift(",[{}.,]".format(i*"+" if i<=128 else (256-i)*"-"),-i)
```
[Answer]
# lHaskell, Score 255 (27,026 bytes)
The program works but putting it in my clipboard seems to destroy it so [here is code that outputs my program.](https://tio.run/##jZCxasNADIb3ewoRPMS0PkohtNDEg5MlQ6eOiSmqffEZ2yf3TkddyLu756YJgSzdfkmfxIc@0OlxLJAhhd5SZbGTrXZCFZpgJkRadz1Zhk@PbX2oVQkbZJTZN6s3trWpAB1kIu2wNquSYFgmmawUr8mwMuxeMtl7Dug@CgmLZh912M/v4qn2ZurAIMQMjmC90ega1bbXJuP4X4U/7He41mhF6lfPTxc1kd7KhV6weX2Hs@XuJHlynCcmji@aIRRkwqcCw9go8DDcX@EHS9023K2UlUznRLaMI6fpC0yAS0v9tJcfzTLZPUj5uFjk@Q8 "Bash – Try It Online")
## Verification
So if copying things to a clipboard breaks it how do I verify that it works?
You can use [this here](https://tio.run/##lVHBasJAEL3vVwwhUEPrUgRRqMkh9tJDvXhUKdNk3QSTnXSzSy347@lGa4iWgr09Zt7Mm/fmHeusaRbhZMqWoRfnEqi4AyGlx1iCBiKoNEmNJS@ymokkI/DysiJt4MNikW9zkcIzGuTxlxFLo3MlAWuIWYm5ClOC/WwYcynMnJQRytRPMa@sccy17xAmu7VfYjW49xdBW7GqrcHea6VHvBNlLLpNN/qv8IUsYx4cQFuVYb0TRdG3f9Voj3NHkjW9bPzl1Xy//RfnuKppbjX4Qzs25xlqFtlwOumMs@i3dVdzXl/f4JzB6hTBKYHBUAVBF4IDCSn3fMcxuBNgYf/Qo281lS9urxSaGzoj0mng1xl9gnLkVFPVzm0OajZcPXI@Go83m28). You can adjust `N` and the string (currently `Big ol' egg`) to see that it works yourself.
[This](https://tio.run/##tZFBa4MwGIbv@RUfElilM3SFssGqB7vLDvPSo5WRaapSTVz8pA76312sbbEdg112@8z3ap738YPXWdetXcvPU1DFHYg0tQiJOYIHlVap5iUrspqIOFNgNl5eVkojfDa8yLe5SOCFI2f@F4o16lymwGvwiVfyXLqJgnbp@CwVuFIShcT62WdVgya6oWbi8W5DS15Npnb/3Mj@BFpCLDiAbmTG650oijGJ4VINMmyRkMC1ZoZpn@WFgBBoAE6BMF8sICKJIjBA/xcyDa6grd7Y/CgLen8nypsi81GHY3RgpOubxlf7X1Pn@4ZQ4NKQBtOHvrwUXffX4qfYcbnKuCZe4z49XoQQ76cSc2YcvL3D2U04qBnMTBxp2xc1ZoiVNEpMBvlOQAPt/Si@1ap8Nd9NhWaozpPSiU3rTO1BmnCiVdW/Fx3k0glnjJmfHEXf) will test all N on a single input in succession but tends to time out.
## Explanation
This abuses literate Haskell's comment notation. In literate Haskell any line that does not start with `>` is a comment. So to make our code work we make 255 copies of the program each shifting by `n` and then we shift each individual copy by `-n`.
[Answer]
# C, score: 1 (73 bytes)
```
aZ0;/*0\:..*/f(s){puts(s);}//	e'bg`q)r(zenq':)r:**r(otsbg`q'')r*0($145(:|
```
[Try it online!](https://tio.run/##S9ZNT07@/z8xysBaX8sgxkpPT0s/TaNYs7qgtKQYSFvX6utzpqonpScUahZpVKXmFapbaRZZaWkVaeSXFIOE1dU1i7QMNFQMTUw1rGr@Z@aVKOQmZuZpaHJVcykAQZqGkqOTs6GRsZKmNVftfwA)
**Shifted by 1:**
```
b[1<0+1];//+0g)t*|qvut)t*<~00
f(char*s){for(;*s;++s)putchar((*s+1)%256);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z8p2tDGQNsw1lpfX9sgXbNEq6awrLQESNvUGRhwpWkkZyQWaRVrVqflF2lYaxVba2sXaxaUloCENTS0irUNNVWNTM00rWv/Z@aVKOQmZuZpaHJVcykAQZqGkqOTs6GRsZKmNVftfwA)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), Score: 3 (24 bytes)
```
¶Ä0(ä.g){n·Å0)åH*oHÆ0*æI
```
[Try it online!](https://tio.run/##AS4A0f8wNWFiMWX//8K2w4QwKMOkLmcpe27Ct8OFMCnDpUgqb0jDhjAqw6ZJ//90ZXN0 "05AB1E – Try It Online")
**Explanation**
```
¶Ä0(ä.g){n·Å0)åH*oHÆ0*æ  # Doesn't matter
                       I # Push the original input to the stack, implicit display
```
Shifted once:
```
·Å1)å/h*|o¸Æ1*æI+pIÇ1+çJ
```
[Try it online!](https://tio.run/##AS4A0f8wNWFiMWX//8K3w4UxKcOlL2gqfG/CuMOGMSrDpkkrcEnDhzErw6dK//90ZXN0 "05AB1E – Try It Online")
**Explanation**
```
·Å1)å/h*|o¸Æ1*æI+p       # Doesn't matter
                  IÇ     # Push the ASCII values of the input
                    1+   # Increment by 1
                      çJ # Push the chars of the ASCII values, join, implicit display
```
Shifted twice:
```
¸Æ2*æ0i+}p¹Ç2+çJ,qJÈ2,èK
```
[Try it online!](https://tio.run/##AS4A0f8wNWFiMWX//8K4w4YyKsOmMGkrfXDCucOHMivDp0oscUrDiDIsw6hL//90ZXN0 "05AB1E – Try It Online")
**Explanation**
```
Æ2*æ0i+}p         # Doesn't matter
         ¹Ç       # Push the ASCII values of the input
           2+     # Increment by 2
             çJ   # Push the chars of the ASCII values, join
               ,q # Print and terminate
```
Shifted thrice:
```
¹Ç3+ç1j,~qºÈ3,èK-rKÉ3-éL
```
[Try it online!](https://tio.run/##AS4A0f8wNWFiMWX//8K5w4czK8OnMWosfnHCusOIMyzDqEstckvDiTMtw6lM//90ZXN0 "05AB1E – Try It Online")
**Explanation**
```
¹Ç        # Push the ASCII values of the input
  3+      # Increment by 3
    ç1j   # Push the chars of the ASCII values, join
       ,q # Print and terminate
```
[Answer]
# Javascript, score: ~~1~~ 4 (~~94~~ 346 bytes)
Pretty straight-forward, has different sections commented out when rotated, the difficult bit was finding usable variable names and comment sections that don't break Javascript syntax.
Unrotated:
```
hc/*% *%nnS/0S eb^[fRR _SbS/0Efd[`Y Xda_5ZSd5aVWS UZSd5aVW3f"#&$'( \a[`RR!! %34hc/*$ifb_jVV$cWfW34Ijh_d]$\hec9^Wh9eZ[W$Y^Wh9eZ[7j&!'&(+,$`e_dVV%%%*89hc/)nkgdo[[)h\k#\89Nomdib)amjh>c\m>j_`###\)^c\m>j_`<o#+$&0$ -01$$$)ejdi[[***/=>/*ch*/hc//chhcchvw*/g¬©¥¢g¦©avw«¢§ g«¨¦|¡«|¨aaag¡«|¨zaibdjrrb^knobbbg£¨¢§
```
Rotated by 5:
```
mh4/*%$/*ssX45X%jgc`kWW%dXgX45Jki`e^%]ifd:_Xi:f[\X%Z_Xi:f[\8k' "(+ ),-   %af`eWW &&%*89mh4/)nkgdo[[)h\k#\89Nomdib)amjh>c\m>j_`###\)^c\m>j_`<o#+$&,+$ -01$$$)ejdi[[***/=>mh4.split``.map(a=>String.fromCharCode(((a.charCodeAt(0)+5)%256))).join``///4BC4/hm/4mh44hmmhhm{|/4l±®ª§²l«®f{|²°§¬¥l¤°«¦°¢£fffl¡¦°¢£²fngiowwgcpstgggl¨§¬
```
Rotated by 10:
```
rm94/*)4/xx$]9:]*olhep\\*i]l$]9:Opnejc*bnki?d]n?k`a$$$]*_d]n?k`a=p$,%'-0%!.12%%%*fkej\\%++*/=>rm94.split``.map(a=>String.fromCharCode(((a.charCodeAt(0)+10)%256))).join``///4BCrm93xuqnyee3rfu-fBCXywnsl3kwtrHmfwHtij---f3hmfwHtijFy-5.0:.*7:;...3otnsee4449GH94mr49rm99mrrmmr49q¶³¯¬·££q°¤³k¤·µ¬±ªq©µ²°«¤µ²§¨kkk¤q¦«¤µ²§¨·kslnt||lhuxylllq²¬±££
```
Rotated by 14: things finally got interesting here, got to abuse the Javascript type system.
```
vq=83.-83||(a=>a.split``.map(a=>String.fromCharCode(((a.charCodeAt(0)+14)%256))).join``)//.3ABvq=82wtpmxdd2qet,eABWxvmrk2jvsqGlevGshi,,,e2glevGshiEx,4-/54-)69:---2nsmrdd3338FGvq=7|yur}ii7vjy1jFG\}{rwp7o{xvLqj{Lxmn111j7lqj{LxmnJ}1924>2.;>?2227sxrwii888=KL=8qv8=vq==qvvqqv8=uº·³°»§§u´¨·o¨»¹°µ®u¹¶´¯¨¹¶«¬ooo¨uª¯¨¹¶«¬»owprxply|}pppu±¶°µ§§
```
Rotated by 199:
```
/*öñìçæñì55áö÷ç,)%"-ç&)áö÷-+"' ç+(&ü!+ü(áááç!+ü(ú-áéâäêíâÞëîïâââç#("'âèèçìúû/*öñë0-)&1ë*-åúû1/&+$ë#/,*%/,!"åååë %/,!"þ1åíæèîíæâïòóæææë',&+ìììñÿ/*öð52.+6""ð/#2ê#ÿ64+0)ð(41/*#41&'êêê#ð%*#41&'6êòëí÷ëçô÷øëëëð,1+0""ñññööñ*/ñö/*öö*//**/=>ñö.split``.map(a=>String.fromCharCode(((a.charCodeAt(0)+199)%256))).join``
```
To find the solutions, I [built a small tool](https://jsfiddle.net/po3ph24q/) to show me different snippets when rotated by a variable amount, I then found certain patterns that I could use as useful building blocks.
The main gist of it is that `a/**/=>a` is still a valid function definition, which allows you to embed a reverse rotated function in the comment section. From there on, it can be repeated a few times, if done correctly.
Since most of the comment sections are nested, it might be possible to find another result, but making it work becomes increasingly difficult with each added answer due to collisions and control characters.
---
Replacing all usages of `charCodeAt(0)` with `charCodeAt``` would shave 4 bytes off the whole solution, but it's too much work to do from scratch.
[Answer]
# [PHP](https://php.net/) with `-d output_buffering=on -d short_open_tag=on`, score: 255 (25,731 bytes)
```
<?die($argv[1]);?>
=@pc`dmfbo)*<ejf)qsfh`sfqmbdf`dbmmcbdl)#0/0#-gvodujpo)%n*|sfuvso!dis)pSe)%n\1^*.2*<~-%bshw\2^**<@?>Aqdaengcp*+=fkg*rtgiatgrncegaecnndcem*$101$.hwpevkqp*&o+}tgvwtp"ejt*qTf*&o]2_+/4+=.&ctix]3_++=A@?Brebfohdq+,>glh+suhjbuhsodfhbfdooedfn+%212%/ixqfwlrq+'p,~uhwxuq#fku+rUg+'p^3`,06,>?/'dujy^4`,,>BA
@Csfcgpier,-?hmi,tvikcvitpegicgeppfego,&323&0jyrgxmsr,(q-vixyvr$glv,sVh,(q_4a-18-??0(evkz_5a--?CBADtgdhqjfs-.@inj-uwjldwjuqfhjdhfqqgfhp-'434'1kzshynts-)r.?wjyzws%hmw-tWi-)r`5b.2:.@?1)fwl{`6b..@DCBEuheirkgt./Ajok.vxkmexkvrgikeigrrhgiq.(545(2l{tizout.*s/?xkz{xt&inx.uXj.*sa6c/3</A?2*gxm|a7c//AEDCFvifjslhu/0Bkpl/wylnfylwshjlfjhssihjr/)656)3m|uj{pvu/+t0?yl{|yu'joy/vYk/+tb7d04>0B?3+hyn}b8d00BFEDGwjgktmiv01Clqm0xzmogzmxtikmgkittjiks0*767*4n}vk|qwv0,u1?zm|}zv(kpz0wZl0,uc8e15@1C?4,izo~c9e11CGFEHxkhlunjw12Dmrn1y{nph{nyujlnhljuukjlt1+878+5o~wl}rxw1-v2?{n}~{w)lq{1x[m1-vd9f26B2D?5-j{pd:f22DHGFIylimvokx23Enso2z|oqi|ozvkmoimkvvlkmu2,989,6pxm~syx2.w3?|o~|x*mr|2y\n2.we:g37;:3E?6.k|q?e;g33EIHGJzmjnwply34Fotp3{}prj}p{wlnpjnlwwmlnv3-:9:-7q?yntzy3/x4?}p?}y+ns}3z]o3/xf;h48<<4F?7/l}r?f<h44FJIHK{nkoxqmz45Gpuq4|~qsk~q|xmoqkomxxnmow4.;:;.8r?zo?u{z40y5?~q??~z,ot~4{^p40yg<i59=>5G?80m~s?g=i55GKJIL|olpyrn{56Hqvr5}rtlr}ynprlpnyyonpx5/<;</9s?{p?v|{51z6?r??{-pu5|_q51zh=j6:>@6H?91nt?h>j66HLKJM}pmqzso|67Irws6~?sum?s~zoqsmqozzpoqy60=<=0:t?|q?w}|62{7??s???|.qv?6}`r62{i>k7;?A;?7I?:2o?u?i?k77IMLKN~qnr{tp}78Jsxt7?tvn?t{prtnrp{{qprz71>=>1;u?}r?x~}73|8??t???}/rw?7~as73|j?l8<@D8J?;3p?v?j@l88JNMLOros|uq~89Ktyu8??uwo?u?|qsuosq||rqs{82?>?2<v?~s?y~84}9??u???~0sx?8bt84}k@m9=AF9K?<4q?w?kAm99KONMP?spt}vr9:Luzv9??vxp?v?}rtvptr}}srt|93@?@3=w?t?z?95~:??v???1ty?9?cu95~lAn:>BH:L?=5r?x?lBn::LPO
...
```
Similar to the Haskell solution, copying and pasting this breaks, so I generated this using [this Perl script](https://tio.run/##vdzNThMBFIbhvVdhSDWdSGHOmf9A5B7cEkNKGZFYaDOAG@OtW8vGjet51ka/FHhbhKdnP07b5nB4Pj8733yflsvddLdcfCw@LRdnqyiKD9m0xfn9@Hw4XF7dPYzLxXq6/3kdX4uLq8/vLq92tzeb7bh@WhYXb3@6n8b7m2ncb9eb8Waz3m5v15sfy5PjP35y@u31afPysHtaLh6LX9P48jo9vX@b3H05Lj5el1@L4@DF79N/C7NM5PwT1fwT9fwTzfwT7fwT3fwT/fwTw/wTUYIN0HeAwKMSG@LZMEDlATIP0HmA0AOUnqD0FK/koPQEpWctNsj3VqD0BKUnKD1B6RUovQJfV5X4ph2UXoHSq0ZsiGeTCpRegdIrUHoNSq/B57wGpdfi/@eg9BqUXrdiQzyb1KD0GpTegNIb8PloQOkNKL0RP4oDpTeg9KYTG@LZpAGlt6D0FnysWlB6C0pvQemt@Kk7KL0Fpbe92BDPJh0ovROPA5TegdI7UHoHSu/EL9hA6R0ovQOv6D3ovAed96DzHnTeg8570HkPOu/Fb9JB5z3ofACdD6DzAXQ@gM4H0PkAOh9A5wPofBBkhpgZgWZK4UDKJCPEtJS1GBFyphR0phR2phR4phTNGygnOiFUjlg5hOWIliNcjng5AuaEmAtB5iKJjhXNCzUXgs2FcXMh4FwIOReCzoWwcyHwXAg9FxUh8cTEi@aFoAtD6EIYuhCILirSfJC32lRpZiozU5uZxsx0q97MkEfTm5mBzDSleU@UeOVvyCMRr/xC2YVgdiGcXQhoF0LahaF2IaxdCGwXQtuF4HYhvF0IcBcteQesaF6YuxDoLoy6C8HuoiOPRDQv5F0IehfC3kVH3vYumhf8LoS/CwHwQgi8EAQvhMELgfBCKLwQDC96culCFC8kXgiKF8LihcB4ITReCI4XwuOFAHkhRF4M5LgNuW4jztsIk5fC5KUxeSlMXgqTl8LkpTB5KUxeCpOXQU5aiU6EyUth8o4jKzIjmhcmL4XJS2HyklyxI2fszB070Ty5ZEdO2aFbduSYHblmR87ZCZOXwuSlMHlZkeOVonlh8lKYvDQmL4XJS2HyUpi8FKftUty2S3HcLmtysZacrBXNiwN3aS7cpThxlzVpfjAfsGGVZqYyM7WZaczM/2n@2e3f/t7zYbX/Cw "Perl 5 – Try It Online").
[Verification for shifted 1, 16, 32 and 255 times.](https://tio.run/##vZ3LbtpQFEXnfIWVpg2oJfE@19ePQpNpx32MqgoZuAmoxLYMVKqqfnvqPBpVqqiUSF6zyE68j4FlO7C8mZfb1U0T2k00bkJ0sj07PVus2uGwbpfD41ej18Pj07FGo5fm09HZVTiJptNpdDK9WK7D8Lhsr75/0dfR5OJ8ML2o57PFJpTVcDS5Xdu04WrWhmZTLsJsUW4283LxbXjUBRy9udxXi926robH16Ofbdjt2yq6ja0/dKnXX@Kvoy508uvNY0IvEdZ/hOs/Iuk/wvcfkfYfkfUfkfcfUfQfoRjIAPgWALgckUEcDQVQLgBzAZwLAF0A6QaQbsSZHCDdANItITKQayuAdANIN4B0A0h3AOkOeF054qIdIN0BpDtPZBBHEweQ7gDSHUB6ApCeAM95ApCeEP@fA6QnAOlJSmQQR5MEID0BSPcA6R54PjxAugdI98RbcQDpHiDdZ0QGcTTxAOkpQHoKPFYpQHoKkJ4CpKfEu@4A6SlAepoTGcTRJANIz4j9AEjPANIzgPQMID0jPmADSM8A0jPgjJ4DnOcA5znAeQ5wngOc5wDnOcB5TnySDnCeA5wXAOcFwHkBcF4AnBcA5wXAeQFwXgCcF4QygzgzhDQTEx5IbEgI4rTECRFCmDMxoc7EhDsTE/JMTDDPiHIEJ4gqh7hykCyH2HKILof4cogwRxhzIpQ5GWLHEswT1pwIbU6MNydCnBNhzolQ50S4cyLkORH2nByixCNOPME8YdCJUehEOHQiJDo5hHkht9o4Y2IcE5MwMZ6JycY5E4PsTc7EFEiMj5l7oogzv0f2hDjzE5adCM1OhGcnQrQTYdqJUe1EuHYiZDsRtp0I3U6EbydCuFOK3AFLME84dyKkOzHWnQjtThmyJwTzhHknQr0T4d4pQ257J5gn9DsR/p0IAU@EgSdCwRPh4ImQ8ERYeCI0POVI0wVBPGHiiVDxRLh4ImQ8ETaeCB1PhI8nQsgTYeSpQMptkHYbot6GcPKMcPKMcfKMcPKMcPKMcPKMcPKMcPKMcPJMSKUVwQnh5Bnh5HUhYySGYJ5w8oxw8oxw8gxpsUNq7JgeO4J5pMkOqbKDuuyQMjukzQ6psyOcPCOcPCOcPHNIeSXBPOHkGeHkGePkGeHkGeHkGeHkGVFtZ0S3nRHldpYgjbVIZS3BPFFwZ0zDnREVd5YgzBfMA1aMjYlxTEzCxHgm5l80T6LzaFs3p82qmdy8@PNjtGhDuQvLaF1F70O5DO1gEBarOjr6XG1X68tu1dujyeD2N8fLaLuq292sbkI125VX7@rqdmG93zX73Wy@v7wM7bq6W/xn65/CdtctutvkZDA4/L0p3Wv2r69Mefz7u5F1N/PDWB/vh4rmPyI9czI9dbT0P7Olh4ZLnztd@sTxusvhg@M5OzCes2eOd7/FJ4xn3h@er1t5YMBuzTMnfNjm44g3N78B "Bash – Try It Online")
## Explanation
Using PHP's `<?` delimiter made this fairly easy, but I had to avoid any strings that could end up as `<?` elsewhere in the code, this basically means `03`, `14`, `25`, `36`, `47`, `58` and `69`. Working around those was fairly easy using arithmetic. It might well be possible to reduce the byte count in the original program too.
[Answer]
# [Crane-Flak](https://github.com/Flakheads/CraneFlak), Score 3 (252 bytes)
```
%&'()%&%X'Z&xx\()'()z%xz|%&'()%&'()%&'()9;=&'()9;=%XZ\&'z|%&'(9;=(9;=%&'XZ\(|xz|9;=%&'%&(%X'Z&\('()xxz%xz|9;=&'()9;=%XZ\&'z|9;=(9;=%&'XZ\(|9;=)))))))%&Y[]'()yy{}%&y{}%&'()%&'():<>'():<>%&Y[]'(){}y{}:<>%&Y[]'()yy{}::<><>:<>%&y{}:<>'():<>%&Y[]'(){}::<><>
```
[Try it online!](https://tio.run/##SypKzMzLSEzO/v9fVU1dQ1NVTTVCPUqtoiJGQxPIrVKtqKqBSsAIS2tbKKUaERWjpg5RAOSCMJAJFNSoAWqD8FTVNMAmxmgA9VRUgA3ENAFNN5CpCQGqapHRsUC1lZXVtapqYALmDisbOwgJU1NdC5RH4oP0WAH5NnZgQYgkuhaIgv///@s6/lcayUGgBAA "Brain-Flak (BrainHack) – Try It Online")
*(Doesn't quite work in Brain-Hack because only Crane-Flak mods by 256)*
**Shifted by 1**
```
&'()*&'&Y(['yy])*()*{&y{}&'()*&'()*&'()*:<>'()*:<>&Y[]'({}&'():<>):<>&'(Y[])}y{}:<>&'(&')&Y(['])()*yy{&y{}:<>'()*:<>&Y[]'({}:<>):<>&'(Y[])}:<>*******&'Z\^()*zz|~&'z|~&'()*&'()*;=?()*;=?&'Z\^()*|~z|~;=?&'Z\^()*zz|~;;=?=?;=?&'z|~;=?()*;=?&'Z\^()*|~;;=?=?
```
[Try it online!](https://tio.run/##ZVBbDsIgELxLExZo4gG0tsZbaB8m6o/GxA@/oK@r48CC0UrCsLM7MyF7eZ3vz9v5@nCOpNI5STqqRlrb6Rx0IDtMcZBgs63iQ8emk4oFoP6iRFNPsDEjqUNip@GxNgT@JyzcKHM@JOv2BG3fjzPJAOkfRbljTJpxxvyLe08BXu5Ck4dLCwucc6u9y4QPFiQOsiZjWqVBe2H6MQ4SrIsyPuJQtz7at0H9RYmmGmFjJkiFxFbBY0wI/E9YuFFqPoKXpLG8SVCA9A9eJDBphrj4b88GfFuF5mf3PxYWZG8 "Brain-Flak (BrainHack) – Try It Online")
**Shifted by 2**
```
'()*+'('Z)\(zz^*+)*+|'z|~'()*+'()*+'()*+;=?()*+;=?'Z\^()|~'()*;=?*;=?'()Z\^*~z|~;=?'()'(*'Z)\(^*)*+zz|'z|~;=?()*+;=?'Z\^()|~;=?*;=?'()Z\^*~;=?+++++++'([]_)*+{{}'({}'()*+'()*+<>@)*+<>@'([]_)*+}{}<>@'([]_)*+{{}<<>@>@<>@'({}<>@)*+<>@'([]_)*+}<<>@>@
```
[Try it online!](https://tio.run/##ZU5bbsIwELwLkr1rRz0AEFJ6CwgmiPYHVKkf/TJOAkc3Y28soWDJ452dh/z9f77@Xc4/vzESG1sRU2sch9DZCnSgMNwnocB68zk91LqOjRhA08WIpb0jJozY5sbOIhNCLnxvmKUxVnKID8cTvH0/PogzlH/UzVaweMYH9BeeMjV4s81LEecRMcQYP77iQmk0K6121GrvXfq9CcqHYRIKLNeb6VG71mkSA2i6GLHkATFhSnNudIyM97nwvWGWxmjkKL0/HOG93fpR6QzlH6u6ESyefoT@wlNmBV43eSniPCKGxRM "Brain-Flak (BrainHack) – Try It Online")
**Shifted by 3**
```
()*+,()([*]){{_+,*+,}({}()*+,()*+,()*+,<>@)*+,<>@([]_)*}()*+<>@+<>@()*[]_+{}<>@()*()+([*])_+*+,{{}({}<>@)*+,<>@([]_)*}<>@+<>@()*[]_+<>@,,,,,,,()\^`*+,||~€()|~€()*+,()*+,=?A*+,=?A()\^`*+,~€|~€=?A()\^`*+,||~€==?A?A=?A()|~€=?A*+,=?A()\^`*+,~€==?A?A
```
[Try it online!](https://tio.run/##ZU5bboMwELxLJJtdTA/QFEi4RRqgNO1Pq0r9yJcTQ9Oz9WLu4LWlCCx5vLPzkN/Op8/vj9P7l/fEuSmIqc17dm4wBehEbrpFIUFZ7@NDbT9wLgbQ@WLE0twQE0ZsQuNgkHEuFK4bFmmMhRzi7uUV3nH8@fslFkw/qXaNYHJBnR13m5CrsNg1YRvlVUws3vuHxm@UzoiVVofsqK3tiEGvyl7HKCR4fKriow7HTmdiAJ0vRixpREyY0hQaO0LG2lC4blikMbIcpZ/bHt7LxU1KB0j/2Ja1YPK4CfodnzNb8LIOSxGXETFs/gE "Brain-Flak (BrainHack) – Try It Online")
## Explanation
The main code at work here is
```
([]){{}({}n<>)<>([])}{}<>([]){{}({}<>)<>([])}<>
```
where `n` is an arbitrary number. This moves everything to the offstack adding `n` to each item (modulo 256 is implicit upon output), and then moves them all back.
However for the first program (i.e. shifted by 0) we don't need to do any of this because shifting by zero is the cat program. So we start with this code:
```
([]){{}({}()<>)<>([])}{}<>([]){{}({}<>)<>([])}<>
```
and shift it down by 1
```
'Z\(zz|'z|m;=(;='Z\(|z|;='Z\(zz|'z|;=(;='Z\(|;=
```
This is unbalanced so we have to fix it. There are a number of ways we could do this by my choice method (for reasons that will become apparent) is the following:
```
'Z\(zz|'z|m;=(;='Z\(|z|;='Z\(zz|'z|;=(;='Z\(|;=)))))){}{}{}{}{}
```
Shifting this up by 2 we get
```
)\^*||~)|~o=?*=?)\^*~|~=?)\^*||~)|~=?*=?)\^*~=?++++++}}}}}
```
Since `()` is easier to deal with than `{}` we will use the `}`s to complete the program we desire. That means that the `)` can be balanced with pretty obvious means. With some fiddling we can turn that into:
```
()\^*||~()|~()*=?*=?()\^*~|~=?()\^*||~()|~=?*=?()\^*~=?+++++++([]_)*+{{}({}()*+()*+<>@)*+<>@([]_)*+}{}<>@([]_)*+{{}<<>@>@<>@({}<>@)*+<>@([]_)*+}<<>@>@
```
Shifting that back down we get
```
&'Z\(zz|&'z|&'(;=(;=&'Z\(|z|;=&'Z\(zz|&'z|;=(;=&'Z\(|;=)))))))&Y[]'()yy{}&y{}&'()&'():<>'():<>&Y[]'(){}y{}:<>&Y[]'()yy{}::<><>:<>&y{}:<>'():<>&Y[]'(){}::<><>
```
The step up to 3 is so complex I don't really understand it any more. I used the same technique and just fiddled around with it until I finally got all 4 of them to work at once. The technique is pretty much the same there is just a lot more fiddling.
[Answer]
# Python 3, Score 1, 76 bytes
Shift 0: no change
```
""!="";print(input());exit()#   oqhms'&&-inhm'bgq'nqc'i(*0(enq'i(hm'hmots'((((
```
Shift 1:
```
##">##<qsjou)joqvu)**<fyju)*$
print(''.join(chr(ord(j)+1)for(j)in(input())))
```
Started work on shift 2, but "" becomes $$ and you can't start a line with that.
When you save it to a file, make sure it doesn't end with a newline. (vim -b file.py + set noeol)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), score ~~1~~ 2
## ~~8~~ 15 bytes
**Shift 0:**
```
M««Ṃ¬ịị¶Ɓ|L(0Ḷṇ
```
[Try it online!](https://tio.run/##y0rNyan8/9/30OpDqx/ubDq05uHubiA6tO1YY42PhsHDHdse7mz///@/uqOTs6GRsToA "Jelly – Try It Online")
**Shift 2:**
```
O‘‘Ọµḷḷ¹Ɗ~N*2Ṇṛ
```
[Try 2 online!](https://tio.run/##y0rNyan8/9//UcMMIHq4u@fQ1oc7tgPRoZ3Huur8tIwe7mx7uHP2////1R2dnA2NjNUB)
**Shift 3:**
```
P’’Ṛ½ṃṃ²Ƒ¶O+3Ọṣ
```
[Try 3 online!](https://tio.run/##y0rNyan8/z/gUcNMIHq4c9ahvQ93NgPRoU3HJh7a5q9t/HB3z8Odi////6/u6ORsaGSsDgA)
]


[Question]
      [
Write a function or program that determines the *cost* of a given string, where
* the cost of each character equals the number of how many times the character has occurred up to this point in the string, and
* the cost of the string is the sum of its characters' costs.
### Example
For an input of `abaacab`, the cost is computed as follows:
```
a b a a c a b
1   2 3   4    occurrence of a
  1         2  occurrence of b
        1      occurrence of c
1+1+2+3+1+4+2 = 14
```
Thus the cost for the string `abaacab` is 14.
### Rules
* **The score of your submission is the cost of your code as defined above**, that is your submission run on its own source code, with a **lower** score being better.
* Your submission should work on strings containing printable ASCII-characters, plus all characters used in your submission.
* Characters are case-sensitive, that is `a` and `A` are different characters.
### Testcases
```
input -> output
"abaacab" -> 14
"Programming Puzzles & Code Golf" -> 47
"" -> 0
"       " -> 28
"abcdefg" -> 7
"aA" -> 2
```
### Leaderboard
```
var QUESTION_ID=127261,OVERRIDE_USER=56433;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} /* font fix */ body {font-family: Arial,"Helvetica Neue",Helvetica,sans-serif;} /* #language-list x-pos fix */ #answer-list {margin-right: 200px;}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Score</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

[Answer]
# Common Lisp, score ~~286~~ ~~232~~ 222
```
(loop with w =(fill(make-list 128)0)as z across(read)sum(incf(elt w(char-code z))))
```
High-valued score due to the wordy syntax of builtin operators of Common Lisp.
[Try it online!](https://tio.run/##tcwxCoAwDEDRqwSnZBDUycXDhFgxGG1pKgUvX72Ef358MfXUMGW9SkOLMUHVskOFBTc1w5OP0H@owDjNNBA7PMCSozvmwCv5faJesmGwAhVl59xLXAM89NWodT9suxc)
The ungolfed code:
```
(loop with w = (fill (make-list 128) 0)  ; create a list to count characters
   as z across (read)                   ; for each character of input
   sum (incf (elt w (char-code z))))     ; increase count in list and sum
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), score 897
```
,[<<[[->+>-<<]>>[<]<[<]<[<]<[+<<]>>>>[>]>[->+>+<<]>[-<+>]<<<]<+[->>+<<]>>>[->+<]>[>]>,]<<[<]<
```
[Try it online!](https://tio.run/##ZU5BDsIwDLvvFb1n5QVW3sA96qGdQJoYO2zs/cVpYUIiUhXHcVyXLc/r/ZgetY4GmEUVjUBSNSScTxpFUpM2TSMsQjSBEEJWPyoX@JbakVs3qO3U/ROn4brN62sP021ZQt7DejzLbRtMuzFicyEQdl6wGyId5Czwk0hCPZD0IG2Cl0dLQwhftaF3mrmv6C9weULL/y/n4tJD11xynnJ5Aw "brainfuck – Try It Online")
Ends on the cell with the correct value. Assumes a cell size larger than the score of the string, otherwise it'll wrap (got a little suspicious when the interpreter said the score was 188).
[Answer]
# [Husk](https://github.com/barbuz/Husk), Score 9
```
½§+L(Σ´×=
```
[Try it online!](https://tio.run/##yygtzv7//9DeQ8u1fTTOLT605fB02////ycmIWAyAA "Husk – Try It Online")
**Explanation:**
This calculates the score as `sum_i (n_i^2 + n_i)/2`, where `i` is indexed arbitrarily across unique character types and `n_i` is the number of characters of type i in the input. But since `sum_i n_i` is the length of the input, this reduces to `(1/2) * (L + sum_i n_i^2)`
**Code breakdown:**
```
o ½ (§ + L (o Σ (´ (× =)))        --With parentheses and two implicit compositions
                   (× =)          --1 or 0 for each equality check between elements of its first and second arguments
                (´ (× =))         --argdup, 1 or 0 for each equality check between elements of its only argument
           (o Σ (´ (× =))         --# of equalities between pairs (this will give sum_i n_i^2)
         L                        --length
    (§ + L (o Σ (´ (× =)))        --length + sum_i n_i^2
o ½ (§ + L (o Σ (´ (× =)))        --1/2 * (length + sum_i n_i^2)
```
[Answer]
# Rust, ~~265~~ 255 bytes. Score: ~~1459~~ 1161
```
fn main(){let mut z=String::new();std::io::stdin().read_line(&mut z);let Z=z.trim_right_matches(|x|x=='\r'||x=='\n');let mut q:Vec<u8>=Z.bytes().collect();q.sort();let(mut k,mut W,mut j)=(0,0u8,0);for Y in&q{if*Y==W{j+=1}else{j=1;W=*Y}k+=j}print!("{}",k)}
```
Ungolfed
```
fn main() {
    let mut input_string = String::new();
    std::io::stdin().read_line(&mut input_string);
    let trimmed = input_string
        .trim_right_matches(|c| c == '\r' || c == '\n');
    let mut chars: Vec<u8> = trimmed.bytes().collect();
    chars.sort();
    let (mut total_score, mut last_char, mut last_score) = (0, 0u8, 0);
    for letter in &chars {
        if *letter == last_char {
            last_score += 1;
        } else {
            last_score = 1;
            last_char = *letter;
        }
        total_score += last_score;
    }
    print!("{}", total_score);
}
```
**Edit:** improved answer by renaming variables and altering code
[Answer]
# Python 2. Score:~~142~~ 115
```
def     f(a):
        x=0
        for y in set(a):z=a.count(y);x+=.5*z*-~z
        print x
```
EDIT:-27 thanks to @Kevin Cruijssen
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), score: 681
```
	s	=iNPUT
	Y	_table()
d	S	LEN(1) . x REM . S	:F(b)
	Y<X>	=y<X> + 1	:(D)
b	Z	_convert(Y,'aRrAy')
N	j	=J + 1
	G	_z[j,2]	:f(q)
	o	=o + g * G + g	:(N)
q	OUtpuT	_O / 2
end
```
[Try it online!](https://tio.run/##fc5JawJBEAXg8@tfUTe7VRTF05QdCLiA6BhcwIXQOHESFJl2GUX989qO4ALGS71DPR7fJrKBXZROJ2ygZ/5XvycwhIknwSKUSkzRRbPqy4KiHO2pU2257MKryUC5YnnwAX1wlzJUgCcrSgQYwfzYaBeuYznMpiad9echpYSPOXTj0hOowxzH82zxG96vXLkhC23d64/SVL@km/KVWKHdj5fbHkyb8lQUYTRNnCZx8oOT3zn56jRPTv7HyXcnO6d@dPJrJ9@cOnGyc54B "SNOBOL4 (CSNOBOL4) – Try It Online")
looks a bit scary, but SNOBOL matches identifiers case-insensitively, which dropped the score by around 100 points. Note that it requires a single line of input, so I've replaced `\n` with `;` in the input field (which is still valid SNOBOL).
The SNOBOL4 implementation on TIO allows for an additional 16 point golf, as `=` and `_` are [both allowable as the assignment operator](http://www.snobol4.org/csnobol4/curr/doc/snobol4.1.html). How neat!
[Answer]
# Mathematica, score 42
```
Total[#^2+#].5&@*CharacterCounts
```
**input**
>
> ["abcdefg"]
>
>
>
thanks to hftf
thanks to att
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes, score 5
```
ΣṁŀgO
```
[Try it online!](https://tio.run/##yygtzv7//9zihzsbjzak@////z8xKTExOTEJAA "Husk – Try It Online")
Different and (so far) shorter strategy to [Natte's](https://codegolf.stackexchange.com/a/241169/95126) or [Sophia Lechner's](https://codegolf.stackexchange.com/a/158410/95126) Husk answers.
```
    O   # sort the input
   g    # and group equal adjacent values;
 ṁ      # now, for each group
  ŀ     # make a range 1..length of the group
 ṁ      # and flatten all the ranges into one list;
Σ       # then output the sum
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), score ~~27~~ ~~18~~ ~~11~~ 10
*Reduced score by 7 thanks to @Adám by using a tradfn and using `1⊥` to sum the frequencies*
*Reduced score by 1 thanks to @rabbitgrowth by using a function instead*
```
1⊥{+/⍳≢⍵}⌸
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/hR2wTDR11Lq7X1H/VuftS56FHv1tpHPTuAMurYxNUB "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), ~~9~~ ~~7~~ 6 points
```
ü mÊcõ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=/CBtymP1&input=Ivwgbcpj9SI)
[Answer]
# Python 2, score 83
```
lambda z:sum((2*z.count(x)+1)**2/8for x in set(z))
```
[**Try it online**](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHKqrg0V0PDSKtKLzm/NK9Eo0JT21BTS8tI3yItv0ihQiEzT6E4tUSjSlPzf7FtDJc66frUuQqKMvNKFNI0ijX/AwA)
`1/8 (1 + 2 n)^2 -1/8` is the same as `n (n+1) / 2`. Floor division removes the need to subtract `1/8`.
[Answer]
## Clojure, score 96
```
#(apply +(for[[k j](frequencies %)](*(inc j)j 0.5)))
```
Five spaces and pairs of brackets...
[Answer]
# [Actually](https://github.com/Mego/Seriously), score 12
```
;╗╔⌠╜cRΣ⌡MΣ
```
[Try it online!](https://tio.run/##S0wuKU3Myan8/9/60dTpj6ZOedSz4NHUOclB5xY/6lnoe27x//9KOGSUAA "Actually – Try It Online")
Explanation:
```
;╗╔⌠╜cRΣ⌡MΣ  (implicit input: S)
;╗           save a copy of S in register 0
  ╔          uniquify S (call it A)
   ⌠╜cRΣ⌡M   for each unique character in A:
    ╜c         count the number of occurrences in S
      R        range(1, count+1)
       Σ       sum
          Σ  sum
```
Repeating the `Σ` is two points less than using an alternative formulation with no repeated characters (`i`+Y`).
[Answer]
# [J](http://jsoftware.com/), score 23
```
$-:@+[:+/,/@(=/~)
```
[Try it online!](https://tio.run/##y/r/P83WSkXXykE72kpbX0ffQcNWv07zf2pyRr5CmoI6how6F0wqMSkxMTkxCSEQUJSfXpSYm5uZl64QUFpVlZNarKCm4Jyfkqrgnp@ThlCIYClAALKhySmpaelIAo7q/wE "J – Try It Online")
[Answer]
## F#, score:~~1264~~1110
-154 points, thanks to @Laikoni
```
let x(y:bool)=System.Convert.ToInt32(y)
let rec p(k:string)q=
 let j=k.Length
 if(j=1)then(x(k.[0]=q))else p k.[0..(j-2)] q+x(k.[j-1]=q)
let rec d(a:string)=
 let z=a.Length
 if(z<2)then z else d a.[0..(z-2)]+p a (a.[z-1])
```
You need to call the d function. In a more readable form:
```
let x (y:bool)=
    System.Convert.ToInt32(y)
let rec e (c:string) b=
    let j=c.Length
    if(j=1)then
        (x(c.[0]=b))
    else
        e c.[0..(j-2)] b+x (c.[j-1]=b)
let rec d (a:string)=
    let h=a.Length
    if(h<2)then
        h
    else
        d a.[0..(h-2)]+e a (a.[h-1])
```
### Explanation
It is a recursive algorithm, the base case is, if the length of the string is less than 2 (0 or 1), the score will be the length of the string. This is because, if the length is 0 (empty string), we have no characters, so the score is 0, and if the length is 1, that means, that the string consists of only 1 character, so the score is 1.
Otherwise it trims the last character of the string, and to the score of the truncated string adds the count of the last character in the untruncated string.
The counting algorithm is also recursive. Its base case is, when the length of the string is one, then the count is 1, if the string matches with the character, and 0 otherwise. This can also be done, if we convert the bool to an int, and this results in a lower score.
Otherwise it trims the last character of the string, calculates the count of that string, and if the last character matches the character, we are calculating the count of, adds one to the count. This is again, better, if we convert that boolean to an int.
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 39 bytes, Score 54
```
BEGIN{RS="(.)"}{M+=++s[RT]}END{print M}
```
[Try it online!](https://tio.run/##SyzP/v/fydXd0686KNhWSUNPU6m22lfbVlu7ODooJLbW1c@luqAoM69EwbeWaIUA "AWK – Try It Online")
[Answer]
**FIREBIRD, score 3577**
Version to calculte the score:
```
SELECT COALESCE(SUM(C),0)FROM(WITH RECURSIVE T AS(SELECT 1 AS I,SUBSTRING(CAST(:V AS BLOB)FROM 1 FOR 1)AS S FROM RDB$DATABASE UNION ALL SELECT I+1,SUBSTRING(CAST(:V AS BLOB)FROM I+1 FOR 1)FROM T WHERE I < CHAR_LENGTH(CAST(:V AS BLOB)))SELECT T.*,(SELECT COUNT(T2.I) FROM T T2 WHERE T2.S=T.S AND T2.I<=T.I)AS C FROM T WHERE CAST(:V AS BLOB) <> '')
```
Below is the idented version of the code, in case anyone want to now. I'm sorry for any mistakes, first time here actually posting!
```
SELECT COALESCE(SUM(C), 0)
FROM (
  WITH RECURSIVE T AS (
    SELECT 1 AS I, SUBSTRING(CAST(:V AS BLOB) FROM 1 FOR 1) AS S
    FROM RDB$DATABASE
    UNION ALL
    SELECT I+1, SUBSTRING(CAST(:V AS BLOB) FROM I+1 FOR 1)
    FROM T
    WHERE I < CHAR_LENGTH(CAST(:V AS BLOB))
  )
  SELECT T.*, (SELECT COUNT(T2.I) FROM T T2 WHERE T2.S = T.S AND T2.I <= T.I) AS C
  FROM T
  WHERE CAST(:V AS BLOB) <> ''
)
```
---
**Explanation**
I start my select in a system table `SELECT 1 AS I, SUBSTRING(CAST(:V AS BLOB) FROM 1 FOR 1) AS S FROM RDB$DATABASE`, which always has only one row. Using that only one row, I return 1 as a column **I**, and the character that exists in the input in the I value.
Let's say I've passed 'abaacab' as input:
```
╔═══╦═══╗
║ I ║ S ║
╠═══╬═══╣
║ 1 ║ a ║
╚═══╩═══╝
```
In the UNION ALL part, I start to increment the index from the first select, until it reaches the end of the input. So, in the example I would get this:
```
╔═══╦═══╗
║ I ║ S ║
╠═══╬═══╣
║ 1 ║ a ║
║ 2 ║ b ║
║ 3 ║ a ║
║ 4 ║ a ║
║ 5 ║ c ║
║ 6 ║ a ║
║ 7 ║ b ║
╚═══╩═══╝
```
After that, I also select the count of ocurrences from the value on **S**, that has already appeared in indexes below the **I**. So, in a column **C** I now have the 'cost' of that character, which I only need to SUM after to get the value.
```
╔═══╦═══╦═══╗
║ I ║ S ║ C ║
╠═══╬═══╬═══╣
║ 1 ║ a ║ 1 ║
║ 2 ║ b ║ 1 ║
║ 3 ║ a ║ 2 ║
║ 4 ║ a ║ 3 ║
║ 5 ║ c ║ 1 ║
║ 6 ║ a ║ 4 ║
║ 7 ║ b ║ 2 ║
╚═══╩═══╩═══╝
```
I used BLOB as the type from the input, to not get limited by size.
[Answer]
## [K](https://en.wikipedia.org/wiki/K_(programming_language))/[Kona](https://github.com/kevinlawler/kona), score 19
```
+/,/1+!:'(#:)'=
```
Works as:
```
              = (implicitly take arg as input), group -> make dictionary of characters to their occurring indices
         (#:)'= count each of these
    1+!:'(#:)'= get a list from 0->n-1 for each of these counts, add one to each
+/,/1+!:'(#:)'= finally, reduce to single list, sum reduce this list
```
Example:
```
k)+/,/1+!:'(#:)'="+/,/1+!:'(#:)'="
19
k)+/,/1+!:'(#:)'="abaacab"
14
```
Legible q equivalent:
```
(sum/)raze 1+til count each group
```
[Answer]
# [Pyke](https://github.com/muddyfish/PYKE), score 7
```
cemSss
```
[Try it here!](http://pyke.catbus.co.uk/?code=cemSss&input=%5B%22c%22%2C%22e%22%2C%22m%22%2C%22S%22%2C%22s%22%2C%22s%22%5D&warnings=1&hex=0)
```
c      -    count_occurrences(input)
 e     -   values(^)
  mS   -  [range(1,i+1) for i in ^]
    ss - sum(sum(i)for i in ^)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 bytes; Score ~~10~~ 9
```
ṢŒrzẆṪRẎS
```
[Try it online!](https://tio.run/##y0rNyan8///hzkVHJxVVPdzV9nDnqqCHu/qC/2MTBAA "Jelly – Try It Online")
This is the first time I use Jelly, and I didn't want to check other people's answers because I wanted to try it myself. I probably reinvented the wheel a couple times there. Suggestions and feedback are greatly appreciated.
EDIT: -1 byte for removing `ɠ` and taking the input as an argument.
Explanation:
```
ṢŒrzẆṪRẎS           #Main Link; input abaacab
Ṣ                   #sorts input; aaaabbc
 Œr                 #run-length encode, or the number of times a character appears; a4b2c1
   z                #zip; ['abc', [4, 2, 1]]
    Ẇ               #takes every contiguous sublists
     Ṫ              #Pops the last element; [4, 2, 1]
      R             #Takes the range of every element; [[1,2,3,4],[1,2],1]
       Ẏ            #Collapses every element into a single array; [1,2,3,4,1,2,1]
        S           #Sum and implicitly print; 14.
```
(no idea why, but the code doesn't work without `Ẇ`,
 although it gives the exact same output as `z`)
[Answer]
# [J](http://jsoftware.com/), score 14
```
1#.2!1+#/.~
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DZX1jBQNtZX19er@a3KlJmfkK6QppJalFlUqqCcmJSYmJyapK1grqAcU5acXJebmZualKwSUVlXlpBYrqCk456ekKrjn56SB1YAJBQgAsxOTklNS09IhbEd1mPHqSJaq/wcA "J – Try It Online")
Outgolfed by the other J solution, but figured I'd post this anyways since it uses a slightly different method.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), score 12 (+2 for `-x`) = 14
```
¬n ó¥ ËÊõÃc
```
## Explanation
```
¬n ó¥ ËÊõÃc                                             "abaacab"
¬            // Split the input into an array of chars  ["a","b","a","a","c","a","b"]
 n           // Sort                                    ["a","a","a","a","b","b","c"]
   ó¥        // Partition matching items                [["a","a","a","a"],["b","b"],["c"]]
      Ë      // map; For each array:
       Ê     //   Get the length x                      [4,2,1]
        õ    //   Create a range [1...x]                [[1,2,3,4],[1,2],[1]]
         Ã   // }
          c  // Flatten                                 [1,2,3,4,1,2,1]
-x           // Sum                                     14
```
[Try it online!](https://tio.run/##AT0Awv9qYXB0///CrG4gw7PCpSDDi8OKw7XDg2P//yJQcm9ncmFtbWluZyBQdXp6bGVzICYgQ29kZSBHb2xmIi14 "Japt – Try It Online")
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/attache), score 36
```
Sum@Map&:(Count#Last)@Prefixes
```
[Try it online!](https://tio.run/##SywpSUzOSP3vkpqWmZcarZKm8z@4NNfBN7FAzUrDOb80r0TZJ7G4RNMhoAiooiK1@H8sV0BRZl5JdFq0En6VSrGx/wE "Attache – Try It Online")
## Explanation
```
Sum@Map&:(Count#Last)@Prefixes
```
This is a composition of 3 functions:
* `Prefixes` - this simply obtains the prefixes of the input
* `Map&:(Count#Last)` - This is a mapped fork. This is equivalent to `arr.map { e -> e.count(e.last) }` So, for each character, this counts the occurrences of that character so far.
* `Sum` - this sums all of these numbers.
[Answer]
# MS-SQL, score 308
I'm using a completely different technique from [my other answer](https://codegolf.stackexchange.com/a/127312/70172), with additional restrictions, so I'm submitting them separately:
```
SelEcT SUm(k)FROM(SELECT k=couNt(*)*(CoUNT(*)+1)/2froM spt_values,z WHERE type='P'AND number<len(q)GROUP BY sUBstring(q,number+1,1))L
```
Caveats: this must be run from the `master` database of a MS-SQL server set to a case-sensitive collation (mine is set to SQL\_Latin1\_General\_CP850\_BIN2).
Input is via varchar field *q* in pre-existing table *z*, [per our IO rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341). Formatted:
```
SelEcT SUm(k)
FROM
    (SELECT k=couNt(*)*(CoUNT(*)+1)/2
     froM spt_values,z
     WHERE type='P'
     AND number<len(q)
     GROUP BY sUBstring(q,number+1,1)
    )L
```
The trick here is to use a "[number table](https://codegolf.stackexchange.com/questions/129211/sql-select-number-ranges)" to join with the input table, which allows me to separate each character into its own row, then group by matching characters, count them up, calculate the score of each, and sum them all together. All the rest is minimizing score by playing with character case, since SQL keywords are not case sensitive.
MS-SQL has a system table in the `master` database called `spt_values` with a lot of junk in it, but I restrict it to `type='P'`, I get a nice number table with 0 through 2047.
[Answer]
# [K4](http://kx.com/download/), score 15
**Solution:**
```
+/,/{1+!#x}'=
```
**Example:**
```
q)k)+/,/{1+!#x}'="Programming Puzzles & Code Golf"
47
```
**Explanation:**
```
+/,/{1+!#x}'= / the solution
            = / group
    {     }'  / apply lambda to each (')
         x    / implicit lambda input
        #     / count length
       !      / range 0..n
     1+       / add one
  ,/          / flatten list
+/            / sum up
```
**Notes:**
In **Q** this could be written as:
```
q)sum raze { 1 + til count x } each group "Programming Puzzles & Code Golf"
47
```
[Answer]
# [Python 3](https://docs.python.org/3/), score ~~89~~ 85
```
lambda	y:sum(y[:x+1].count(v)for	x,v in enumerate(y))
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklkbPSqrg0V6My2qpC2zBWLzm/NK9Eo0wzLb@Is0KnTCEzTyE1rzQ3tSixJFWjUlPzf0FRJlBBmoYSWdqVgCYAAA "Python 3 – Try It Online")
[Answer]
# [Standard ML](http://www.mlton.org/), 66 bytes, score 113
```
fun$(a::z)=1+length(List.filter(fn y=>y=a)z)+	$z|
$_=0;$o explode;
```
This code defines an anonymous function which is bound to the implicit result identifier `it`. [Try it online!](https://tio.run/##lZBBSwMxEIXP7q8YwiJJi6WVgtIQQXoQwUPB66LMtsm6kE3KZgpt8L@vaVNY8ebc5nvvzcALnb3rLHk3DObgSo6rVRRqMbXaNfTF39pAM9Na0j03Dk7q6aRQRDG9KeN3UX6quSw96OPe@p2W5xNAOhAEULDvW0f81dGM/DulpeFtUgR8AKscE7IoLl6GNeIWayaBT2CxhIm4CpveNz12XYrC5hCj1QFuYZ1ewYu3JgeWD2Mgk/kIIE/m94@jgPV2p02ThV8X8PnqHdG/eqkoFVO5v80wOfwA "Standard ML (MLton) – Try It Online")
### Explanation
The ungolfed code looks like this:
```
fun f (a::z) = 1 + length (List.filter (fn y => y=a) z) + f z
  | f  _     = 0
val g = f o explode
```
The function `g` takes a string as input, converts it to a list of characters with `explode`, and passes it on to the function `f` which recurses over the list, with `a` being the current character and `z` being the remaining list. For each `a` the number of occurrences of `a` in `z` is computed by filtering `z` to contain only chars equivalent to `a` and taking the length of the resulting list. The result is incremented by one to account for the current occurrence of `a` and added to result of the recursive call of `f` on `z`.
[Answer]
# PHP, 44 bytes, score 78:
```
While($C=ORD($argn[$p++]))$s-=++$$C;EcHo-$s;
```
Almost [Jörg´s solution](https://codegolf.stackexchange.com/a/127353/55735), but one byte shorter.
---
## PHP, 51 bytes, score 80
```
ForEach(COUNT_CHARS($argn)As$p)$z-=~$p*$p/2;echo$z;
```
---
[Answer]
# [Perl6/Rakudo](https://perl6.org/), 45 bytes, score 66
Run with `perl -ne`:
```
say [+] bag(.comb).values.map({($_+1)*$_/2});
```
Uses the essential nature of a Bag (like a set with a count per member).
Step by step:
```
.say;                      # abaacab
say .comb;                 # (a b a a c a b)
say bag(.comb);            # Bag(a(4), b(2), c)
say bag(.comb).values;     # (2 4 1)
say bag(.comb).values.map({($_+1)*$_/2});        # (3 10 1)
say [+] bag(.comb).values.map({($_+1)*$_/2});  #14
```
Also note that each character's score can be calculated from its occurrences as `(n+1)*n/2`.
Edited because I cannot evidently read.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), score 33
```
0vAB;n*<
p>i:0(?^:ag1+:}r-@a
```
[Try it online!](https://tio.run/##S8sszvj/36DM0ck6T8uGq8Au08pAwz7OKjHdUNuqtkjXIRG/LAA "><> – Try It Online")
28 bytes, with 2 occurrences each of `a` and `0`, and 3 occurrences of `:`. `AB` can be replaced by any two characters which don't appear anywhere else in the code.
Works by storing the current character count in the code grid on row 10. The sum is actually a negative sum to start with, and the -1 from reaching the end of STDIN is multiplied with this to turn it back into a positive number.
]