title: Binary Substrings

text:
# Question
Title: Binary Substrings
Inspired by the fourth problem from BMO2 2009.

Given a positive integer *n* as input or a parameter, return the number of positive integers whose binary representations occur as blocks in the binary expansion of *n*.

For example, 13 -\> 6 because 13 in binary is 1101 and it has substrings `1101, 110, 101, 11, 10, 1`. We do not count binary numbers that start with zero and we do not count zero itself.

### Test Cases

```
13 -> 6
2008 -> 39
63 -> 6
65 -> 7
850 -> 24
459 -> 23
716 -> 22
425 -> 20
327 -> 16

```

You may take in *n* as any of the following:

* an integer
* a list of truthy/falsy values for the binary representation
* a string for the binary representation
* a base 10 string (though I'm not sure why anyone would do this)

Make your code as short as possible.

# Answer
> 7 votes
# Python 3, ~~54~~ 50 bytes

```
lambda n:sum(bin(i)[2:]in bin(n)for i in range(n))

```

Thanks to Rod and Jonathan Allan for saving four bytes.

# Answer
> 5 votes
# Jelly, 4 bytes

```
ẆQSḢ

```

Try it online!

Takes input as list of `0`s and `1`s.

Try it online with numbers!

Explanation:

```
ẆQSḢ Argument: B = list of bits, e.g. [1, 1, 0, 1]
Ẇ    Get B's non-empty sublists (i.e. [[1], [1], [0], [1], [1, 1], [1, 0], [0, 1], [1, 1, 0], [1, 0, 1], [1, 1, 0, 1]])
 Q   Keep first occurrences (i.e. [[1], [0], [1, 1], [1, 0], [0, 1], [1, 1, 0], [1, 0, 1], [1, 1, 0, 1]])
  S  Reduce by vectorized addition (i.e. [6, 4, 1, 1])
   Ḣ Pop first element (i.e. 6)

```

Proof it works:

This program gets an input number, **N**. The first thing this product does is, of course, take the substrings of **N2** (**N** in base **2**). This includes duplicate substrings starting with either **0** or **1**.

After that, we simply take the unique substrings by keeping only the first occurrence of each value in the substring list.

Then, this program sums the first elements of the lists together, then the second elements, then the third, fourth, etc. and if one of the lists has no such element `0` is assumed. What the challenge asks is effectively *How many unique substrings starting with **1** does this number have in its binary form?*. Since every first element which is to be counted is `1`, we can simply sum instead of filtering for appropriate substrings.

Now, the first element of the resulting list of the summation described above holds the count of the first bits of the substrings, so we simply pop and finally return it.

# Answer
> 4 votes
# Octave, ~~62~~ 61 bytes

```
@(n)sum(arrayfun(@(t)any(strfind((g=@dec2bin)(n),g(t))),1:n))

```

**Try it online!**

### Explanation

For input `n`, the code tests all numbers from `1` to `n` to see if their binary representation is a substring of the binary representation of the input.

```
@(n)                                                          % Anonymous function of n
        arrayfun(                                      ,1:n)  % Map over range 1:n
                 @(t)                                         % Anonymous function of t
                         strfind(               ,    )        % Indices of ...
                                                 g(t)         % t as binary string ...
                                 (g=@dec2bin)(n)              % within n as binary string
                     any(                             )       % True if contains nonzero
    sum(                                                    ) % Sum of array

```

# Answer
> 3 votes
# 05AB1E, 5 bytes

Takes input as a binary string.
The header converts integer input to binary for ease of testing.

```
ŒCÙĀO

```

Try it online!

**Explanation**

```
Œ        # push all substrings of input
 C       # convert to base-10 int
  Ù      # remove duplicates
   Ā     # truthify (convert non-zero elements to 1)
    O    # sum

```

# Answer
> 3 votes
# Perl 5, 36 + 1 (`-p`) = 37 bytes

```
/.*(.+?)(?{$k{0|$1}++})(?!)/;$_=%k-1

```

Try it online!

Takes input as a binary string.

# Answer
> 2 votes
# PowerShell, ~~103~~ ~~92~~ 82 bytes

```
param($s)(($s|%{$i..$s.count|%{-join$s[$i..$_]};$i++}|sort -u)-notmatch'^0').count

```

Try it online!

Takes input as an array of `1` and `0` (truthy and falsey in PowerShell). Loops through `$s` (i.e., how many elements in the input array). Inside the loop, we loop from the current number (saved as `$i`) up to `$s.count`. Each inner loop, we `-join` the array slice into a string. We then `sort` with the `-u`nique flag (which is shorter than `select` with the `-u`nique flag and we don't care whether they're sorted or not), take those that don't start with `0`, and take the overall `.count`. That's left on the pipeline and output is implicit.

# Answer
> 2 votes
## JavaScript (ES6), 55 bytes

```
f=(s,q="0b"+s)=>q&&s.includes((q--).toString(2))+f(s,q)

```

Takes input as a binary string.

Here's a sad attempt at doing it with numbers and recursive functions:

```
f=(n,q=n)=>q&&(g=n=>n?n^q&(h=n=>n&&n|h(n>>1))(q)?g(n>>1):1:0)(n)+f(s,q-1)

```

### Old approach, 74 bytes

```
s=>(f=s=>+s?new Set([+s,...f(s.slice(1)),...f(s.slice(0,-1))]):[])(s).size

```

Also takes input as a binary string.

# Answer
> 2 votes
# Haskell (~~126~~121 bytes)

```
import Data.List
r o c(t:s)=r([t]:[t:x|x<-o])(o++c)s
r o c[]=o++c
f=length.nub.filter(>"").map(dropWhileEnd(<'1')).r[][]

```

(5 bytes improvement thanks to @WheatWizard's comment)

Defines a function "f" that accepts a binary string as input.

Ungolfed and commented:

```
import Data.List -- unfortunately we need some functions that aren't in Prelude

-- recursively generate all sublists of a given list (or string)
-- arguments are the list of sublists currently being worked with,
--   a list of finished sublists, and list to examine
-- output is a list of reversed lists
rsubstrs :: [[t]]->[[t]]->[t]->[[t]]

rsubstrs open closed (t:ts) = rsubstrs ([t]:[t:o|o<-open]) (open++closed) ts
rsubstrs open closed [] = open++closed

-- count unique nonzero binary substrings, produced by composing a sequence of functions:
--   rsubstrs above (with two empty lists supplied to the first two curried arguments)
--   a map operation that removes any trailing sequences of zeros
--   filter to remove empty strings (which were zeros)
--   nub, which finds all unique items in a list
--   length, to count the results
countsubs = length . nub . filter (/="") . map (dropWhileEnd (=='0')) . rsubstrs [] []

```

# Answer
> 1 votes
# Jelly, 5 bytes

```
ẆḄQṠS

```

Try it online!

Takes input as a list of 1s and 0s. The footer in the link applies the function to each of the examples in the post.

Jonathan Allan pointed out that `ẆḄQTL` is 5 byte alternative which uses the `T` atom which finds the indices of all truthy elements.

**Explanation**

Take bin(13)=1101 as an example. Input is `[1,1,0,1]`

```
ẆḄQṠS
Ẇ       All contiguous sublists -> 1,1,0,1,11,10,01,110,101,1101 (each is represented as a list)
 Ḅ      From binary to decimal. Vectorizes to each element of the above list -> 1,1,0,1,3,2,1,6,5,13
  Q     Unique elements
   Ṡ    Sign. Positive nums -> 1 , 0 -> 0.
    S   Sum

```

Took the "truthify" (sign in this case) idea from the 05AB1E answer

# Answer
> 1 votes
# , ~~88~~ 77 bytes

```
function(x)sum(!!unique(strtoi(mapply(substring,x,n<-1:nchar(x),list(n)),2)))

```

Try it online!

Takes input as a binary string.

using `mapply`, generates an array of all substrings of the input. `strtoi` converts them as base `2` integers, and I take the sum of the logical conversion (`!!`) of entries in the result.

# Answer
> 1 votes
# Python 2,  ~~118~~  81 bytes

*Thanks to @Rod for saving 37 bytes!*

```
lambda n:len({int(n[i:j+1],2)for i in range(len(n))for j in range(i,len(n))}-{0})

```

Takes input as a binary string.

Try it online!

# Python 2, 81 bytes

*Thanks to @Rod!*

```
lambda n:len({n[i:j+1]for i in range(len(n))for j in range(i,len(n))if'1'==n[i]})

```

Takes input as a binary string.

Try it online!

# Answer
> 1 votes
# Pyth, 8 bytes

```
l #{vM.:

```

**Try it here!**

Takes input as a binary string.

`.:` generates all the substrings, `vM` evaluates each (that is, it converts each from binary), `{` deduplicates, `<space>#` filters by identity and `l` gets the length.

# Answer
> 1 votes
# Ruby ~~41 36~~ 27 bytes

Takes binary string as input

Is ultra-inefficient

```
->n{(?1..n).count{|j|n[j]}}

```

Partly inspired by this python 3 answer

Try it online!

# Answer
> 1 votes
# Retina, ~~37~~ 29 bytes

```
.+
*
+`(_+)\1
$1#
#_
_
wp`_.*

```

Try it online! I just had to try out Retina 1.0's `w` modifier. Edit: Saved 8 bytes thanks to @MartinEnder. Explanation:

```
.+
*

```

Convert from decimal to unary.

```
+`(_+)\1
$1#
#_
_

```

Convert from unary to binary, using `#` for `0` and `_` for 1.

```
wp`_.*

```

Generate substrings that begin with `1`, I mean, `_`. The `w` modifier then matches all substrings, not just the longest one at each starting `_`, while the `p` modifier deduplicates the matches. Finally as this is the last stage the count of matches is implicitly returned.

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

Counting unique subsequences of the binary representation that start with one, although I'm not sure this code even needs an explanation.

```
Union@Subsequences@#~Count~{1,___}&

```

Try it online!

# Answer
> 1 votes
# Husk, 7 bytes

```
←LumḋQḋ

```

Try it online!

## Explanation

```
←LumḋQḋ
      ḋ binary digits of the input
     Q  all possible sublists
   mḋ   convert each back to base-10
  u     uniquify
 L      get the length
←       decrement (since one of the sublists will be 0)

```

# Answer
> 0 votes
# Perl 6, 47 bytes

```
->\n{+grep {n.base(2).contains(.base: 2)},1..n}

```

Try it online!

# Answer
> 0 votes
# Julia 0.6, 37 bytes

```
~n=sum(contains.([bin(n)],bin.(1:n)))

```

Try it online!

Juliafication of the Python answer by J843136028 using `.` for element-wise function application with broadcasting. (link)

# Answer
> 0 votes
# Java, 232 bytes

```
String b=toBin(n);
l.add(b);
for(int i=1;i<b.length();i++){
for(int j=0;j<=b.length()-i;j++){
String t="";
if((""+b.charAt(j)).equals("0"))continue;
for(int k=0;k<i;k++){
t+=""+b.charAt(j+k);
}
if(!l.contains(t))l.add(t);
}
}
return l.size();

```

Where n is the input, b is the binary representation and l is a list of all the substrings. First time posting here, definitely need to improve, and feel free to point out any mistakes! Slightly edited for readability.

# Answer
> 0 votes
# Attache, 35 bytes

```
`-&1@`#@Unique@(UnBin=>Subsets@Bin)

```

Try it online!

Equivalently:

```
{#Unique[UnBin=>Subsets[Bin[_]]]-1}

```

## Explanation

I will explain the second version, as it is easier to follow (being explicit):

```
{#Unique[UnBin=>Subsets[Bin[_]]]-1}
{                                 }   lambda: _ = first argument
                        Bin[_]        convert to binary
                Subsets[      ]       all subsets of input
         UnBin=>                      map UnBin over these subsets
  Unique[                      ]      remove all duplicates
 #                              -1    size - 1 (since subsets is improper)

```

# Answer
> 0 votes
# C++, 110 bytes

```
#include<set>
std::set<int>s;int f(int n){for(int i=1;i<n;i+=i+1)f(n&i);return n?s.insert(n),f(n/2):s.size();}

```

This is a recursive function. We use a `std::set` to count values, ignoring duplicates. The two recursive calls mask bits off the left (`f(n&i)`) and off the right (`f(n/2)`), eventually producing all the substrings as integers.

Note that if you want to call it again, `s` must be cleared between calls.

## Test program

```
#include <cstdlib>
#include <iostream>

int main(int, char **argv)
{
    while (*++argv) {
        auto const n = std::atoi(*argv);
        s={};
        std::cout << n << " -> " << f(n) << std::endl;
    }
}

```

## Results

```
./153846 13 2008 63 65 850 459 716 425 327
13 -> 6
2008 -> 39
63 -> 6
65 -> 7
850 -> 24
459 -> 23
716 -> 22
425 -> 20
327 -> 16

```

# Answer
> 0 votes
# Java 8, ~~160~~ ~~159~~ 158 bytes

```
import java.util.*;b->{Set s=new HashSet();for(int l=b.length(),i=0,j;i<l;i++)for(j=l-i;j>0;s.add(new Long(b.substring(i,i+j--))))s.add(0L);return~-s.size();}

```

Input as binary-String.
There must be a shorter way.. \>.\>

**Explanation:**

Try it online.

```
import java.util.*;          // Required import for Set and HashSet
b->{                         // Method with String as parameter and integer as return-type
  Set s=new HashSet();       //  Create a Set
  for(int l=b.length(),      //  Set `l` to the length of the binary-String
      i=0,j;i<l;i++)         //  Loop from 0 up to `l` (exclusive)
    for(j=l-i;j>0;           //   Inner loop from `l-i` down to `0` (exclusive)
      s.add(new Long(b.substring(i,i+j--))))
                             //    Add every substring converted to number to the Set
      s.add(0L);             //    Add 0 to the Set
  return~-s.size();}         //  Return the amount of items in the Set minus 1 (for the 0)

```

# Answer
> 0 votes
# , 34 bytes

```
f=.3 :'<:#~.,(#:i.2^##:y)#.;.1#:y'

```

Try it online!

# Answer
> 0 votes
# , 15 bytes

```
#.\\.#@=@-.&,0:

```

Input is a binary list. Try it online!

```
#.\\.               Convert every substring to decimal
         -.&,0:     Flatten and remove the 0s.
     #@=            How many unique elements?

```

# Answer
> 0 votes
# Perl 6, 34 bytes

```
{+unique ~«(.base(2)~~m:ex/1.*/)}

```

Test it

## Expanded:

```
{
  +                                # turn into Numeric (number of elements)
   unique                          # use only the unique ones
          ~«(                      # turn into strings
             .base(2)              # the input in base 2
                     ~~
                       m:ex/1.*/   # :exhaustive match substrings
                                )
}

```

---
Tags: code-golf, binary
---


title: Golf a Brain-Flak Integer

text:
# Question
Title: Golf a Brain-Flak Integer
Integers are tedious to represent in Brain-Flak. There are 8 operators:

```
()      Evaluates to 1, but does not push anything on any stack
[]      Evaluates to an indeterminate value for the purposes of this question
{}      Removes the top of the stack and evaluates to it
<>      Switches to or back from the alternate stack and evaluates to zero
(foo)   Pushes the value of the expression foo to the stack and evaluates to it
[foo]   Evaluates to the negation of foo
{foo}   Evaluates the expression foo until the top of the stack is zero
<foo>   Evaluates to zero but executes foo anyway

```

`foo` may consist of multiple operators, in which case they are evaluated and summed. For example `(()())` pushes `2` to the stack (and evaluates to `2` too).

Obviously, the `(()...())` mechanism is not useful in Code Golf as large numbers would take `n*2+2` bytes to represent. Your challenge is therefore to write a program or function that will output in as few bytes as possible a Brain-Flak program that will push a given positive integer `n` to the active stack. This program must not make any assumptions about the existing contents of the stacks, so it must not leave the stacks exchanged or add or remove extra values from the stacks.

Although your program or function must be capable of returning a working Brain-Flak program for all inputs from 1 to 1,000,000 the winner will be the program or function that generates the smallest set of appropriate Brain-Flak programs for all 1061 prime numbers between 1,000 and 10,000. You should note the total size of your outputs for those 1061 inputs as part of your submission. Your program or function may accept the integer and return the (string) Brain-Flak program in any of the usual acceptable I/O formats. Ties will be broken using the size of your program or function.

# Answer
> 17 votes
# Python 2, ~~59394~~ ~~59244~~ ~~58534~~ ~~58416~~ ~~58394~~ 58250

Ok here is my solution.

```
import re
import math

cache = {0:"<()>"}

def find(x,i,j):
    return i*((x**2+x)/2)+(j+1)*((x**2-x)/2)

def solve(x, i, j):
    a = (i + j + 1)/2.
    b = (i - j - 1)/2.
    c = -x
    return (-b + math.sqrt(b**2 - 4*a*c))/(2*a)

def size(i,j=0):
    return 4*(i+j)+14

def polynomials(n):
    upperBound = int(4*math.log(n,2))
    i = 0
    answers = []
    while size(i) < upperBound:
        for j in range(i):
            sol = int(solve(n, i-j, j)+.5)
            if find(sol, i-j, j) == n:
                answers.append((sol, i-j, j))
        i += 1
    return answers

def complement(character):
        dict = {"(":")","{":"}","<":">","[":"]",")":"(","}":"{",">":"<","]":"["}
        return dict[character]

def findMatch(snippet, index):
        increment = 1 if snippet[index] in "({<[" else -1
        stack = []
        if snippet[index] in "(){}<>[]":
                stack.append(snippet[index])
        while len(stack) > 0 and index + increment < len(snippet):
                index += increment
                if snippet[index] in "(){}<>[]":
                        if complement(snippet[index]) == stack[-1]:
                                stack = stack[:-1]
                        else:
                                stack.append(snippet[index])
        return index

def isPrime(n):
    return not [0 for x in range(2,int(n**.5)+1) if n%x==0] and n>1

def getPrimeFactors(n):
    return [x for x in range(2,n/2) if n%x==0 and isPrime(x)]

def divHardcode(n,m):
    assert n%m == 0
    assert m != 1
    assert n != 1
    binary = bin(m)[3:]
    return (binary.count("1")+len(binary))*"("+getBF(n/m)+")"*binary.count("1")+binary.replace("1","){}{}").replace("0","){}")

def isTriangular(n):
    #Triangles must be between sqrt(2n) and cbrt(2n)
    if n < 0: return isTriangular(-n)
    for x in range(int((2*n)**(1/3.)),int((2*n)**.5)+1):
        if (x**2+x) == 2*n:
            return True
    return False

def getTriangle(n):
    if n < 0: return -getTriangle(-n)
    #Triangles must be between sqrt(2n) and cbrt(2n)
    for x in range(int((2*n)**(1/3.)),int((2*n)**.5)+1):
        if (x**2+x) == 2*n:
            return x
    #If we don't find one we made a mistake
    assert False

def getSimpleBF(n):
    if n in cache:return cache[n]
    if n < 0:
        # There is room for better solutions here
        return "["+getSimpleBF(-n)+"]"
    elif n == 0:
        return ""
    elif n < 6:
        return "()"*n
    #Non-edge cases
    solutions = []
    factors = getPrimeFactors(n)
    if n >= 78 and isTriangular(n):
        solutions.append(
           min([push(getTriangle(n))+"{({}[()])}{}","<"+push(getTriangle(n)+1)+">{({}[()])}{}"],key=len)
        )
    polynomialSolutions = polynomials(n)
    for polynomial in polynomialSolutions:
        solutions.append("<%s>{%s({}[()])%s}{}"%(push(polynomial[0]),"({})"*polynomial[1],"({})"*polynomial[2]))
        #Mod 3 tricks
    if n % 3 == 2:
       solutions.append(("((%s)()){}{}")%getBF(n/3))
    elif n % 3 == 1:
       solutions.append(("((%s)()()){}{}")%getBF(n/3-1))
    #Basic solutions
    if isPrime(n):
        solutions.append(getSimpleBF(n-1) + "()")
    else:
        #TODO multithread
        solutions += map(lambda m:divHardcode(n,m),factors)
    return min(solutions,key=lambda x:len(unpack(x)))

def getBF(n):
    if n in cache: return cache[n]
    result = getSimpleBF(n)
    index = n - 1
    while index > n-(len(result)/2):
        score = getSimpleBF(index)+getSimpleBF(n-index)
        if len(score) < len(result):result = score
        index -= 1
    index = n + 1
    while index < n+(len(result)/2):
        score = getSimpleBF(index)+getSimpleBF(n-index)
        if len(score) < len(result):result = score
        index += 1
    cache[n] = result
    return result

def unpack(string):
    reMatch = re.match("\(*<",string)
    if reMatch:
        location =reMatch.span()
        return string[location[1]:findMatch(string,location[1]-1)] +string[:location[1]-1] + string[findMatch(string,location[1]-1)+1:]
    return string

def push(n):
    return unpack("("+getBF(n)+")")

def kolmo(string):
    code = push(ord(string[-1]))
    stringVector = map(ord,string)
    for x,y in zip(stringVector[-1:0:-1],stringVector[-2::-1]):
        code = "("+code+getBF(y-x)+")"
    code = code.replace("<()>)",")")
    return code

def kolmo(stringVector):
    code = push(stringVector[-1])
    for x,y in zip(stringVector[-1:0:-1],stringVector[-2::-1]):
        code = "("+code+getBF(y-x)+")"
    code = code.replace("<()>)",")")
    return code

if __name__ == "__main__":
    import primes
    sum = 0
    for prime in primes.nums:
        print push(prime)
        sum += len(push(prime))
    print sum

```

The relevant function is `push(n)`. To call it simply call push on the integer you wish to represent.

# Explanation

The main optimization done by the program is multiplication hard-coding. The idea of multiplication hardcoding is pretty simple. You push the a number and then pop and push it to create a new value. For example to multiply by two you can use the following code `((n){})` where n code producing a specific number. This works because both `(n)` and `{}` have a value of n.

This simple idea can be made more complex for larger numbers. Take for instance 5 it was discovered a while ago that the best way to multiply by five was `(((n)){}){}{}`. This code makes two copies of the n multiplies one by 4 and adds the two. Using the same strategy I make every multiplication based on a number's binary representation. I won't get into the details of how this works right now but I do this by chopping off the first one of the binary representation and replacing 0 with `){}` and 1 with `){}{}`. It then makes sure that n is pushed the appropriate number of times and balances all the parentheses. (If you want to know how this is done you can look at my code). If you want to know why this works just ask me in a comment. I don't think anyone actually reads all the updates to my post so I left the explanation out.

When the algorithm attempts to find a multiplication hardcode it attempts all of a numbers prime factors. It ignores composite factors because at one point composite factors could always be expressed more concisely as its own prime factors it is not known if this is still true.

The other byte saving mechanism is a polynomial solution finder. There are certain forms of polynomials that are easy to represent with decrementing loops. These polynomials include, but are not limited to, polygonal numbers. This optimization finds polynomials that fit the form and creates the code that makes them.

## Output

paste-bin

# Answer
> 16 votes
# Brain-Flak, 64664

Try it Online!

Here is my annotated code

```
({}<
 ((((()()()()()){}){}){}()) #41
>)
{
 (({})[()()()()()()])
 ([({}<(())>)](<>)){({}())<>}{}<>{}{}<>(({})){(<{}({}<>)>)}{}({}<>)
 {((< #IF
  {}
  {({}[()]< #FOR
   ((((()()()()()){}){}){}()) #41
   (({})[()])                 #40
  >)}{}
 >))}{}
 (({}))
 #MOD2
 {(<
  ({}<(())>)({<({}[()]<>)><>(()[{}])<><({}<>)>}{}<({}<>)><>)<>({}<>)
  {((<{}({}< #IF
   {}
   (((()()()()())({})({})({}){})({})({})({}){})  #125
   (({})[()()])                                  #123
   ((((()()()()()){}){}){}())                    #41
   <>
   ((((()()()()()){}){}){})                      #40
   <>
   >)

  >))}{}{}
 >)}{}
 #MOD2 (number 2)
 (({}))
 ({}(())){({}[()]<>)<>(()[{}])<>({}<>)}{}
 (({})<([{}]{})>)
 {
  ({}[()]<<>
    ((((()()()()()){}){}){}) #40
    (({})())                 #41
   <>>)
 }{}
}{}
<>{({}<>)<>}<>((((()()()()()){}){}){})

```

## Explanation

This only implements two rules as of now:

* If n is divisible by two return `(n/2){}`
* If n is not divisible by two return `n-1()`

It also hardcodes all the numbers smaller than 6.

# Answer
> 11 votes
## Perl, ~~59222~~ ~~59156~~ 58460 characters

* `n()` (11322660 characters)
* `(n){}()` (64664 characters)
* `((n)){}{}` (63610 characters)
* `((n)()){}{}` (63484 characters) - this is a novel calculation
* `(n){({}[()])}{}` (60748 characters)
* `n[m]` (62800 characters)
* `(n){m({}[l])}{}` (58460 characters) - this is a novel calculation

The formula for that last calculation is `n(n/l+1)/2+mn/l`. I've tried some other calculations but they are no longer helpful for the given output. The program actually generates all the values up to 9999 but then lists the given prime numbers and their total length.

```
@primes = (<list of the 4-digit prime numbers here>);
@numbers = ();
for ($i = 1; $i < 10000; $i++) {
  $numbers[$i] = "()" x $i; # default calculation
}
for ($i = 2; $i < 10000; $i++) {
  for ($j = 1; $j < 8; $j++) {
    &try($i, "$numbers[$i+$j]\[$numbers[$j]]");
  }
  &try($i + 1, "$numbers[$i]()");
  &try($i * 2, "($numbers[$i]){}");
  &try($i * 3, "(($numbers[$i])){}{}");
  &try($i * 3 + 2, "(($numbers[$i])()){}{}");
  for ($l = 1; $l * $l < $i; $l++) {
    unless ($i % $l) {
      for ($j = 0; ($k = (($i + $j + $j) * $i / $l + $i) / 2) < 10000; $j++) {
        &try($k, "($numbers[$i]){$numbers[$j]({}[$numbers[$l]])}{}");
      }
    }
  }
}
$len = 0;
foreach (@primes) {
  print "($numbers[$_])\n";
  $len += 2 + length $numbers[$_];
}
print "$len\n";
sub try {
  ($n, $s) = @_;
  $numbers[$n] = $s if (length($numbers[$n]) > length $s);
}

```

# Answer
> 8 votes
# Lua 5.3, 57522

I actually started working on this back when the question was posted, but forgot about it until the Brain-Flak anniversary.

```
-- 64 gives all results through 10000 (should run in about 1 second)
-- 78 gives all results through 100000 (should run in about 20 seconds)
-- 90 gives all results through 1000000 (should run in about 200 seconds)
-- Note: Timings may not be accurate, as the are not updated every time new cases are added.

local k_max_len = 64
local k_limit = 10000

local pre = os.clock()

local function compute_multiplier_helper(prefix, suffix, m)
  if m == 2 then
    prefix[#prefix + 1] = "("
    suffix[#suffix + 1] = "){}"
  elseif m % 2 == 0 then
    prefix[#prefix + 1] = "("
    compute_multiplier_helper(prefix, suffix, m // 2)
    suffix[#suffix + 1] = "){}"
  else
    suffix[#suffix + 1] = ")"
    compute_multiplier_helper(prefix, suffix, m - 1)
    prefix[#prefix + 1] = "("
    suffix[#suffix + 1] = "{}"
  end
end

local function compute_multiplier(m)
  local prefix = {}
  local suffix = {}
  compute_multiplier_helper(prefix, suffix, m)
  return table.concat(prefix), table.concat(suffix)
end

local multipliers = {}
for m = 2, k_limit do
  -- Including all factors, not just primes.
  -- This did improve a few numbers, although none in the ppcg test set.
  local prefix, suffix = compute_multiplier(m)
  local mult = {prefix = prefix, suffix = suffix, m = m, cost = #prefix + #suffix}
  table.insert(multipliers, mult)
end
table.sort(multipliers, function(a, b) return a.cost < b.cost end)

local poly_multipliers = {}
poly_multipliers[1] = {m = 1, s = "({})", l = 4}
for m = 2, k_limit do
  local prefix, suffix = compute_multiplier(m)
  local s = prefix .. "({})" .. suffix
  assert(#s <= 4 * m)
  poly_multipliers[m] = {m = m, s = s, l = #s}
end
poly_multipliers[k_limit + 1] = {m = 0, s = "", l = 0}

table.sort(poly_multipliers, function(a, b) return a.l < b.l end)

local pcache = {}
local plen_cache = {}

local function register_push(prefix, suffix, value, pvalue)
  if value > 1500000 or value < -1500000 then return end
  local old_res = pcache[value]
  if old_res == nil then
    local res = {prefix = prefix, suffix = suffix, value = value, pvalue = pvalue}
    pcache[value] = res
    local length = #prefix + #suffix
    local lcache = plen_cache[length]
    if lcache == nil then
      lcache = {}
      plen_cache[length] = lcache
    end
    lcache[#lcache + 1] = res
  end
end

local function get_pushes(length)
  return ipairs(plen_cache[length] or {})
end

register_push("", "()", 1, 0)
register_push("", "<()>", 0, 0)

local function triangle(n)
  return (n * (n + 1)) // 2
end

local function process(length)
  -- basic
  for _, res in get_pushes(length - 2) do
    register_push(res.prefix, res.suffix .. "()", res.value + 1, res.pvalue)
    register_push(res.prefix, "[" .. res.suffix .. "]", -res.value, res.pvalue)
  end

  -- multiplication by constant (precomputed)
  for _, mult in ipairs(multipliers) do
    local cost = mult.cost
    if length - cost >= 4 then
      local m, prefix, suffix = mult.m, mult.prefix, mult.suffix
      for _, pus in get_pushes(length - cost) do
        local name = prefix .. pus.suffix .. suffix
        register_push(pus.prefix, name, pus.value * m, pus.pvalue)
      end
    else
      break
    end
  end

  -- residue 2 mod3 trick (Neil)
  -- ((n)()){}{}
  --  (n)        -- push n
  -- (   ())     -- push n + 1
  --        {}{} -- (n + 1) + (n + 1) + n
  if length - 10 >= 2 then
    for _, res in get_pushes(length - 10) do
      local name = "((" .. res.suffix .. ")()){}{}"
      register_push(res.prefix, name, 3 * res.value + 2, res.pvalue)
    end
  end

  -- residue 1 mod3 trick (Wheat Wizard)
  -- ((n)()()){}{}
  --  (n)          -- push n
  -- (   ()())     -- push n + 2
  --          {}{} -- (n + 2) + (n + 2) + n
  -- not useful, but fast...
  if length - 12 >= 2 then
    for _, res in get_pushes(length - 12) do
      local name = "((" .. res.suffix .. ")()()){}{}"
      register_push(res.prefix, name, 3 * res.value + 4, res.pvalue)
    end
  end

  -- residue 2 mod5 trick (tehtmi)
  -- (((n)){}()){}{}
  --   (n)           -- push n
  --  (   )          -- push n
  -- (     {}())     -- push 2n + 1
  --            {}{} -- (2n + 1) + (2n + 1) + n
  -- [[
  if length - 14 >= 2 then
    for _, res in get_pushes(length - 14) do
      local name = "(((" .. res.suffix .. ")){}()){}{}"
      register_push(res.prefix, name, 5 * res.value + 2, res.pvalue)
    end
  end
  -- ]]

  -- residue 4 mod5 trick (tehtmi)
  -- (((n)()){}){}{}
  --   (n)           -- push n
  --  (   ())        -- push n + 1
  -- (       {})     -- push 2n + 2
  --            {}{} -- (2n + 2) + (2n + 2) + n
  -- [[
  if length - 14 >= 2 then
    for _, res in get_pushes(length - 14) do
      local name = "(((" .. res.suffix .. ")()){}){}{}"
      register_push(res.prefix, name, 5 * res.value + 4, res.pvalue)
    end
  end
  -- ]]

  -- residue 6 mod7 trick (tehtmi)
  -- ((((n)())){}{}){}{}
  --    (n)              -- push n
  --   (   ())           -- push n + 1
  --  (       )          -- push n + 1
  -- (         {}{})     -- push 3n + 3
  --                {}{} -- (3n + 3) + (3n + 3) + n
  -- [[
  if length - 18 >= 2 then
    for _, res in get_pushes(length - 18) do
      local name = "((((" .. res.suffix .. ")())){}{}){}{}"
      register_push(res.prefix, name, 7 * res.value + 6, res.pvalue)
    end
  end
  --]]

  -- residue 4 mod7 trick (tehtmi)
  -- ((((n))()){}{}){}{}
  --    (n)              -- push n
  --   (   )             -- push n
  --  (     ())          -- push n + 1
  -- (         {}{})     -- push 3n + 2
  --                {}{} -- (3n + 2) + (3n + 2) + n
  -- [[
  if length - 18 >= 2 then
    for _, res in get_pushes(length - 18) do
      local name = "((((" .. res.suffix .. "))()){}{}){}{}"
      register_push(res.prefix, name, 7 * res.value + 4, res.pvalue)
    end
  end
  --]]

  -- residue 2 mod7 trick (tehtmi)
  -- ((((n))){}{}()){}{}
  --    (n)              -- push n
  --   (   )             -- push n
  --  (     )            -- push n
  -- (       {}{}())     -- push 3n + 1
  --                {}{} -- (3n + 1) + (3n + 1) + n
  -- [[
  if length - 18 >= 2 then
    for _, res in get_pushes(length - 18) do
      local name = "((((" .. res.suffix .. "))){}{}()){}{}"
      register_push(res.prefix, name, 7 * res.value + 2, res.pvalue)
    end
  end
  --]]

  -- triangle numbers (?)
  --(n){({}[()])}{}
  --(n)              -- push n
  --   {        }    -- sum and repeat
  --    (      )     -- push
  --     {}[()]      -- top - 1
  --             {}  -- pop 0
  if length - 14 >= 2 then
    for _, res in get_pushes(length - 14) do
      if res.value > 0 then
        local code = "{({}[()])}{}"
        register_push(res.prefix .. "(" .. res.suffix .. ")", code, triangle(res.value - 1), res.pvalue + res.value)
        register_push(res.prefix, "(" .. res.suffix .. ")" .. code, triangle(res.value), res.pvalue)
        register_push("", res.prefix .. "(" .. res.suffix .. ")" .. code, triangle(res.value) + res.pvalue, 0)
      end
    end
  end

  -- negative triangle numbers (tehtmi)
  --(n){({}())}{}
  --(n)            -- push n
  --   {      }    -- sum and repeat
  --    (    )     -- push
  --     {}()      -- top + 1
  --           {}  -- pop 0
  if length - 12 >= 2 then
    for _, res in get_pushes(length - 12) do
      if res.value < 0 then
        local code = "{({}())}{}"
        register_push(res.prefix .. "(" .. res.suffix .. ")", code, -triangle(-res.value - 1), res.pvalue + res.value)
        register_push(res.prefix, "(" .. res.suffix .. ")" .. code, -triangle(-res.value), res.pvalue)
        register_push("", res.prefix .. "(" .. res.suffix .. ")" .. code, -triangle(-res.value) + res.pvalue, 0)
      end
    end
  end

  -- cubic (tehtmi)
  -- (n){(({}[()])){({}[()])}{}}{}
  -- (n^3-3*n^2+8*n-6)/6
  -- (-6 + n*(8 + n*(-3 + n)))/6
  --[[ superceded by negative cubic because
       it is the same cost of -ncubic(-n)
  if length - 28 >= 2 then
    for _, res in get_pushes(length - 28) do
      if res.value > 0 then
        local code = "{(({}[()])){({}[()])}{}}{}"
        local v = res.value + 1
        v = (-6 + v*(8 + v*(-3 + v)))//6
        register_push(res.prefix .. "(" .. res.suffix .. ")", code, v - res.value, res.pvalue + res.value)
        register_push(res.prefix, "(" .. res.suffix .. ")" .. code, v, res.pvalue)
        register_push("", res.prefix .. "(" .. res.suffix .. ")" .. code, v + res.pvalue, 0)
      end
    end
  end
  --]]

  -- negative cubic (tehtmi)
  -- (n){(({}())){({}())}{}}{}
  -- (n^3-3*n^2+8*n-6)/6
  -- (-6 + n*(8 + n*(-3 + n)))/6
  -- [[
  if length - 24 >= 2 then
    for _, res in get_pushes(length - 24) do
      if res.value < 0 then
        local code = "{(({}())){({}())}{}}{}"
        local v = -res.value + 1
        v = (-6 + v*(8 + v*(-3 + v)))//6
        v = -v
        register_push(res.prefix .. "(" .. res.suffix .. ")", code, v - res.value, res.pvalue + res.value)
        register_push(res.prefix, "(" .. res.suffix .. ")" .. code, v, res.pvalue)
        register_push("", res.prefix .. "(" .. res.suffix .. ")" .. code, v + res.pvalue, 0)
      end
    end
  end
  --]]

  -- polynomial (Wheat Wizard, modified by tehtmi)
  -- <(n)>{A({}[()])B}{} where A, B are ({})({})({})... repeated a, b times
  -- <(n)>                -- push n (without adding)
  --      {          }    -- repeat until top is zero
  --       A              -- top * a
  --        ({}[()])      -- top = top - 1; += top - 1
  --                B     -- (top - 1) * b
  --                  {}  -- pop 0
  -- triangular numbers are with a = b = 0
  -- from B and base:
  -- (n - 1) * (B + 1) * (n - 2) * (B + 1) * ...
  -- (B + 1) * (1 + ... + n - 1)
  -- (B + 1) * n * (n - 1) / 2
  -- from A:
  -- n * A + (n - 1) * A + ...
  -- A * (1 + ... n)
  -- A * (n + 1) * n / 2
  -- total: (B + 1) * n * (n - 1) / 2 + A * (n + 1) * n / 2
  --        [(A + B + 1) * n^2 + (A - B - 1) * n] / 2
  -- S := 4 * (A + B)
  -- [[
  if length - 18 >= 2 then
    for S = 4, length - 14, 4 do
      for _, res in get_pushes(length - 14 - S) do
        if res.value > 0 then
          for _, A in ipairs(poly_multipliers) do
            if A.l > S then
              break
            end
            for _, B in ipairs(poly_multipliers) do
              if A.l + B.l < S then
                -- continue
              elseif A.l + B.l > S then
                break
              else
                local a = A.m
                local b = B.m

                local logic = "{" .. A.s .. "({}[()])" .. B.s .. "}{}"
                local v = res.value
                v = ((a + b + 1) * v * v + (a - b - 1) * v) // 2
                register_push(res.prefix .. "(" .. res.suffix .. ")", logic, v, res.pvalue + res.value)
                register_push(res.prefix, "(" .. res.suffix .. ")" .. logic, v + res.value, res.pvalue)
                register_push("", res.prefix .. "(" .. res.suffix .. ")" .. logic, v + res.value + res.pvalue, 0)
              end
            end
          end
        end
      end
    end
  end
  --]]

  -- negative polynomial (tehtmi)
  -- <(n)>{A({}())B}{}
  -- [[
  if length - 16 >= 2 then
    for S = 4, length - 12, 4 do
      for _, res in get_pushes(length - 12 - S) do
        if res.value < 0 then
          for _, A in ipairs(poly_multipliers) do
            if A.l > S then
              break
            end
            for _, B in ipairs(poly_multipliers) do
              if A.l + B.l < S then
                -- continue
              elseif A.l + B.l > S then
                break
              else
                local a = A.m
                local b = B.m

                local logic = "{" .. A.s .. "({}())" .. B.s .. "}{}"
                local v = -res.value
                v = ((a + b + 1) * v * v + (a - b - 1) * v) // -2

                register_push(res.prefix .. "(" .. res.suffix .. ")", logic, v, res.pvalue + res.value)
                register_push(res.prefix, "(" .. res.suffix .. ")" .. logic, v + res.value, res.pvalue)
                register_push("", res.prefix .. "(" .. res.suffix .. ")" .. logic, v + res.value + res.pvalue, 0)
              end
            end
          end
        end
      end
    end
  end
  --]]

  -- addition
  -- [[
  if length >= 4 then
    for part1 = 4, length // 2, 2 do
      for _, res1 in get_pushes(part1) do
        for _, res2 in get_pushes(length - part1) do
          register_push(res2.prefix .. res1.prefix, res1.suffix .. res2.suffix, res1.value + res2.value, res1.pvalue + res2.pvalue)
        end
      end
    end
  end
  --]]

  -- pseudo-exponentiation (tehtmi)
  -- (n)<>(m){({}[()])<>(({}){})<>}{}<>{}
  -- (n)<>(m)                             -- push n and m on opposite stacks
  --         {                    }       -- sum and repeat
  --          ({}[()])                    -- top(m) - 1
  --                  <>(({}){})<>        -- n = 2*n; += n
  --                               {}     -- pop 0
  --                                 <>   -- swap to result
  --                                   {} -- pop and add n
  -- [[
  if length - 34 >= 4 then
    local subl = length - 34
    for part1 = 2, subl - 2, 2 do
      for _, res2 in get_pushes(part1) do
        local b = res2.value
        if b > 0 and b < 55 then -- overflow could be a problem, so bound...
          for _, res1 in get_pushes(subl - part1) do
            -- 2n + 4n + 8n + ... + (2^m)*n + 2^m * n
            -- n( 2 + 4 + 8 + .. 2^m + 2^m)
            -- n( 3 * 2^m - 2 )
            local a = res1.value
            local body = "(" .. res1.suffix .. ")<>" .. res2.prefix .. "(" .. res2.suffix .. "){({}[()])<>(({}){})<>}{}<>{}"
            local v = a * (3 * (1 << b) - 2) + b * (b - 1) // 2 + a + b + res2.pvalue
            register_push(res1.prefix, body, v, res1.pvalue)
            register_push("", res1.prefix .. body, v + res1.pvalue, 0)
          end
        end
      end
    end
  end
  --]]
end

--print(os.clock(), "seconds (startup)")

local start = os.clock()
for i = 2, k_max_len - 2, 2 do
  --print(i)
  process(i)
end

plen_cache = nil

local final = {}
for i = 1, k_limit do
  if pcache[i] ~= nil then
    final[i] = pcache[i].prefix .. "(" .. pcache[i].suffix .. ")"
  end
end

pcache = nil

-- hard coded to 10000 for ppcg test
local sieve = {}
for i = 1, 10000 do sieve[i] = true end
for i = 2, 10000 do
  for j = i * i, 10000, i do
    sieve[j] = false
  end
end

--print(os.clock() - start, "seconds (calculation)")

--local bf = require("execute2")

local count = 0
local sum = 0
local sum2 = 0
local maxlen = 0
local pcount = 0
for i = 1, k_limit do
  local res = final[i]
  final[i] = nil
  --print(i, #res, res)
  --local ev = res and bf.eval1(bf.compile(res)) or -1; assert( res == nil or ev == i, string.format("Failed %d %s %d", i, res or "", ev))
  if sieve[i] and i > 1000 then
    sum = #res + sum
    pcount = pcount + 1
  end
  if res then
    sum2 = #res + sum2
    maxlen = math.max(maxlen, #res)
    count = count + 1
  end
end
print("sum", sum)
--print("coverage", count / k_limit, "missing", k_limit - count)
--print("sum2", sum2)
--print("maxlen", maxlen)
assert(pcount == 1061)

```

Similar idea to the other answers where known-useful functions are used to build up larger numbers from good representations of simpler numbers.

One difference is that instead of solving subproblems in terms of smaller numbers, I'm solving subproblems in terms of numbers with shorter representations. I think this makes it more elegant to take advantage of negative numbers as well as handling the case where smaller numbers are represented in terms of larger numbers.

Also, trying to find all numbers that can be represented in a certain size rather trying to represent a particular number as shortly as possible actually simplifies certain calculations. Instead of working a formula in reverse to see whether it can be applied to a number, the formula can be worked forwards and applied to every number.

Another difference is that known solutions are stored in two pieces -- an (optional) "prefix" and a "suffix" (more like an infix). The valuation of the prefix is expected to be ignored when calculating the given number -- the prefix just contains code that sets up the suffix to run (generally by pushing one or more things to the stack). So, given a prefix and a suffix, the corresponding number can be pushed onto the stack with `prefix(suffix)`.

This split basically solves the same problem as the `unpack` function in Wheat Wizard's answer. Instead of wrapping code with `<...>` only to undo this later, such code is simply added to the prefix.

In a few cases, the prefix actually does get evaluated (mainly for the pseudo-exponentiation operation), so its valuation is also stored. However, this doesn't really cause a big problem, as the generator isn't trying to construct specific numbers. It seem to theoretically imply that there could be two pieces of code of the same length and generating the same number that wouldn't be redundant in the cache due to having different prefix valuations. I didn't bother accounting for this though, as it doesn't seem to matter much (at least in this domain).

I imagine it would be easy to whittle down the byte count just by adding more cases, but I've had enough for the moment.

I've run to 1000000, but only done sanity checking up to 100000.

Pastebin of output on given primes.

# Answer
> 6 votes
## Python, ~~59136~~ 58676 characters

**Brainflak number golfing function:**

```
m=11111
R=range(0,m)
R[1]="()"
R[2]="()()"
l=2
def a(v,r):
 if v>0 and v<m:
  if isinstance(R[v],int) or len(r)<len(R[v]):
   R[v]=r
   if v<R[0]:
    R[0]=v
def s(v,k):
 S=0
 while v>0:
  S+=v
  v-=k
 return S
p=lambda r:"("+r+")"
w=lambda r:"{({}["+r+"])}{}"
def q(r,v):
 for i in range(1,v):
  r="("+r+")"
 for i in range(1,v):
  r+="{}"
 return r
def e(r,v,k):
 for i in range(0,k):
  r=q(r,v)
 return r
while l<m:
 R[0]=l+1
 a(l*2,q(R[l],2))
 a(l*3,q(R[l],3))
 a(l*5,q(R[l],5))
 a(l*7,q(R[l],7))
 for i in range(1,l):
  a(l+i,R[l]+R[i])
  a(l-i,R[l]+"["+R[i]+"]")
  if l%i==0:
   t=s(l-i,i)
   a(s(l,i),p(R[l])+w(R[i]))
   a(l+2*t,p(R[l])+q(w(R[i]),2))
   a(l+4*t,p(R[l])+e(w(R[i]),2,2))
   a(l+8*t,p(R[l])+e(w(R[i]),2,3))
   a(l+16*t,p(R[l])+e(w(R[i]),2,4))
   a(l+32*t,p(R[l])+e(w(R[i]),2,5))
   a(l+64*t,p(R[l])+e(w(R[i]),2,6))
   a(l+128*t,p(R[l])+e(w(R[i]),2,7))
   a(l+3*t,p(R[l])+q(w(R[i]),3))
   a(l+9*t,p(R[l])+e(w(R[i]),3,2))
   a(l+27*t,p(R[l])+e(w(R[i]),3,3))
   a(l+5*t,p(R[l])+q(w(R[i]),5))
   a(l+6*t,p(R[l])+q(q(w(R[i]),3),2))
   a(l+10*t,p(R[l])+q(q(w(R[i]),5),2))
   a(l+15*t,p(R[l])+q(q(w(R[i]),5),3))
   a(l+12*t,p(R[l])+q(q(q(w(R[i]),3),2),2))
   a(l+18*t,p(R[l])+q(q(q(w(R[i]),3),3),2))
   a(l+20*t,p(R[l])+q(q(q(w(R[i]),5),2),2))
   a(l+24*t,p(R[l])+q(q(q(q(w(R[i]),3),2),2),2))
   a(l+36*t,p(R[l])+q(q(q(q(w(R[i]),3),3),2),2))
   a(l+40*t,p(R[l])+q(q(q(q(w(R[i]),5),2),2),2))
 l=R[0]
f=lambda v:p(R[v])

```

**Prime number iteration:**

```
def isPrime(v):
 i=2
 while i*i<=v:
  if v%i==0:
   return False
  i+=1
 return True

for i in range(1000,10000):
 if isPrime(i):
  print f(i)

```

**Output:**

Pastebin

**Explanation:**

We pre-populate a list *R* of Brain-flak representation evaluating to individual integers over a larger than necessary range \[1,*m*-1\] to define our function *f*. The representations are formed by taking the lowest unused representation (indexed by *l*) and forming many new representations from it, keeping only the shortest. The lowest unused representation assumes that all number 1 to *l* have been assigned a representation, and that these representations have already been used to produce new numbers. If a value less than *l* gets a shorter representation we must go back and reproduce numbers beginning form that point. The function *f* produces a program saving the number to the stack by adding parenthesis.

I didn't know any Brainflak when I began this, and greatly appreciate Eamon Olive's answer for pointing out the formula for triangle numbers. Mostly I've generalized the summation and been relentless about checking sums and differences. Adding lots of multiples of sums has had a great effect.

For those who care, here is the scratch code I used to see which formulas were worth it.

**Representation Formulas:**

1. Multiplication by small primes:
`(X){}`
`((X)){}{}`
`((((X)))){}{}{}{}`
`((((((X)))))){}{}{}{}{}{}`
2. Addition *X*+*Y*:
`XY`
3. Subtraction *X*-*Y*:
`X[Y]`
4. Summation to and including *X* of increment *Y*:
`(X){({}[Y])}{}`
5. Multiples of summations to *X* of increment *Y*, plus *X*:
`(X)({({}[Y])}{}){}`
`(X)(({({}[Y])}{})){}{}`
`(X)(({({}[Y])}{}){}){}`
etc...

# Answer
> 5 votes
# ruby, 60246 bytes

```
$brain_flak = Hash.new{|h, k|
    a = []
    a.push "()"*k
    if k > 1
        if k > 10
            # Triangle Numbers:
            n = (Math.sqrt(1+8*k).to_i-1)/2
            if (n*n+n)/2 == k
                a.push "("+h[n]+"){({}[()])}{}"
                a.push  h[n+n]+")({({}[()])}{}"
            end
        end
        (k**0.51).to_i.downto(2){|i|
            # multiplication:
            if k%i==0
                a.push "("*(i-1) + h[k/i] + ")"*(i-1)+"{}"*(i-1)

            end
        }
        (k/2).downto(1){|i|
            # Addition
            a.push h[k-i] + h[i]
        }
    end

    h[k] = a.min_by{|x|x.length}
}
$brain_flak[0] = "<><>"

def get_code_for (i)
  "(#{$brain_flak[i]})"
end

```

I use a hash. I finds the best golf for a given number and uses the smaller ones to find the larger ones.

Recursive hashes are so much fun!

# Answer
> 2 votes
# Python, 64014 characters

I didn't know anything about brainflak before this challenge and only fiddled around with it a bit on tryitonline, so there could be obvious shortcuts I missed. This is a quite boring solution, just splits the input into `x=x/2+x%2` or `x=x/3+x%3`, whichever is shorter.

```
k=lambda x:"(("+o(x/3)+")){}{}"+(x%3)*"()"if x>3else"()"*x
m=lambda x:"("+o(x/2)+"){}"+(x%2)*"()"if x>6else"()"*x
o=lambda x:min(k(x),m(x),key=len)
b=lambda x:"("+o(x)+")"

```

Call it like so: `b(42)`

## output on pastebin

# Answer
> 2 votes
## Lua, 64664 bytes

Program prints the total length of the programs and the program for the 203rd prime (theres a line you can change to change which one is printed, or uncomment a line to print all the programs)

Right now the only optimization is x = 2\*n + 1

Hopefully I will have time to add some more optimizations to lower the score.

```
local primeS = [[<INSERT PRIMES HERE>]]

local primes = {}

for num in primeS:gmatch("%d+") do
    table.insert(primes, num+0)
end

local progs = {}
progs[0] = ""
progs[1] = "()"
progs[2] = "()()"

local function half(n)
    if progs[n] then return progs[n] end
    local p = ""
    local div = math.floor(n/2)
    local rem = n%2 == 1 and "()" or ""
    return "("..progs[div].."){}"..rem
end

for i = 3, 10000 do

    local bin = half(i)

    progs[i] = progs[i-1] .. "()"

    if #bin < #progs[i] then
        progs[i] = bin
    end

    if i % 1000 == 0 then
        print(i)
    end

end

local n = 203 -- This is the program it outputs
print(n..", ("..progs[203]..")")

local len = 0
for i,v in ipairs(primes) do
    len = len + #progs[v] + 2
    --print(v.." ("..progs[v]..")\n")
end
print("Total len: "..len)

```

# Answer
> 1 votes
# Husk, 64664, 35 bytes

```
?*"()"¹+*"()"%2¹`+"){}":'(₀½-%2¹¹<6

```

Try it online!

Husk is a golfing language so making a high scoring solution is a little hard, simply because long Husk code quickly becomes unwieldy. I just gave this a shot to practice my Husk.

This implements the same algorithm as my Brain-Flak solution from earlier.

---
Tags: metagolf, stack, test-battery, brain-flak
---


title: The puppy command

text:
# Question
Title: The puppy command
The `puppy` utility takes a filename as input, and does exactly what you would expect a puppy to do: it shreds it!

## How to shred

1. ~~Rip out the pages with your teeth~~ Split the input file on newlines.
2. ~~Tear up each page with your paws~~ For each line (not including the linefeed), pick a random integer `n` such that `2 <= n <= # of characters in the line`. Split the line into `n` non-empty non-overlapping substrings of random length.
3. ~~Scatter the shreds all over the floor~~ Output each substring of each line to a unique random filename (`[a-zA-Z0-9]` only, any consistent extension including none, length `1 <= n <= 12`) in the current directory. Overwriting pre-existing files within the current directory (including the input file, if it is in the current directory) is acceptable, as long as it does not interfere with your submission running.

## Clarifications

* There will never be an input where it is possible to use up all of the possible filenames.
* Files will consist of only printable ASCII (ordinals 32-127) and linefeeds, and will use UNIX/Linux-style line endings (LF, not the Windows-style CRLF).
* A single trailing newline in output files is acceptable as long as every output file has a trailing newline, but is not required. You may choose whether or not the input file contains a trailing newline.
* Each line in the input will contain at least 2 characters.
* The random values chosen must be chosen from a uniform random distribution on the given set of possible values.

If your language is unable to perform file I/O, you may instead take the input file's contents as input, and output pairs of strings representing the output filename and the text for that file. However, your submission will not be eligible for winning.

## Example

Reference implementation:

```
#!/usr/bin/env python3

import random
import string
import sys

fname = sys.argv[1]
with open(fname) as f:
  txt = f.read().rstrip().split('\n')

for line in txt:
  n = random.randint(2, len(line))-1
  idxs = [0]+random.sample(range(1, len(line)), n)+[len(line)]
  idxs.sort()
  splits = []
  for i in range(0, len(idxs)-1):
    splits.append(line[idxs[i]:idxs[i+1]])
  ofnames = []
  for s in splits:
    flen = random.randint(1, 10)
    ofname = ''
    while ofname == '' or ofname in ofnames:
      ofname = ''
      for i in range(flen):
        ofname += random.choice(string.ascii_letters+string.digits)
    ofnames.append(ofname)
    with open(ofname, 'w') as f:
      f.write(s)

```

Example run:

```
$ cat bestsong.txt
Never gonna give you up
Never gonna let you down
Never gonna run around
And desert you!

$ puppy bestsong.txt

$ ls
8675309
a
bestsong.txt
cSdhg
Dq762
jq7t
ret865
rick4life
weu767g
xyzzy

$ cat 8675309
esert you!

$ cat a
Never gonna let you down

$ cat cSdhg
ive y

$ cat Dq762
And d

$ cat jq7t
Never gonna g

$ cat ret865
run arou

$ cat rick4life
Never gonna

$ cat weu767g
nd

$ cat xyzzy
ou up

```

# Answer
## PowerShell v2+, ~~215~~ 211 bytes

```
nal d Get-Random;gc $args[0]|%{$b=d(0..($l=($t=$_).length)) -C(d(2..$l));$b=$b+0+$l|select -u|sort;0..($b.count-2)|%{-join($t[$b[$_]..($b[$_+1]-1)])}}|%{$_>(-join[char[]](d(48..57+65..90+97..122) -c(d(1..12))))}

```

Requires v2 or newer since v1 didn't have `Get-Random` available.
Edit -- saved 4 bytes by using char-array casting instead of individually casting each letter

**Somewhat Ungolfed**

```
Get-Content $args[0]|ForEach-Object{
  $t=$_
  $l=$t.length
  $b=Get-Random(0..$l) -Count(Get-Random(2..$l))
  $b=$b+0+$l|Select-Object -unique|Sort-Object
  0..($b.count-2)|ForEach-Object{
    -join($t[$b[$_]..($b[$_+1]-1)])
  }
}|ForEach-Object{
  $_>(-join[char[]](Get-Random(48..57+65..90+97..122) -count(Get-Random(1..12))))
}

```

### Explanation

Starts with setting `d` as a `New-Alias` for `Get-Random`, so we don't have to type out `Get-Random` each time we're using it (a lot). We then `Get-Content` of our input `$args` and pipe those through a loop with `|%{...}`. Note that `Get-Content` will by default split on newlines (either CRLF or just LF), so we don't need to do anything additional there.

Each iteration of the loop, we start with formulating the slices this line is going to be Ginsu'd into. Set `$t` equal to the line we're working with, and `$l` equal to its length, then construct a collection from `(0..$l)`. This represents all possible character indices in our current line. We then `Get-Random` from between `(2..$l)` to determine how many to select, and then get a random number of indices equal to that `-c`ount. Store those indices in `$b`.

We then also add on `0` and `$l` to `$b`, so we have the beginning and end of our line guaranteed to be in the collection of indices. Pipe that through to `Select-Object` with the `-u`nique flag, then pipe to `Sort-Object`, so our indices are now guaranteed to start with the first character and end with the last character, and some random number in between.

Next, we're looping over all the indices in `$b` with `0..($b.count-2)|%{...}`. Each of those loop iterations, we're slicing `$t` (our current line of text) and then `-join`ing them together into a string (rather than a char-array). Those get bundled up and left on the pipeline, and we close the outer loop.

So now we have an in-order collection of random slices of each of the lines of text. (Meaning, at this point, if we simply `-join`ed them back together, we'll get the original text minus newlines.) We then pipe that collection through another loop `|%{...}` and each iteration we're outputting that slice to a file with `$_>...`. The file is created by taking from 1 to 12 random integers that correspond with ASCII codes for `[0-9A-Za-z]`. No file will have an extension, and the `>` command will output a trailing newline by default on every file.

### Example
> 3 votes

# Answer
# APL (Dyalog Unicode), ~~85 80 67~~ 62 bytes

```
{⍵⎕NPUT(⎕A,⎕D,¯1⎕C⎕A)[?62/⍨?12]1}¨⊃,/{⍵⊆⍨(⍋⊃¨⊂)?⍴⍨≢⍵}¨⊃⎕NGET⍞1

```

Try it online!

This was a fun one.

Full program which takes a string as input, and outputs files to wherever the `]cd` command points to in the Dyalog workspace.

Done with some advice from dzaima.

-13 bytes from Bubbler, by removing ⎕UCS 10. -5 more bytes from Bubbler after some more smaller golfs and change to the sorting idiom.

## Output

Input file is a list of numbers from 1-99 from my "Size Up a Number" challenge.

## Explanation

`⊃⎕NGET⍞1` read file from location as APL array, take first element, split on newlines. (mode 1)

(last two elements are file attributes)

`{⍵⊆⍨(⊂∘⍋⌷⊢)?(/⍨≢⍵)}¨` *for each line, execute the following:*

`(/⍨≢⍵)`  create a list of the length repeated length times

`?`  generate random numbers within those ranges

`(⊂∘⍋⌷⊢)`  sort in ascending order

`⍵⊆⍨`  partition the line according to the sorted array

`⊃,/` join into a single vector and remove nesting

`{⍵⎕NPUT(⎕A,(¯1∘⎕C⎕A),⎕D)[?(?12)/62]1}` for each partition, do the following:

`(⎕A, )`  create a list with the uppercase alphabet,

`( (¯1∘⎕C⎕A) )`  the lowercase alphabet,

`( ,⎕D)`  and numbers from 0-9.

`[ (?12) ]`  generate a random number in range 1-12

`[ /62]`  replicate 62 that many times

`[? ]`  create that many random numbers in range 1-62, and index into the list.

`⍵⎕NPUT 1`  write the partition into the random filename, creating it if necessary.
> 2 votes

---
Tags: code-golf, string, random, file-system
---


title: More Codington Crescent

text:
# Question
Title: More Codington Crescent
*Who's up for a second attempt?*

If you've ever listened to the radio program "I'm sorry, I haven't a clue", then you've probably heard of the game called "Mornington Crescent". For those who haven't, it's a game where players name random stations on the London Underground network. The first person to name "Mornington Crescent" wins the game.1

Very much like last time, I present to you another game of **Codington Crescent**.

## The Challenge

The winner of this challenge is the first person to post a working program that, given a variable-sized list of positive integers, returns the average (arithmetic mean) of said list. The list will not be empty and will always have at least one item. Input and output can be given in any reasonable and convenient format

### Test Cases

```
[150, 541, 168, 225, 65, 191, 964, 283, 825, 5, 802, 426, 45, 326, 22, 619, 281] => 349.29411764705884
[874, 33, 423, 36, 1000, 255, 345, 902, 700, 141, 916, 959, 222, 246, 96] => 476.53333333333336
[567, 868, 680, 121, 574, 391, 233, 39, 764, 499, 455, 684, 742, 117, 376] => 474.0
[177, 372, 778, 709, 474, 796, 840, 742] => 611.0
[181, 751, 940, 782, 727, 756, 541, 762, 677, 751, 719] => 689.7272727272727
[47, 804, 782, 231, 170] => 406.8
[315, 972] => 643.5
[679, 727] => 703.0
[859, 229, 363, 468, 103, 104, 570, 772, 83, 693, 898, 672, 306, 733, 189, 717, 231] => 470.0
[228, 839] => 533.5
[395, 622, 760, 820, 70, 814, 797, 202, 277, 663, 93, 218, 564, 735] => 502.14285714285717
[724, 631, 932, 333, 605, 880, 670, 468, 703, 744, 680, 28] => 616.5
[950, 733, 305, 178, 995] => 632.2
[762, 506, 553, 284, 499, 694, 665, 998, 576, 504, 123, 658, 943, 385, 354, 732] => 577.25
[151, 919, 514, 721, 426, 333, 808, 514] => 548.25
[995] => 995.0
[891, 243, 42, 968, 458, 372, 301, 269, 559, 394, 980, 372, 804, 429, 738] => 521.3333333333334
[147, 473, 632] => 417.3333333333333
[105, 483, 225, 541, 684, 456, 328] => 403.14285714285717
[311, 1, 770, 417, 910, 185, 375, 631, 226, 266, 609] => 427.3636363636364

```

Test case generator

## The Rules

1. Each player has their own program that they will add/change characters. This is termed their **running program**.

In this way, the only answer-chaining aspect is the rules. Everyone uses their own running program. No one shares a program at all 2. Each answer (a **turn**) has to obey source restrictions defined by previous answers. These are called **rules**. Each variant lasts for 5 **turns**. Rules are in the form of restrictions.
3. Running programs can change languages between turns.
4. Answerers (players) can either add, change or remove (but only one of the options) as many characters of their running program per turn as they like. Alternatively, they can choose to "pass" (more scientifically, **farkle**), adding no new rules, and still counting as a turn. This may be the only choice if rules conflict with each other. The turn count is still incremented and is to be posted. Pro tip: You probably might want to mark it community wiki because it doesn't add much.
5. At the end of each turn, the player declares a new rule that will span the next 5 turns. Rules must be objective, and a TIO verification program is highly recommended. Also, rules have to be able to be applied to every language (e.g. `Programs must not error using Python 3.4.2` isn't a valid rule).
6. Play continues until a running program achieves the target result.
7. If a turn hasn't been taken for a week, then an implicit *farkle* will occur. You can always take a turn after an implicit farkle, as it counts as a turn (think of it as the Community user's turn).

## Starting Rules

As to kick off the game, the first 5 turns must follow these rules:

1. Turns may not accomplish the end goal
2. Minimum program length is 10 bytes

## Permanent Rules

Last time, it was noted that the following rules suited better as a permanent rule rather than 5-turn rules:

3. Running programs must be irreducible. Irreducible in this case means that the program doesn't produce the output of the whole program if characters from the whole program are removed. Ie. There does not exist a program that has the default same output that can be constructed by removing characters from the original program.)
4. A program cannot win within 5 turns of its first appearance

## Example Rules

These are purely examples of what you could add as rules to the challenge. They do not apply unless someone decides to use them.

* **The first and last character of the running program must be a space**
* **Running programs must have an even amount of bytes**
* **Running programs must not be more than 30 bytes**

## Extra Answer Chaining Rules

* You cannot answer twice in a row. Someone else needs to answer before you have another go.
* Languages need to be on Try It Online to be valid answers.

**Pro-tip: sort by oldest for a more cohesive flow of answers**

1 The original game of Mornington Crescent doesn't really have rules... It's more of an activity that looks like it's a complicated game.

## Answer Template

```
# [Language], turn number [your turn]

    <code>

[Try it online link]
[prev answer link]

## Rules

- Rule (n turns left)
- Rule (n turns left)
- Rule (n turns left)

```

# Answer
> 3 votes
# 05AB1E, turn 3

```
$XY~sDOsg/*+

```

Try it online!

(How do I link to previous answer?)

Boy do I love Code Golf!

### Explanation

```
$               # Push 1 and input
 X              # Push 1
  Y             # Push 2
   ~            # Converts 1 and 2 to 3
    s           # Swap to get implicit input
     D          # Duplicate
      O         # Sum the list
       s        # Swap top 2 values and gets the preserved list.
        g       # Push the length of the list.
         /      # Push the quotient of sum and length
          *     # Multiply with 3
           +    # Add with one

```

## Current rules

* Turns may not accomplish the end goal - Prints the triple the average plus one (**2 turns left!**)
* Minimum program length is 10 bytes (3 turns left) - Length of the program is 12 bytes (**2 turns left!**)
* Programs must contain the ~ character - The character is supposed to push the bitwise OR of 1 and 2 (*3 turns left!*)
* Programs must have an average byte value of less than or equal to 80 - The average byte value of the program is 79.25 (4 turns left!)

### The new rule

*Drumroll*

---

The program must include 5-10 non-alphanumeric characters (5 turns left!)

# Answer
> 2 votes
# Io, 20 bytes

Returns the average+1.

```
method(~,~average+1)

```

Try it online!

## Rules

the first 5 turns must follow these rules:

* Turns may not accomplish the end goal
* Minimum program length is 10 bytes

this applies for all running programs:

* Running programs must be irreducible. Irreducible in this case means that the program doesn't produce the output of the whole program if characters from the whole program are removed. Ie. There does not exist a program that has the default same output that can be constructed by removing characters from the original program.)
* A program cannot win within 5 turns of its first appearance

New rule:

* Programs must contain the `~` character

# Answer
> 2 votes
# Python 3, 23 bytes, turn 2

```
lambda l:sum(l)/~len(l)

```

Try it online!

Input as a list of floats; outputs as a float.

## Rules

Permanent rules:

* Running programs must be irreducible. Irreducible in this case means that the program doesn't produce the output of the whole program if characters from the whole program are removed. Ie. There does not exist a program that has the default same output that can be constructed by removing characters from the original program.)
* A program cannot win within 5 turns of its first appearance

Current rules:

* Turns may not accomplish the end goal (3 turns left)
* Minimum program length is 10 bytes (3 turns left)
* Programs must contain the `~` character (4 turns left)

My new rule:

* Programs must have an average byte value of less than or equal to 80. (verifier)

# Answer
> 1 votes
# Befunge-98 (PyFunge), 13 bytes, turn 5

(turn 4 was an implicit farkle)

```
"PDPF"4(~FP@

```

This answer is far from winning, but I'm including some characters an average program in this language will likely need, and keeping the challenge alive.

Try it online!

Previous answer

Rules:

* Programs may not accomplish the end goal (last turn)
* Minimum program length is 10 bytes (last turn)
* Programs must contain the ~ character (1 turn left)
* Programs must have an average byte value of less than or equal to 80. (2 turns left)
* The program must include 5-10 non-alphanumeric characters (3 turns left!)
* Programs may not contain 2 consecutive lowercase letters (5 turns left)

---
Tags: code-challenge, restricted-source, answer-chaining
---


title: How should I tile my kitchen?

text:
# Question
Title: How should I tile my kitchen?
I recently ordered some new and colorful tiles to replace my boring old white tiling for my kitchen. However, when the tiles arrived, they were all in a weird shape! Therefore, I need a program to figure out how to arrange the tiles so that I need to use as few of my old boring white tiling as possible.

Even though the tiles are weird, I'm not a fan of abstract design stuff, so the tiling should be regular. To be precise, it should be a **lattice**: there should no rotation or reflection of the tiles, and there should be two translations `S` and `T` which are combined to place the tiles with relative offsets of `aS + bT` for all `a` and `b`. Of course, the tiles shouldn't overlap when placed in this lattice arrangement.

I'll give you the tile in string format, and I need you to output the tiling. You may need to cut some of the tiles where they extend beyond the edges of my kitchen. For example:

```
abc        abcdefabcdef
 def   ->  cdefabcdefab
           efabcdefabcd

```

can be broken down as

```
+-----+   +-+-----+   +-+
|a b c|d e f|a b c|d e f|
+-+   +-+---+-+   +-+---+
 c|d e f|a b c|d e f|a b
  +-+---+-+   +-+---+-+
 e f|a b c|d e f|a b c|d
----+-+   +-----+-+   +-

```

where the translations are `(+6, 0)` and `(+4, +1)`. All but three of the tiles have been cut in this example.

You will be given a string to tile either via function parameter or STDIN. Spaces in the tile are considered "empty" and can be filled with other tiles.

My kitchen is 30x30 squares big, so all you need to do is make the number of empty squares is as small as possible in that area. You only need to print out 1 valid 30x30 square, which means that there may not be any lattice arrangement which has a 30x30 square with fewer empty squares.

Examples (I'm not going to give the full 30x30 square for brevity):

```
Input:
ab
 a
Output:
abaaba
baabaa
aabaab

Input:
xxx
x x y
xxx

Output:
xxxxxxxxxxx
xyxxyxxyxxy
xxxxxxxxxxx
xxxxxxxxxxx
xyxxyxxyxxy
xxxxxxxxxxx

Input:
012
 3 4
  56
Output:
0123 456
23 45601
 4560123
5601234

Input:
rrr
R r
Output:
rrrR r
R rrrr
rrrR r

Input:
defg
  c
ab
Output:
cabdefg cab
defg cabdef
g cabdefg c
abdefg cabd
efg cabdefg
 cabdefg ca
bdefg cabde
fg cabdefg

```

Your program should run in a reasonable amount of time, and this is , so the shortest program wins!

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

```
{G←{⍵⊃⍨⊃⍋(+/' '=,)¨⍵}
G{s←,30-⍳,⍨61
G,⊢∘⊂⌺30 30⊢((≢a)/⍪' '~⍨,x)@(B∘.+a)⊢''⍴⍨(⍴b)+⊃⌈/a←(⊢-⌊/)(⊃+/)¨s×⊂⍵}¨o/⍨(⍱/X∊⍨+/,-/)¨o←,∘.,⍨⊂¨∪{⍵/⍨0<2⊥¨×⍵}(,B∘.-⍸b<(1∊⊢)⌺3 3⊢b)~X←,B∘.-B←⍸b←(⍉0,⌽)⍣4⊢' '≠x←⍵}

```

Try it online!

A monadic dfn that takes a matrix of characters and returns the 30-by-30 matrix of a possible tiling with minimal blanks. Runs in 5 seconds for the smallest test case and in under a minute for the last one.

### The idea

The task looks pretty straightforward at first glance, but it was surprisingly hard to derive a valid solution, and even harder to get one that "runs in a reasonable amount of time" (which somewhat explains why it was unanswered so far).

The first obstacle was that there are infinitely many possible tiling vectors. I solved this by limiting the vectors to the ones where the original tile and the moved tile share at least a point. If `ab` is the given tile, this means the following movements are considered as tiling vector candidates:

```
                                        AB   AB  AB  AB   AB
ABab    ab   ab  ab  ab   ab    abAB  ab    ab   ab   ab    ab
      AB    AB   AB   AB    AB

```

Then I filter out redundant ones (keeping only one of \\$v\\$ or \\$w\\$ when \\$v = -w\\$), generate all possible pairs of these candidate tiling vectors, and only keep the ones \\$v, w\\$ where neither \\$v+w\\$ nor \\$v-w\\$ movement overlaps with the original tile.

Reasoning: We know that the pairs of tiles at offsets \\$(0, v)\\$ and \\$(0, w)\\$ do not overlap, and therefore \\$(v, v+w)\\$ and \\$(w, v+w)\\$. Once it is known that \\$(0, v+w)\\$ and \\$(v, w)\\$ (alternatively \\$(0, v-w)\\$) pairs are safe, we know that \\$(0, v, w, v+w)\\$ are mutually safe, and by translation in four directions \\$v, w, -v, -w\\$, the entire infinite tiling is safe.

Given a full list of candidate vector pairs, I chose a naive way: for each vector pair, generate a large enough board of actual tiling, extract all 30-by-30 regions, and choose the one with the smallest number of blanks. For that, I used \\$-30 \le a,b \le 30\\$ for the formula \\$av + bw\\$. In order to prevent the memory (and execution time) blowing up, I apply this filtering twice, first within each vector pair, and then across all minimally chosen boards.

### Ungolfed

The code changed a lot while golfing, but the core idea remains the same.

```
f←{
  ⍝ A boolean matrix where 1 means non-blanks, padded once to all directions
  bool←(⍉0,,∘0)⍣2⊢' '≠x←⍵
  ⍝ Spread 1s to adjacent cells (8 directions)
  padded←({1∊⍵}⌺3 3>⊢)bool
  ⍝ Extract the coordinates of ones
  cbool←⍸bool
  cpadded←⍸padded
  ⍝ badoffs: All offsets that move a cell to already occupied cell
  ⍝ offs: All offsets that move a cell to a cell adjacent to the tile,
  ⍝       badoffs removed and (negative, any) and (zero, negative) removed
  offs←∪{⍵/⍨0<2⊥¨×⍵}(,cbool∘.-cpadded)~badoffs←,cbool∘.-cbool
  ⍝ Pairs of valid offsets
  offpairs←,∘.,⍨⊂¨offs
  ⍝ Remove offset pairs (v,w) if v+w or v-w is bad
  filter←{⍱/(⍺+⍵)(⍺-⍵)∊badoffs}/¨offpairs
  pairs←filter/offpairs

  ⍝ Aux. function: Select the matrix with smallest number of blanks
  MinBlanks←{⍵⊃⍨⊃⍋(+/' '=,)¨⍵}
  ⍝ Aux. function: Given an offset pair, tile the floor using them and
  ⍝                extract the 30x30 region with minimum blanks
  GetResults←{
    somepair←⍵
    ⍝ -30 to 30, inclusive (the values of a and b)
    steps←30-⍳61
    ⍝ All values of av + bw, offset to the minimum coordinates of (0,0)
    alloffs←⊃{,(steps×⊂⍺)∘.+steps×⊂⍵}/somepair
    alloffs-←⌊/alloffs
    ⍝ Initialize a big enough blank grid
    dims←(⍴bool)+⊃⌈/alloffs
    grid←dims⍴''
    ⍝ Fill the grid with the tiles' cells moved accordingly
    filled←((≢alloffs)/⍪' '~⍨,x)@(cbool∘.+alloffs)⊢grid
    ⍝ Extract all 30x30 regions and return the one with minimum blanks
    results←,{⊂⍵}⌺30 30⊢filled
    MinBlanks results
  }
  ⍝ Map the above function over each of the pairs, and extract min blanks
  results←GetResults¨pairs
  MinBlanks results
}

```

---
Tags: code-golf, grid, restricted-time, tiling
---


# Question
Title: Find the numbers coprime to their decimal digits
Two numbers are coprime if their greatest common divisor is 1.

Given a positive integer **N**, your task is to compute the first **N** terms of OEIS A061116, which is the sequence of positive integers higher than 1 that are coprime to all their *decimal* digits.

Here are the first few terms of the sequence:

```
11, 13, 17, 19, 21, 23, 27, 29, 31, 37, 41, 43, 47, 49, 51, 53, 57, 59, 61, 67, 71

```

You can assume that **N \< 200**.

---

# Test Cases

```
Input -> Output

1 -> 11
3 -> 11, 13, 17
6 -> 11, 13, 17, 19, 21, 23
25 -> 11, 13, 17, 19, 21, 23, 27, 29, 31, 37, 41, 43, 47, 49, 51, 53, 57, 59, 61, 67, 71, 73, 79, 81, 83

```

You may output in any decent form (as a list, with a separator or whatever else). You can take input as the String representation of **N** or as an integer. Standard I/O rules apply.

---

Default Loopholes apply. This is , so the shortest code in bytes wins!

# Answer
# Plain English ~~853~~ ~~787~~ ~~738~~ ~~594~~ ~~550~~ ~~538~~ 532 bytes

Removed 66 bytes of white space. Removed 49 bytes by using a more generic output type. Removed 144 bytes by abbreviating variable names, and reusing the quotient and the remainder. Removed 44 bytes by abbreviating an interface. Shortened `Destroy the number things.` to `Destroy the L.` Removed 6 bytes by changing "some" to "a", and "number" to "count".

Golfed code:

```
To create a L number things given a c count:
Put 0 in a i count.
Loop.
Add 1 to a n count.
If the i is at least the c, exit.
If the n is g,
append the n to the L;
add 1 to the i.
Repeat.
To decide if a n count is g:
If the n is at most 10, say no.
Put 1 in a m count.
Loop.
If the m is greater than the n, say yes.
Divide the n by the m giving a q quotient and a r remainder.
Divide the q by 10 giving the q and the r.
Get a gcd given the n and the r.
If the gcd is at least 2, say no.
Multiply the m by 10.
Repeat.

```

Ungolfed code:

```
Some special numbers are some number things.

To create some special numbers given a count:
  Put 0 in another count.
  Loop.
    Add 1 to a number.
    If the other count is at least the count, exit.
    If the number is coprime with its digits,
      Append the number to the special numbers;
      Add 1 to the other count.
  Repeat.

To decide if a number is coprime with its digits:
  If the number is at most 10, say no.
  Put 1 in another number.
  Loop.
    If the other number is greater than the number, say yes.
    Divide the number by the other number giving a quotient and a remainder.
    Divide the quotient by 10 giving another quotient and another remainder.
    Get a gcd given the number and the other remainder.
    If the gcd is greater than 1, say no.
    Multiply the other number by 10.
  Repeat.

```

"Some number things" are a doubly-linked list of numbers. The calling code has the responsibility to `Destroy the special numbers.`, so I have added the corresponding bytes.

The Plain English IDE is available at github.com/Folds/english. The IDE runs on Windows. It compiles to 32-bit x86 code.
> 7 votes

# Answer
# Jelly, ~~10~~, 8 bytes

```
gQỊẠ
2Ç#

```

Try it online!

2 bytes saved thanks to @Dennis!

Explanation:

```
        # Helper link: Is it in the sequence at all?
   Ạ    # All of...
g       # The GCDs of A and...
 Q      # The unique digits of A
  Ị     # Are less than or equal to 1
        #
        # Main link:
  #     # The first *n* truthy results of
 Ç      # The last link
2       # Starting at 2

```
> 6 votes

# Answer
# Perl 6, 39 bytes

```
{(grep {$_ gcd.comb.all==1},2..*)[^$_]}

```

Try it online!
> 5 votes

# Answer
# Mathematica, ~~80~~ ~~70~~ 64 bytes

```
For[t=2;n=#,n>0,t++,Max[t~GCD~IntegerDigits@t]<2&&Print@t&&n--]&

```

Try it online!

*-10 bytes thanx to @MartinEnder*
*-6 bytes from @JungHwan Min*
> 4 votes

# Answer
# Haskell, ~~64~~ ~~59~~ ~~58~~ ~~57~~ 51 bytes

Saved a total of 6 bytes thanks to @Laikoni and @Ørjan Johansen

```
(`take`[x|x<-[2..],and[x`gcd`read[c]<2|c<-show x]])

```

Try it online!
> 3 votes

# Answer
## Haskell, 115 bytes

```
q n=take n(filter(\x->1==(maximum$map(x%)(d x)))[11,13..])
d 0=[]
d x=mod(x)10:(d(x`quot`10))
x%0=x
x%y=y%(x`mod`y)

```
> 2 votes

# Answer
# Husk, 11 bytes

```
↑tfȯεΠṠM⌋dN

```

Try it online!
> 2 votes

# Answer
## JavaScript (ES6), 93 bytes

```
f=(n,k=11,g=(a,b)=>b?g(b,a%b):a)=>n?[...''+k].some(d=>g(k,d)>1)?f(n,k+1):[k,...f(n-1,k+1)]:[]

```
> 1 votes

# Answer
# PHP, 120 bytes

```
for($n=2;!$r[$argn-1];$t?:$r[]=$n,$n++)for($t=$i=0;~$s=("$n")[$i++];$t|=$d)for($d=$s?:$t|=1;$s%$d|$n%$d--;);print_r($r);

```

Try it online!
> 1 votes

# Answer
# Japt, 10 bytes

```
Èì ejX}jUB

```

Try it
> 1 votes

# Answer
# Husk, 14 bytes

```
↑tfλΛȯεnḊ¹Ḋd)N

```

Try it online!

## Explanation

```
↑tfλΛȯεnḊ¹Ḋd)N
  fλ        )N filter all natural numbers by the following lambda:
    Λȯ     d   map each digit of the natural number, and check if all are truthy:
        Ḋ¹Ḋ    divisors of the digit and divisors of the argument
       n       set intersection
      ε        has length 1? (co primality check)
 t             remove the first element
↑              take n items from the sequence(n → input)

```
> 1 votes

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


# Question
Title: Generate a congruent list with the smallest sum
Two lists `A` and `B` are congruent if they have the same length, and elements that compare equal in `A` compare equal in `B`.

In other words, given any two valid indices `x` and `y`:

* If `A[x] = A[y]`, then `B[x] = B[y]`.
* If `A[x] != A[y]`, then `B[x] != B[y]`.

For example, the lists `[1, 2, 1, 4, 5]` and `[0, 1, 0, 2, 3]` are congruent.

## The Task

Given a nonempty list of *nonnegative* integers `A`, return a new list of *nonnegative* integers `B` such that is congruent to `A`, while minimizing the sum of the integers in `B`.

There are potentially many possible valid outputs. For example, in the list `[12, 700, 3]`, any permutation of `[0, 1, 2]` would be considered valid output.

## Test Cases

```
Format:
input ->
one possible valid output

[1 2 1 4 5] ->
[0 1 0 2 3] (this is the example given above)

[3 2 2 1 5 7 2] ->
[1 0 0 2 3 4 0]

[8 8 8 8 8] ->
[0 0 0 0 0]

[2] ->
[0]

[8 6 8 4 6 8 2 4 6 8 0 2 4 6 8] ->
[0 1 0 2 1 0 3 2 1 0 4 3 2 1 0]

[14 1] ->
[1 0]

[19 6 4 9 14 17 10 9 6 14 8 14 6 15] ->
[8 0 3 2 1 7 5 2 0 1 4 1 0 6]

[15] ->
[0]

[1 18 4 8 6 19 12 17 6 13 7 6 8 1 6] ->
[1 8 3 2 0 9 5 7 0 6 4 0 2 1 0]

[9 10 11 9 7 11 16 17 11 8 7] ->
[2 4 0 2 1 0 5 6 0 3 1]

[1 3 16 19 14] ->
[0 1 3 4 2]

[18 8] ->
[1 0]

[13 4 9 6] ->
[3 0 2 1]

[16 16 18 6 12 10 4 6] ->
[1 1 5 0 4 3 2 0]

[11 18] ->
[0 1]

[14 18 18 11 9 8 13 3 3 4] ->
[7 1 1 5 4 3 6 0 0 2]

[20 19 1 1 13] ->
[3 2 0 0 1]

[12] ->
[0]

[1 14 20 4 18 15 19] ->
[0 2 6 1 4 3 5]

[13 18 20] ->
[0 1 2]

[9 1 12 2] ->
[2 0 3 1]

[15 11 2 9 10 19 17 10 19 11 16 5 13 2] ->
[7 2 0 5 1 3 9 1 3 2 8 4 6 0]

[5 4 2 2 19 14 18 11 3 12 20 14 2 19 7] ->
[5 4 0 0 2 1 9 7 3 8 10 1 0 2 6]

[9 11 13 13 13 12 17 8 4] ->
[3 4 0 0 0 5 6 2 1]

[10 14 16 17 7 4 3] ->
[3 4 5 6 2 1 0]

[2 4 8 7 8 19 16 11 10 19 4 7 8] ->
[4 1 0 2 0 3 7 6 5 3 1 2 0]

[15 17 20 18 20 13 6 10 4 19 9 15 18 17 5] ->
[0 1 3 2 3 9 6 8 4 10 7 0 2 1 5]

[15 14 4 5 5 5 3 3 19 12 4] ->
[5 4 2 0 0 0 1 1 6 3 2]

[7 12] ->
[0 1]

[18 5 18 2 5 20 8 8] ->
[2 0 2 3 0 4 1 1]

[4 6 10 7 3 1] ->
[2 3 5 4 1 0]

[5] ->
[0]

[6 12 14 18] ->
[0 1 2 3]

[7 15 13 3 4 7 20] ->
[0 4 3 1 2 0 5]

[10 15 19 14] ->
[0 2 3 1]

[14] ->
[0]

[19 10 20 12 17 3 6 16] ->
[6 2 7 3 5 0 1 4]

[9 4 7 18 18 15 3] ->
[4 2 3 0 0 5 1]

[7 4 13 7] ->
[0 1 2 0]

[19 1 10 3 1] ->
[3 0 2 1 0]

[8 14 20 4] ->
[1 2 3 0]

[17 20 18 11 1 15 7 2] ->
[5 7 6 3 0 4 2 1]

[11 4 3 17] ->
[2 1 0 3]

[1 9 15 1 20 8 6] ->
[0 3 4 0 5 2 1]

[16 13 10] ->
[2 1 0]

[17 20 20 12 19 10 19 7 8 5 12 19] ->
[7 2 2 1 0 6 0 4 5 3 1 0]

[18 11] ->
[1 0]

[2 16 7 12 10 18 4 14 14 7 15 4 8 3 14] ->
[3 9 2 7 6 10 1 0 0 2 8 1 5 4 0]

[5 7 2 2 16 14 7 7 18 19 16] ->
[3 0 1 1 2 4 0 0 5 6 2]

[8 6 17 5 10 2 14] ->
[3 2 6 1 4 0 5]

```

This is , so the shortest valid submission (counted in bytes) wins.

# Answer
# Python 2, ~~62~~ 54 bytes

```
lambda L:map(sorted(set(L),key=L.count)[::-1].index,L)

```

Try it online!

Edit: saved 8 bytes via map thanx to Maltysen
> 5 votes

# Answer
# Pyth - ~~12~~ ~~11~~ 10 bytes

```
XQ_o/QN{QU

```

Test Suite.
> 4 votes

# Answer
# Japt, 11 bytes

```
£â ñ@è¦XÃbX

```

Test it online!

### Explanation

```
 £   â ñ@  è¦ XÃ bX
UmX{Uâ ñX{Uè!=X} bX}   Ungolfed
                       Implicit: U = input array
UmX{               }   Map each item X in the input to:
    Uâ                   Take the unique items of U.
       ñX{     }         Sort each item X in this by
          Uè!=X            how many items in U are not equal to X.
                         This sorts the items that occur most to the front of the list.
                 bX      Return the index of X in this list.
                       Implicit: output result of last expression

```
> 4 votes

# Answer
# , 11 bytes

```
i.~~.\:#/.~

```

Try it online!

## Explanation

```
i.~~.\:#/.~  Input: array A
       #/.~  Frequency of each unique character, sorted by first appearance
   ~.        Unique, sorted by first appearance
     \:      Sort down the uniques using their frequencies
i.~          First index in that for each element of A

```
> 2 votes

# Answer
# Röda, 55 bytes

```
{|l|l|indexOf _,[sort(l)|count|[[-_2,_1]]|sort|_|[_2]]}

```

Try it online!
> 2 votes

# Answer
# Haskell, ~~93~~ ~~91~~ 85 bytes

```
import Data.List
f a=[i|x<-a,(i,y:_)<-zip[0..]$sortOn((0-).length)$group$sort a,x==y]

```

Try it online!

EDIT: Thanks to @Laikoni for taking off 6 bytes!

Not very short but I can't think of anything else. The idea is to iterate over the array (`x<-a`) and perform a lookup in a tuple list (`(i,y:_)<-`...`,x==y`) that assigns a nonnegative integer to each unique element in the input based on how common it is. That tuple list is generated by first `sort`ing the input, `group`ing it into sublists of equal elements, sorting that list by the length of the sublists (`sortOn((0-).length)`; length is negated to sort into "descending" order), then finally zipping it with an infinite list incrementing from 0. We use pattern matching to extract the actual element fromm the sublist into `y`.
> 2 votes

# Answer
# CJam, ~~17~~ 14 bytes

<sup>-3 bytes thanks to Peter Taylor</sup>

This is a golfed version of the program I used to generate the testcases.

```
{_$e`$W%1f=f#}

```

This is an anonymous block that expects input as an array on top of the stack and outputs an array on top of the stack.

Explanation:

```
{_$e`$W%1f=f#} Stack:                  [1 2 1 4 5]
 _             Duplicate:              [1 2 1 4 5] [1 2 1 4 5]
  $            Sort:                   [1 2 1 4 5] [1 1 2 4 5]
   e`          Run-length encode:      [1 2 1 4 5] [[2 1] [1 2] [1 4] [1 5]]
     $         Sort lexicographically: [1 2 1 4 5] [[1 2] [1 4] [1 5] [2 1]]
      W%       Reverse:                [1 2 1 4 5] [[2 1] [1 5] [1 4] [1 2]]
        1f=    Second element of each: [1 2 1 4 5] [1 5 4 2]
           f#  Vectorized indexing:    [0 3 0 2 1]

```
> 1 votes

# Answer
# Mathematica, 94 bytes

```
(s=First/@Reverse@SortBy[Tally[j=#],Last];For[i=1,i<=Length@s,j=j//.s[[i]]->i+5!;i++];j-5!-1)&

```

Try it online!
> 1 votes

# Answer
# TI-BASIC, 66 bytes

```
Ans+max(Ans+1)seq(sum(Ans=Ans(I)),I,1,dim(Ans→A
cumSum(Ans→B
SortD(∟A,∟B
cumSum(0≠ΔList(augment({0},∟A→A
SortA(∟B,∟A
∟A-1

```

# Explanation

```
seq(sum(Ans=Ans(I)),I,1,dim(Ans    Calculates the frequency of each element of Ans.
                                   Comparing a value to a list returns a list of booleans,
                                   so taking the sum will produce the number of matches.

Ans+max(Ans+1)                     Multiplies each frequency by one more than the max element,
                                   then adds each original value.
                                   This ensures that identical values with the same frequency
                                   will be grouped together when sorting.
                                   Additionally, all resulting values will be positive.

→A                                 Stores to ∟A.

cumSum(Ans→B                       Stores the prefix sum of the result into ∟B.
                                   Since ∟A has only positive values, ∟B is guaranteed
                                   to be strictly increasing.

SortD(∟A,∟B                        Sort ∟A in descending order (by frequency), grouping
                                   identical values together. Also, dependently sort ∟B
                                   so the original ordering can be restored.

       0≠ΔList(augment({0},∟A      Prepends a 0 to ∟A and compares each consecutive difference
                                   to 0. This places a 1 at each element that is different
                                   from the previous element, and 0 everywhere else.
                                   The first element is never 0, so it is considered different.

cumSum(                      →A    Takes the prefix sum of this list and stores to ∟A.
                                   Since there is a 1 at each element with a new value,
                                   the running sum will increase by 1 at each value change.
                                   As a result, we've created a unique mapping.

SortA(∟B,∟A                        Sorts ∟B in ascending order with ∟A as a dependent,
                                   restoring the original element ordering.

∟A-1                               Since we started counting up at 1 instead of 0,
                                   subtract 1 from each element in ∟A and return it.

```
> 1 votes

# Answer
# Perl 5, 77 + 1 (-a) = 78 bytes

```
$c{$_}++for@F;%r=map{$_=>$i++.$"}sort{$c{$b}<=>$c{$a}}keys%c;print$r{$_}for@F

```

Try it online!
> 1 votes

# Answer
# JavaScript (ES6), 91 bytes

Using a list of unique values, sorted by frequency.

```
x=>x.map(x=>Object.keys(C).sort((a,b)=>C[b]-C[a]).indexOf(x+''),C={},x.map(v=>C[v]=-~C[v]))

```

**Test**

```
var F=
x=>x.map(x=>Object.keys(C).sort((a,b)=>C[b]-C[a]).indexOf(x+''),C={},x.map(v=>C[v]=-~C[v]))

Test=`[1 2 1 4 5] -> [0 1 0 2 3]
[3 2 2 1 5 7 2] -> [1 0 0 2 3 4 0]
[8 8 8 8 8] -> [0 0 0 0 0]
[2] -> [0]
[8 6 8 4 6 8 2 4 6 8 0 2 4 6 8] -> [0 1 0 2 1 0 3 2 1 0 4 3 2 1 0]
[14 1] -> [1 0]
[19 6 4 9 14 17 10 9 6 14 8 14 6 15] -> [8 0 3 2 1 7 5 2 0 1 4 1 0 6]
[15] -> [0]
[1 18 4 8 6 19 12 17 6 13 7 6 8 1 6] -> [1 8 3 2 0 9 5 7 0 6 4 0 2 1 0]
[9 10 11 9 7 11 16 17 11 8 7] -> [2 4 0 2 1 0 5 6 0 3 1]
[1 3 16 19 14] -> [0 1 3 4 2]
[18 8] -> [1 0]
[13 4 9 6] -> [3 0 2 1]
[16 16 18 6 12 10 4 6] -> [1 1 5 0 4 3 2 0]
[11 18] -> [0 1]
[14 18 18 11 9 8 13 3 3 4] -> [7 1 1 5 4 3 6 0 0 2]
[20 19 1 1 13] -> [3 2 0 0 1]
[12] -> [0]
[1 14 20 4 18 15 19] -> [0 2 6 1 4 3 5]
[13 18 20] -> [0 1 2]
[9 1 12 2] -> [2 0 3 1]
[15 11 2 9 10 19 17 10 19 11 16 5 13 2] -> [7 2 0 5 1 3 9 1 3 2 8 4 6 0]
[5 4 2 2 19 14 18 11 3 12 20 14 2 19 7] -> [5 4 0 0 2 1 9 7 3 8 10 1 0 2 6]
[9 11 13 13 13 12 17 8 4] -> [3 4 0 0 0 5 6 2 1]
[10 14 16 17 7 4 3] -> [3 4 5 6 2 1 0]
[2 4 8 7 8 19 16 11 10 19 4 7 8] -> [4 1 0 2 0 3 7 6 5 3 1 2 0]
[15 17 20 18 20 13 6 10 4 19 9 15 18 17 5] -> [0 1 3 2 3 9 6 8 4 10 7 0 2 1 5]
[15 14 4 5 5 5 3 3 19 12 4] -> [5 4 2 0 0 0 1 1 6 3 2]
[7 12] -> [0 1]
[18 5 18 2 5 20 8 8] -> [2 0 2 3 0 4 1 1]
[4 6 10 7 3 1] -> [2 3 5 4 1 0]
[5] -> [0]
[6 12 14 18] -> [0 1 2 3]
[7 15 13 3 4 7 20] -> [0 4 3 1 2 0 5]
[10 15 19 14] -> [0 2 3 1]
[14] -> [0]
[19 10 20 12 17 3 6 16] -> [6 2 7 3 5 0 1 4]
[9 4 7 18 18 15 3] -> [4 2 3 0 0 5 1]
[7 4 13 7] -> [0 1 2 0]
[19 1 10 3 1] -> [3 0 2 1 0]
[8 14 20 4] -> [1 2 3 0]
[17 20 18 11 1 15 7 2] -> [5 7 6 3 0 4 2 1]
[11 4 3 17] -> [2 1 0 3]
[1 9 15 1 20 8 6] -> [0 3 4 0 5 2 1]
[16 13 10] -> [2 1 0]
[17 20 20 12 19 10 19 7 8 5 12 19] -> [7 2 2 1 0 6 0 4 5 3 1 0]
[18 11] -> [1 0]
[2 16 7 12 10 18 4 14 14 7 15 4 8 3 14] -> [3 9 2 7 6 10 1 0 0 2 8 1 5 4 0]
[5 7 2 2 16 14 7 7 18 19 16] -> [3 0 1 1 2 4 0 0 5 6 2]
[8 6 17 5 10 2 14] -> [3 2 6 1 4 0 5]`

Test.split(`\n`).forEach(row => {
  row=row.match(/\d+/g)
  var nv = row.length/2
  var tc = row.slice(0,nv)
  var exp = row.slice(nv)
  var xsum = eval(exp.join`+`)
  var result = F(tc)
  var rsum = eval(result.join`+`)
  var ok = xsum == rsum
  console.log('Test ' + (ok ? 'OK':'KO')
  + '\nInput [' + tc
  + ']\nExpected (sum ' + xsum + ') ['+ exp
  + ']\nResult (sum ' + rsum + ') [' + result + ']')

})
```
> 1 votes

# Answer
# Jelly, 10 bytes

```
Qċ@Þ⁸UiⱮµ’

```

Try it online!

I'm certain there's a way to remove at least one byte, but I've spend an hour not finding it so...

## How it works

```
Qċ@Þ⁸UiⱮµ’ - Main link. Takes A on the left
Q          - Remove duplicates in A
   Þ       - Sort by the following function:
 ċ         -   Number of times...
  @ ⁸      -   ...in A
     U     - Reverse. Call this l
       Ɱ   - Over each element in A...
      i    -   Find its index in l
        µ’ - Decrement to account for Jelly's 1-indexing

```
> 1 votes

# Answer
# PHP, 92 bytes

```
$b=array_unique($a);print_r(array_map(function($v)use($b){return array_search($v,$b);},$a));

```

Try it online!
> 0 votes

# Answer
# , 58 bytes

```
x=scan();cat(match(x,names(z<-table(x))[rev(order(z))])-1)

```

Try it online!

Port of Chas Brown's Python answer.

`table` computes the counts of each element in `x` (storing the values as the `names` attribute), `order` returns a permutation of the indices in `z`, and `match` returns the index of the first match of `x` in `names(z)`. Then it subtracts `1` because R indices are 1-based.
> 0 votes

---
Tags: code-golf, array
---