title: How likely is this mutation?

text:
# Question
Title: How likely is this mutation?
In my previous bioinformatics challenge, I asked you to mutate a DNA sequence. This time, I'd like you to evaluate how likely a mutation, or a series of mutations, is.

The two types of substitutions are transitions and transversions, and due to the chemical structure of DNA bases, transitions are more likely to occur than transversions. A transition is when a base is turned into one of the same size (purine -\> purine or pyrimidine -\> pyrimidine), and a transversion involves two bases of different sizes (purine \<-\> pyrimidine). Following Kimura's model, postulated in 1980, we can define `a` as the probability of a transition occurring for each unit of time, and `b` as the probability of a transversion occurring.

See diagram below. A and G are purines, C and T are pyrimidines.

Although the exact values of `a` and `b` change from organism to organism (and even between different areas in an organism's genome), we can set `a=0.25` and `b=0.1` for this challenge.

Given two DNA strings of same length as input, I would like you to calculate how likely it would be for string B to be a mutated version of string A. This is code golf, so fewest bytes wins!

Test cases:

```
Input String A | Input string B | Output probability
tgcctatc       | tgcctata       |  0.1
aggttcctt      | gggttcctt      |  0.25
aactgg         | aaccgg         |  0.25
atgccct        | atcgcct        |  0.01
tatcactaag     | tgtcaatgag     |  0.00625
ctcctgggca     | cttttgcgca     |  0.00625
ctgtgtgct      | cagagagca      |  0.0001
atcgctttca     | ttggctttca     |  0.01
attcac         | taagcg         |  0.000001
attttcattg     | attttttacg     |  0.000625

```

Specifications:

* The input DNA strings can be as strings of characters, binary or numerical.
* We will assume that all of the mutations are independent events.
* The output can be in plain notation (0.00015) or scientific (\\$1.5\times10^{-4}\\$).

If you have any questions or require more specifications, send them my way in the comments!

# Answer
> 11 votes
# Jelly, 9 bytes

```
^ị“½¥¢‘İP

```

Try it online!

Takes input as `2376` instead of `acgt` respectively. The Footer does this for you

-1 byte thanks to Jonathan Allan!

## How it works

```
^ị“½¥¢‘İP - Main link. Takes the first input on the left and the second on the right
^         - XOR the corresponding elements
  “½¥¢‘   - Yield [10, 4, 1]
 ị        - Index into this array, 1-indexed and modularly
       İ  - Take the inverse of each
        P - Take the product

```

### Why this works

| Characters | As integers | `XOR` | 1-index into `[10,4,1]` | Inverse |
| --- | --- | --- | --- | --- |
| `aa` | `2, 2` | \\$0\\$ | \\$1\\$ | \\$1\\$ |
| `cc` | `3, 3` | \\$0\\$ | \\$1\\$ | \\$1\\$ |
| `gg` | `7, 7` | \\$0\\$ | \\$1\\$ | \\$1\\$ |
| `tt` | `6, 6` | \\$0\\$ | \\$1\\$ | \\$1\\$ |
| `ac` | `2, 3` | \\$1\\$ | \\$10\\$ | \\$0.1\\$ |
| `ag` | `2, 7` | \\$5\\$ | \\$4\\$ | \\$0.25\\$ |
| `at` | `2, 6` | \\$4\\$ | \\$10\\$ | \\$0.1\\$ |
| `cg` | `3, 7` | \\$4\\$ | \\$10\\$ | \\$0.1\\$ |
| `ct` | `3, 6` | \\$5\\$ | \\$4\\$ | \\$0.25\\$ |
| `gt` | `7, 6` | \\$1\\$ | \\$10\\$ | \\$0.1\\$ |

# Answer
> 9 votes
# 05AB1E, ~~22~~ ~~18~~ ~~16~~ ~~13~~ ~~12~~ ~~10~~ 9 bytes

```
^Tη4ªsèzP

```

-4 bytes by porting *@Arnauld*'s JavaScript answer (his first version)
-2 bytes by taking the inputs as lists of codepoints (thanks *@cairdCoinheringaahing*)
-3 bytes by taking the inputs as `[0,1,2,3]` for `agct` respectively
-1 byte thanks to *@cairdCoinheringaahing* by porting his Jelly answer (and now taking `[0,1,2,3]` for `acgt`)
-1 byte thanks to a tip of *@JonathanAllan* (and now taking `[2,3,7,6]` for `acgt`)

Inputs as two lists of integers `[2,3,7,6]` for `acgt` respectively.

Try it online or try it online with strings input or verify all test cases.

**Explanation:**

```
^          # Bitwise-XOR the (implicit) input-lists at the same positions together
 T         # Push 10
  η        # Pop and push its prefixes: [1,10]
   4ª      # Append a 4: [1,10,4]
     sè    # Index (0-based modular) the XOR-ed values into this list
       z   # Take 1/v for each
        P  # And take the product of the list
           # (after which the result is output implicitly as result)

```

Here the transformations per pair:

| Character-pair | values | XOR-ed | 0-based index (modulo-3) | indexed into `[1,10,4]` | 1/v |
| --- | --- | --- | --- | --- | --- |
| `aa` | \\$2,2\\$ | \\$0\\$ | \\$0\\$ | \\$1\\$ | \\$1\\$ |
| `cc` | \\$3,3\\$ | \\$0\\$ | \\$0\\$ | \\$1\\$ | \\$1\\$ |
| `gg` | \\$7,7\\$ | \\$0\\$ | \\$0\\$ | \\$1\\$ | \\$1\\$ |
| `tt` | \\$6,6\\$ | \\$0\\$ | \\$0\\$ | \\$1\\$ | \\$1\\$ |
| `ac` | \\$2,3\\$ | \\$1\\$ | \\$1\\$ | \\$10\\$ | \\$0.1\\$ |
| `ag` | \\$2,7\\$ | \\$5\\$ | \\$2\\$ | \\$4\\$ | \\$0.25\\$ |
| `at` | \\$2,6\\$ | \\$4\\$ | \\$1\\$ | \\$10\\$ | \\$0.1\\$ |
| `cg` | \\$3,7\\$ | \\$4\\$ | \\$1\\$ | \\$10\\$ | \\$0.1\\$ |
| `ct` | \\$3,6\\$ | \\$5\\$ | \\$2\\$ | \\$4\\$ | \\$0.25\\$ |
| `gt` | \\$7,6\\$ | \\$1\\$ | \\$1\\$ | \\$10\\$ | \\$0.1\\$ |

# Answer
> 7 votes
# JavaScript (ES6),  ~~52~~  51 bytes

Expects two lists of codepoints as `(a)(b)`.

```
a=>b=>a.map((c,i)=>p/=!(c^=b[i])|22%c&4||10,p=1)&&p

```

Try it online!

### How?

Given the code points **p** and **q** of the nucleobase characters, we use the formula:

```
(22 MOD (p XOR q)) AND 4

```

whose result is **4** for a transition pair (`a <-> g` or `c <-> t`) or **0** otherwise. Conveniently, **4** is the inverse of the probability of said transition.

```
 c0  | c1  |  p  |  q  | x = p^q | 22%x | &4
-----+-----+-----+-----+---------+------+----
 'a' | 'a' |  97 |  97 |     0   |  NaN |  0
 'a' | 'c' |  97 |  99 |     2   |    0 |  0
 'a' | 'g' |  97 | 103 |     6   |    4 |  4
 'a' | 't' |  97 | 116 |    21   |    1 |  0
 'c' | 'c' |  99 |  99 |     0   |  NaN |  0
 'c' | 'g' |  99 | 103 |     4   |    2 |  0
 'c' | 't' |  99 | 116 |    23   |   22 |  4
 'g' | 'g' | 103 | 103 |     0   |  NaN |  0
 'g' | 't' | 103 | 116 |    19   |    3 |  0
 't' | 't' | 116 | 116 |     0   |  NaN |  0

```

# Answer
> 6 votes
# , ~~77~~ 73 bytes

(input directly as DNA sequence)

```
function(t,f,`+`=utf8ToInt,d=abs(+t-+f)).1^sum(d>0)*2.5^sum(d%in%c(6,17))

```

Try it online!

---

# , ~~53~~ ~~50~~ 48 bytes

(input as vector of `1` for A, `2` for C, `3` for G, `4` for T)

```
function(t,f,d=(t-f)^2).1^sum(d>0)*2.5^sum(d==4)

```

Try it online!

# Answer
> 5 votes
# , 34 bytes

```
%@10 4*/@({~(>ag`ct)e.~/:~"1)~:#,.

```

Try it online!

## How it works

```
%@10 4*/@({~(>ag`ct)e.~/:~"1)~:#,.
                                ,. join the characters to pairs
                               #   take the ones
                             ~:    where both are different
                       /:~"1       sort the pairs
                    e.~            is it in …
            (>ag`ct)               'ag' or 'ct'?
          {~                       map 0 and 1 to
%@10 4                             0.1 and 0.25
      */@                          fold with multiplication

```

# Answer
> 5 votes
# Python 3, 57 bytes

```
f=lambda x,y:x==[]or[1,.1,.25,.1][x.pop()^y.pop()]*f(x,y)

```

Try it online!

Port of my Jelly answer

-2 bytes thanks to ovs!

# Answer
> 5 votes
# Wolfram Language (Mathematica), 27 bytes

```
1##&@@1[.1,.25,.1][[#-#2]]&

```

Try it online!

Uses `0123` for `acgt`.

# Answer
> 3 votes
# C (gcc), ~~79~~ 71 bytes

-8 bytes thanks to ceilingcat

```
float r;f(a,b,l)int*a,*b;{for(r=1;l--;++a,++b)*a-*b?r/=*a**b-2?10:4:0;}

```

Try it online!

The function receives two arrays of integers. The bases are mapped as follows

```
 A  G
-2 -1

 C  T
 1  2

```

This mapping allows the following decision making

```
*a-*b?r/=*a**b-2?10:4:0;

```

In a nutshell: the product of two bases is 2 only if they have the same size (A\<-\>G or C\<-\>T).

# Answer
> 3 votes
# Jelly,  ~~8~~  6 bytes

-2 bytes since we may take input mapped from `actg` to arbitrary numbers.

```
^«9‘İP

```

A dyadic Link accepting two lists of integers, `a:4 c:9 t:10 g:7` which yields the probability.

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

### How?

```
^«9‘İP - Link: a, b               e.g.  [4, 9,10, 7], [4, 4, 4, 4]
^      - bitwise XOR (vectorises)       [0,13,14, 3]
  9    - nine                           9
 «     - minimum                        [0, 9, 9, 3]
   ‘   - increment                      [1,10,10, 4]
    İ  - inverse                        [1, 0.1, 0.25, 0.1]
     P - product                        0.0025

```

# Answer
> 2 votes
# Vyxal, ~~10~~ 7 bytes

```
꘍9v∵›ĖΠ

```

Try it Online!

*-3 by porting Jonathan Allan's Jelly answer*

## Explained

```
꘍9v∵›ĖΠ
꘍         # Bitwise XOR of the two input lists
 9v∵      # vectorise(min, ^, 9)
    ›     # ^ + 1 (vectorises)
     Ė    # 1 / ^ (vectorises)
      Π   # product(^)

```

# Answer
> 2 votes
## DESMOS, <sup>~~125~~</sup> 109 bytes

$$f(k,l)=\prod\_{n=1}^{\operatorname{length}\left(k\right)}\left\\{k-l=0,\left|k-l\right|=2:.25,.1\right\\}\left\[n\right\]$$

```
\prod_{n=1}^{\operatorname{length}\left(k\right)}\left\{k-l=0,\left|k-l\right|=2:.25,.1\right\}\left[n\right]

```

try it online:
https://www.desmos.com/calculator/6nxdztewy3

Explanation:
\\$\prod\_{n=1}^{\operatorname{length}\left(k\right)}{}\left\[n\right\]\\$  `takes the product of the list starting with n=1`
\\$k-l=0\\$ `if k-l = 0 returns 1`
\\$\left|k-l\right|=2:.25,.1\\$ `else if abs(k-l) = 2 returns 0.25 else return 0.1`

# Answer
> 1 votes
# Perl 5, 81 bytes

```
sub{$i="@_";$r=1;$_=ord($1^$3),$r/=10-/0/*9-/3|6/*6while$i=~s/(.)(.* )(.)/$2/;$r}

```

Try it online!

# Answer
> 1 votes
# Scala, ~~52~~ 51 bytes

```
_.lazyZip(_).map(_.^(_)*7%8/3*7/4*3+1)./:(1.0)(_/_)

```

Try it online!

Uses `0123` for `actg`. Like many of the other answers, it xors the values and then hashes them to get the right probabilities.

Here is a table for the XOR, borrowed from Kevin Cruijssen's answer (modified for `actg` instead of `acgt`).

| Character pair | values | XOR |
| --- | --- | --- |
| aa | 0,0 | 0 |
| cc | 1,1 | 0 |
| gg | 2,2 | 0 |
| tt | 3,3 | 0 |
| ac | 0,1 | 1 |
| at | 0,2 | 2 |
| ag | 0,3 | 3 |
| ct | 1,2 | 3 |
| cg | 1,3 | 2 |
| gt | 3,2 | 1 |

Basically, we get 0 when there isn't a mutation, 1 or 2 for purine -\> pyrimidine or vice versa, or 3 for purine -\> purine or pyrimidine -\> pyrimidine. The goal is to get 0 to 1, 1 and 2 to 10, and 3 to 4, and then later reduce by dividing these inverses of the probabilities.

| Original value | `*7` | `%8` | `/3` | `*7` | `/4` | `*3` | `+1` |
| --- | --- | --- | --- | --- | --- | --- | --- |
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
| 1 | 7 | 7 | 2 | 14 | 3 | 9 | 10 |
| 2 | 14 | 6 | 2 | 14 | 3 | 9 | 10 |
| 3 | 21 | 5 | 1 | 7 | 1 | 3 | 4 |

# Answer
> 1 votes
# Retina, ~~124~~ 72 bytes

```
O$`.
$.%`
¶

L`..
A`(.)\1
%O`.
ag|ct
4
..
10
%`$
$*
¶

~`.+
.+¶1/$$.($&_

```

Try it online! Takes input on separate lines but link includes test suite that converts from comma-separated inputs for convenience. Outputs as a fraction `1/n`. Explanation:

```
O$`.
$.%`
¶

L`..

```

Transpose the inputs.

```
A`(.)\1
%O`.
ag|ct
4
..
10

```

Get the probability of each mutation.

```
%`$
$*
¶

~`.+
.+¶1/$$.($&_

```

Take the product and prefix `1/` to the result.

Previous 124-byte solution used decimal output:

```
O$`.
$.%`
¶

L`..
%O`.
(.)\1
1/1
ag|ct
25/100
[a-z].
1/10
+`\d+(.+)¶(\d+)/1
$.(*$2*)$1
{`/1$

^\B
0
(.)(\.(\d+))?/10
.$1$3/1

```

Try it online! Takes input on separate lines but link includes test suite that converts from comma-separated inputs for convenience. Explanation:

```
O$`.
$.%`
¶

L`..

```

Transpose the inputs.

```
%O`.
(.)\1
1/1
ag|ct
25/100
[a-z].
1/10

```

Get the probability of each mutation.

```
+`\d+(.+)¶(\d+)/1
$.(*$2*)$1

```

Multiply all of the probabilities together.

```
{`/1$

^\B
0
(.)(\.(\d+))?/10
.$1$3/1

```

Convert the fraction to a decimal.

# Answer
> 1 votes
# Charcoal, 23 bytes

```
Ｉ∕¹ΠＥＥθ⁻℅ι℅§ηκ∨¬ι⎇﹪ι⁶χ⁴

```

Try it online! Link is to verbose version of code. Takes the RNA translations as input, so expects characters from the set `acgu`. Works with both lower and upper case but not mixed case. Explanation:

```
      θ                 First input
     Ｅ                  Map over characters
         ι              Current character
        ℅               Ordinal
            η           Second input
           §            Character at index
             κ          Current index
          ℅             Ordinal
       ⁻                Subtract
    Ｅ                   Map over ordinal differences
                ι       Current difference
               ¬        Is zero
              ∨         Logical Or
                   ι    Current difference
                  ﹪     Modulo
                    ⁶   Literal `6`
                 ⎇      If nonzero then
                     χ  Predefined variable `10`
                      ⁴ Else literal `4`
   Π                    Take the product
  ¹                     Literal `1`
 ∕                      Divide
Ｉ                       Cast to string
                        Implicitly print

```

# Answer
> 1 votes
# PHP, 78 bytes

Accepts input as arrays of integers `[0,1,2,3]`, where `a->0, c->1, g->2, t->3`

```
function($o,$p){$s=1;foreach($o as$k=>$v){$s/='104'[$p[$k]^$v]?:10;}return$s;}

```

Try it online!

**Explanation**

```
function($o, $p) {        // function accepting two arrays of integers
  $s=1;                   // initial probability
  foreach($o as $k=>$v) { // loop through first input as key, value pairs
    $s /=                 // divide by... and assign result to $s
    '104'                 // string of possible division integers
                          // 1 => no change in probability
                          // 0 => special case
                          // 4 => inverse of 0.25
    [$p[$k] ^ $v]         // take an integer from string offset based on XOR value
                          // of loop's 'value' and corresponding value in second input
    ?:10;                 // evaluate boolean value of integer and return it when "truthy"
                          // else return 10 (inverse of 0.1) when "falsy"
                          // 1) integer is 0 (special case)
                          // 2) integer is undefined (XOR was 3, string offset doesn't exist)
  }
  return $s;              // return probability
}

```

# Answer
> 1 votes
# Haskell, 53 bytes

```
a?b|a==b=1|a/b<0=10|1>0=4
a!b=foldl1(/)$zipWith(?)a b

```

Try it online!

* input : `a`-\> 1, `g`-\> 2, `c`-\> -1, `t` -\> -2
* `?` compares bases to get the inverse of probabilities
* `!` zips sequences using ? to compare each pair and folds by dividing

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


title: Spot the different

text:
# Question
Title: Spot the different
# Introduction

This challenge was originally the "Among Us" challenge in the "Misc" category of YASCON CTF 2020. (The link includes an answer to that challenge. Click at your own risk.)

You're given a lot of files, 1 of which is different from every other files. Your job is to find that 1 different file.

# Challenge

* Input: the file names of all the files to be searched through.
* Output: the name of the 1 different file.

It is guaranteed to have at least 3 files, exactly 1 of which is different file.

This is a . Least bytes wins.

# Example Input and Output

Input:

> 1.txt 2.jpg 3.png 4.mp3

Output:

(`3.png` is different)

> 3.png

# Answer
> 1 votes
# JavaScript (SpiderMonkey), 71 bytes

```
x=>x.find(u=>!x.filter(v=>(R=n=>[...read(n,'binary')]+'')(u)==R(v))[1])

```

Try it online!

---

66 bytes

```
x=>x.find(u=>!x.filter(v=>(R=n=>read(n,'binary')+'')(u)==R(v))[1])

```

works on my computer. But I cannot make it run on TIO. Maybe due to the version of SpiderMonkey.

---
Tags: code-golf
---


# Question
Title: Generating minimal regular expression character classes
# Background

**Character classes** are a standard way to indicate a set of characters to match in regular expressions. For example, the class `[ab]` matches a or b, `[a-z]` matches any lower case letter, and `[^a]` matches everything but a. For the purpose of this question, classes can contain:

* a sequence of characters to match, where the characters `\`, `]`, `-` and `^` must normally be escaped with a `\`.
* a range of characters to match, indicated by separating two characters with a `-`: e.g. `[0-9]`. Note that if `-` is the first or last character in a class then it need not be escaped, as it's not indicating a range.
* a combination of sequences and ranges: e.g. `[ac-fhk-o]`. Note that the class cannot be empty, and if `]` is the first character in the class then it need not be escaped.
* a complement match indicated by the first character in the class being `^`: e.g. `[^a-z]`. Note that if `^` is not the first character in the class, then it need not be escaped.

# Task

Given a non-empty string made up of printable ASCII characters (" " to "~" = 0x20-0x7E), output the *shortest* character class that matches precisely those characters. The string may contain duplicate characters. Default Input/Output methods apply.

# Scoring

This is , so shortest code in bytes wins, with all the standard loopholes forbidden.

# Test cases

```
"the"     => "[the]" or "[eht]" etc
"faced"   => "[ac-f]" or "[c-fa]"
"0-121"   => "[-0-2]" or "[012-]" etc
"]"       => "[]]"
"[-^]"    => "[][^-]" or "[]^[-]"
"[\]"     => "[[-\]]" or "[]\\[]" or "[][\\]"

```

# Answer
No answers after a few days, so thought I'd have a go. Found it trickier than expected, so the answer's pretty long, but I'm reasonably confident it works. Should be able to trim it a fair bit more.

# Python 3.8, ~~431~~ ~~405~~ 410 bytes

```
import re,itertools as I
B,M,C,P="\-]^"
s=sorted;x=s({*input()})
d=[ord(x)-i for i,x in enumerate(x)];l=[];i=0
for _,g in I.groupby(d):n=len([*g]);l+=[[x[i]+M+x[i+n-1]],x[i:i+n]][n<4];i+=n
o="".join(s(l,key=lambda i:2*(M in i[::2])+(P in i)-3*(i[0]==M<C not in x)-2*(C in i)))
print("["+re.sub(".",lambda m:B*((x:=m.group())==B or x==P==o[0]or x==M<M*2==o[(i:=m.start()):i+2]in o[1:-1]or x==C in o[1:])+x,o)+C)

```

Try it online!

# Explanation

The overall approach is to:

1. Split the letters into ranges of length at least 4 and individual characters. Note that ranges of length 3 are never necessary (eg. `"[abc]"` is the same length as `"[a-c]"` and `"[]\\[]"` is the same length `"[[-\]]"`) and are sometimes worse (e.g. `"]-./"` is shorter as `"[]./-]"` than as `"[]\--/]"` or `"[--/\]]"`).
2. Sort the letters and ranges, so `"]"` goes first, otherwise `"-"` goes first, otherwise `"-"` goes last, and with `"^"` as late as posssible. There is no conflict between putting `"]"` first and `"-"` last since `"]--"` is not a valid range.
3. Escape as necessary: `\` always, `]` unless it's first, `^` if it's first, and `-` if it's in the middle (which will only happen if it's the beginning of a range).

# Extra test cases

```
"-^"      => "[-^]"
"-4]"     => "[]4-]"
"abcde^"  => "[a-e^]"
"XYZ[\\]" => "[X-\]]"
"-./0]"   => "[]\--0]"
"+*,-^"   => "[\^*--]"
"^_`a"    => "[\^-a]"

```
> 6 votes

---
Tags: code-golf, string, regular-expression
---


title: Output the text "Code Bowling"

text:
# Question
Title: Output the text "Code Bowling"
# Code-Bowling

You've been hired by Brunswick Bowling to create a simple program to output the text `Code Bowling` on their monitors. This company is worth a pretty penny and you feel you can swindle them for quite the *bit* of cash.

The job description clearly states that they pay on a scoring basis and you're pretty confident you can manipulate their scoring system to your advantage and get the largest pay check possible from these guys. To do so will require you packing as much *code* as you can into your program/function, even though their scoring system is designed to prevent you from doing so.

Get out your piggy banks, let's code!

---

# Challenge

The challenge is to simply output the text `Code Bowling`, exactly as it is written here, with the highest score possible. *(See section: **Scoring System** below)*

Leading and trailing new-lines (line-breaks) are acceptable.

Your code may be an entire program or just an executable function.

---

# Rules

*Obligatory: This challenge is using Code-Bowling: Common Rules, Revision 1.0.0; See Meta for details.*

1. **Character : Byte Ratio**
In Code-Bowling a character-count is preferred over a byte-count. The obvious reasoning for this is that multi-byte unicode characters (e.g. ) can be used in place of single-byte unicode characters to fluff up byte count and will make bowling more about who renames the most variables with high-byte unicode characters rather than who most strategically creates meaningful complex code.
2. **Variable/Function/Object Names**
All variable names (or object pointers, function names, etc) should be 1 character long. The only acceptable time to use 2-character variables names is after all possible 1-character variables have been used. The only acceptable time to use 3-character variables names is after all possible 2-character variables have been used. Etc.
3. **Un-used Code**
All code must be used. Meaning the program must fail to always properly complete the task if any individual character (or varying set(s) of characters) is/are removed. Naturally, a subset of the program should not be able complete the task on its own without the rest of the program.
4. **Comments**
Comments are not permitted towards character-count, unless somehow utilized by your program/function.

---

# Scoring System:

### Pangram Challenge:

A pangram is a sentence that uses every letter at least once. (The quick brown fox jumps over the lazy dog).

This challenge-type has a scoring systems designed where a perfect pangram would achieve the theoretical maximum score *(though you are not **required** to use every character at least once.)* Additionally, using any character more than once will start incurring a penalty. This challenge also expands to more than just the alphabetical characters.

### Scoring Metric:

> 1. Each character used increases your score by 1.
> 2. Repeated use of any alphanumeric character (a-z, A-Z, 0-9) will result in a deduction of 3 points per repeat (first use does not result in a deduction).
> 3. Repeated use of basic punctuation `([!?.-,":';])` \- including the brackets - will result in a deduction of 2 points per repeat.
> 4. Repeated use of other ASCII characters `{`~@#$%^&*_+=|\/><}` \- including the curly brackets - will result in a deduction of 4 points per repeat.
> 5. Use of spaces, tabs, and newlines will result in a deduction of 1 point per use. That is, they do not count towards character total.
> 6. Characters not mentioned above *(Exotic Characters)* will result in a deduction of 1 point per use. That is, they do not count towards character total.

### Scoring Tool:

An **automated** scoring widget has been created and can be found **here**.

---

This is a variant. The program with the highest score wins! (Since there is a maximum score of `94`, whoever reaches it first (if it can be reached) will be marked as the accepted answer, though others are free to keep answering for fun)

# Answer
> 39 votes
## Glypho, 94

The source file is encoded in CP437.

```
␀␀!"☺☺#$☻♥♥☻♦♣♦♣%♠♠&•◘•◘'○○(◙♂◙♂♀♪♪♀♫☼♫☼►◄◄►↕↕)*‼¶¶‼§§+,▬↨↨▬↑↓↑↓→←→←∟∟-.↔▲▲↔/▼▼▼⌂Ç⌂Çüééüââ01ää23àååàçêçê4ëë5èïèïîî67ìÄÄì8ÅÅ9ÉÉ:;æÆÆæô<=ôöòòöûùûù>ÿÿÿÖÖ?@ÜÜAB¢££¢¥₧¥₧CƒƒDáíáíóóEFúññúÑªÑªGººHI¿¿J⌐¬⌐¬K½½½¼¼LM¡««¡N»»»░░OP▒▒QR▓││▓┤╡┤╡S╢╢T╖╕╖╕U╣╣V║╗║╗╝╜╜╝W╛╛╛┐X┐┐Y└└└┴┬┴┬├─├─Z┼┼┼╞╞[\╟╟]^╚╔╔╚╩╦╩╦_╠╠`═╬═╬╧╨╨╧╤╥╥╤a╙╙╙╘╘bc╒╒de╓╓fg╫╪╪╫┘┌┌┘█▄█▄▌hi▌▐j▐▐▀αα▀ßΓßΓπΣπΣkσσσµlµµτmnτΦΘΘΦΩδΩδo∞∞∞φpφφεεqr∩≡≡∩±±st≥≤≤≥u⌠⌠⌠⌡⌡vw÷xy÷≈°°≈∙∙z{·|}·√ⁿⁿ√~²²²

```

Try it online!

### Explanation

Glypho is quite useful for challenges like this because it doesn't care about the actual characters being used at all. Instead it looks at each chunk of 4 characters and the command being used is determined by the pattern these four characters make:

```
0000 n
0001 i
0010 >
0011 \
0012 1
0100 <
0101 d
0102 [
0110 +
0111 o
0112 *
0120 -
0121 ]
0122 !
0123 e

```

That means we can just solve the problem and then fill in unique characters in each quartet with the printable characters and all the repeated ones with some of the "exotic" characters, which are ignored by the scoring. Glypho is sufficiently verbose that a normal handwritten solution contains enough unique characters to fit all the 94 printable ones inside. In fact, I ended up golfing it down until it had exactly 94, just so that I could use unique exotic characters for the repeated ones (hopefully, to make it harder to reduce the program).

The shorthand form of the above program is this:

```
11+d*d*d+d+1+1+dd1+o
d+11+d*d1+*1+-+do
11+d*d1+d**do
1+o
11+d*d*d+o
<o
ddo
11+d*d++o
111++d-<+ddo
<-+do
<1+1+o
1-+1-+o

```

Where each line prints one of the characters.

I've used this Retina script to convert it to Glypho using `0123`. Afterwards, I've just filled in the characters in place of the digits.

In theory it might be possible to reduce this further, if someone managed to golf down the shorthand program and then managed to recombine the characters such that the right patterns show up, but I'm not sure how to prove or disprove that this is possible. If anyone manages to form a valid solution from a subset of my program, please let me know so I can delete the answer until it's fixed. Until then, I'll have to assume that this is valid.

# Answer
> 51 votes
# Python 3, ~~82~~ ~~87~~ 88

*Thanks to @JonathanAllan for +1 score*

```
print("g!#$%&'*n+,./012i34579;<l=>?@ADEwFGHIJKLoMNOPQRSBTUVWXYZ ^_`abchejkmqsuvdyz{|}~ \x6f       C"[::-8])

```

Try it online!

Nothing special, just slicing and skipping characters. The string is reversed so you can't remove characters and have the original string being printed.

# Answer
> 20 votes
# \>\<\>, ~~92~~ 94

**YAY, I DID IT!**

is the *exotic* character `\x11` with decimal value 17. The program exits with an error after printing the result (it's a stack underflow). I had to manage which mirrors and directional commands I used carefully, since I can only use each one once.

```
   >"vCoUV␑3`h]Z_X
       /a[f+
#$%&'r(!
.0456~8?
:;<=@9l)
ABDEFcGe
HIJKL*
MNOPQ7
RSTWYd
bgijk1
mnqst-
uwxyz2
{|}  ,
     \p^

```

**Try it online**

**The core program:**

```
   >"vCoUV␑3`h]Z_X
       /a[f+
     r !
     ~ ?
     9 )
     c e
     *
     7
     d
     1
     -
     2
     ,
     \p^
```

**Explanation:**

Push the string `vCoUV␑3`h]Z_X >` (execution wraps). Move downward. Reverse the stack and remove the `v`.

Push `9` and `c` (12). Multiply to get `108` (`l`). Push `7`. Push `d` (13), subtract `1`, divide by `2` to get `6`. Put `l` at (x,y) of (13,6), which is below the `e`. I could've done this way shorter, but this is lengthened so I have room to put more ASCII characters.

Move up into a loop. Push length of stack with `l`. If greater than 14, output character, otherwise create a new stack with top 10 elements, add 15 then reflect execution right then up and output. This is used to prevent the extra spaces and `>` from being printed at the end, as well as turning the random-looking string into what needs to be printed. Continue looping.

If any of the lines is shorter (by removing a character), the program will no longer work, either because the vertical parts of the program no longer line up, or because the string to print isn't correct anymore. Attempting to remove a character from in front of each line will change the stack depth and where the `l` is placed, also causing problems.

Fish

# Answer
> 16 votes
# Octave, ~~20~~ ~~21~~ ~~22~~ ~~25~~ ~~27~~ 33

The best I've managed this far is

```
g=@()disp(horzcat([67 9583 -412],'e B',"nvkhmf"+!0));

```

This creates an anonymous function `f` that takes no input. You can call it `f()`. I'd say the semicolon at the end is necessary, in order to avoid printing of the function body.

It is possible this can be improved by combining `eval` and `printf`, but I've tried and failed over and over.

This uses all digits once, by exploting the fact that Octave does a `mod(x,256)` operation when implicitly converting numbers to characters. This means that we can use negative numbers, as well as numbers outside the normal `32-126`-range. The following numbers all result in the letter `i` when converted to characters: `... -2455 -2199 -1943 ... 105 361 ...`. Instead of using `'owling'` in the end, we use `"nvkhmf"` and add 1. This creates a vector of integers that are implicitly converted to characters. Instead of `1`, we use `!0` (or `not(false)`. Also, we use `"` instead of `'` to avoid two penalty points.

We need to find the set of numbers that gives the lowest score. The string `Code Bowling` result in the following matrix, when we subtract and add -10\*256 - 10\*256.

```
  -2493  -2449  -2460  -2459  -2528  -2494  -2449  -2441  -2452  -2455  -2450  -2457
  -2237  -2193  -2204  -2203  -2272  -2238  -2193  -2185  -2196  -2199  -2194  -2201
  -1981  -1937  -1948  -1947  -2016  -1982  -1937  -1929  -1940  -1943  -1938  -1945
  -1725  -1681  -1692  -1691  -1760  -1726  -1681  -1673  -1684  -1687  -1682  -1689
  -1469  -1425  -1436  -1435  -1504  -1470  -1425  -1417  -1428  -1431  -1426  -1433
  -1213  -1169  -1180  -1179  -1248  -1214  -1169  -1161  -1172  -1175  -1170  -1177
   -957   -913   -924   -923   -992   -958   -913   -905   -916   -919   -914   -921
   -701   -657   -668   -667   -736   -702   -657   -649   -660   -663   -658   -665
   -445   -401   -412   -411   -480   -446   -401   -393   -404   -407   -402   -409
   -189   -145   -156   -155   -224   -190   -145   -137   -148   -151   -146   -153
     67    111    100    101     32     66    111    119    108    105    110    103
    323    367    356    357    288    322    367    375    364    361    366    359
    579    623    612    613    544    578    623    631    620    617    622    615
    835    879    868    869    800    834    879    887    876    873    878    871
   1091   1135   1124   1125   1056   1090   1135   1143   1132   1129   1134   1127
   1347   1391   1380   1381   1312   1346   1391   1399   1388   1385   1390   1383
   1603   1647   1636   1637   1568   1602   1647   1655   1644   1641   1646   1639
   1859   1903   1892   1893   1824   1858   1903   1911   1900   1897   1902   1895
   2115   2159   2148   2149   2080   2114   2159   2167   2156   2153   2158   2151
   2371   2415   2404   2405   2336   2370   2415   2423   2412   2409   2414   2407
   2627   2671   2660   2661   2592   2626   2671   2679   2668   2665   2670   2663

```

So, `['',2627 2415 2148 1893 -2528 66 -1169 -1161 2668 105 -146 103]` results in `ans = Code Bowling`. The challenge is then to find the set of numbers and characters that reduces the score the most. Using all digits is of course good, but duplicates are bad. Since all digits are used, and non are used twice, this is the best possible mix. Also, we get to use `-`, resulting in one point.

One could claim that it can be reduced to the line below (31 points), but then it would no longer be an *"executable function"*, and would therefore have a different functionality.

```
disp(horzcat([67 9583 -412],'e B',"nvkhmf"+!0))

```

# Answer
> 12 votes
## C, ~~27~~ 29

*+2 points thanks to @ceilingcat!*

```
f(){char q<:]="Code B\157wling";puts(q);%>

```

# Answer
> 12 votes
# QBasic, 34

This is unformatted code (yay for case-insensitivity). You can run it in QB64 or at archive.org (though note that the latter will format the code as you type it). I *think* I've managed to abide by all the rules.

```
CLS
PrINT "C
LOcatE 1, 2 : ? CHR$(957-846); "de Bowling

```

The `CLS` is necessary: without it, the `C` is not guaranteed to print at the top left corner of the screen, where it will line up with `ode Bowling`. The `LOcatE` is necessary: without it, `ode Bowling` will be printed on the line below `C`. I don't believe there is any subset of the program (except whitespace) that can be deleted and keep the same output.

# Answer
> 9 votes
# Haskell, score ~~21~~ ~~38~~ ~~46~~ ~~47~~ ~~21~~ 70

```
putStr$toEnum(length"!#%&'*+,-./012345789;<=>?@ADGHIJKLMNOPQRTUVWXYZ[]^_`abcfjkqsvyz{|}~"):"ode B\x6Fwling"

```

Try it online! The idea is to get the leading `C` by constructing a string of length 67 which contains all not otherwise used characters and converting the length of this string to a character. I started with `putStr$toEnum(length""):"ode B\x6Fwling"` (`'\x6F'` is hexadecimal for `'\111'` which yields `'o'`) and computed all printable ASCII characters not contained in the program:

```
!#%&'*+,-./012345789;<=>?@ACDGHIJKLMNOPQRTUVWXYZ[]^_`abcfjkqsvyz{|}~

```

Incidentally there remain exactly 67 printable ASCII characters which can put into the string, and `C` itself which cannot appear in the string because then the program would be reducible to just `putStr"Code B\x6Fwling"`.

---

**Previous solution:** (score 21)

```
f|x<-'C'=mapM putStr[(:)x"ode Bowling"]

```

Defines a function `f` which takes no input and prints the string. Try it online!

# Answer
> 8 votes
# JavaScript, 19

```
prompt('C\157de B\x6fwlin'+"g")

```

Not a very high score.

# Answer
> 8 votes
# Jelly, 94

```
“!#"$&('*)+-/,13.0456:79<;>=@B?ADFHJLNCPRTEVXZ\G^IKMQ`SWbY[]d_acfhjegliknmprotquvxwy{z}¹|³⁵⁷~°⁹⁻”O%2s8UḄỌ

```

**Try it online!**

105 unique characters, 11 exotics (`“¹³⁵⁷°⁹⁻”ḄỌ`).

### How?

Forms the string from 8-bit reversed ASCII where each bit is encoded using the LSB of the Unicode value of a character.

```
“...”O%2s8UḄỌ - Main link: no arguments
“...”         - the string enclosed            !  #  "  $  &  (  '  *  )  +  -  /  ,  1  3  .  0  4  5  6  :  7  9  <  ;  >  =  @  B  ?  A  D  F  H  J  L  N  C  P  R  T  E  V  X  Z  \  G  ^  I  K  M  Q  `  S  W  b  Y  [  ]   d  _  a  c   f   h   j   e   g   l   i   k   n   m   p   r   o   t   q   u   v   x   w   y   {   z   }   ¹   |   ³    ⁵    ⁷   ~   °    ⁹    ⁻
     O        - cast to ordinal (vectorises) [33,35,34,36,38,40,39,42,41,43,45,47,44,49,51,46,48,52,53,54,58,55,57,60,59,62,61,64,66,63,65,68,70,72,74,76,78,67,80,82,84,69,86,88,90,92,71,94,73,75,77,81,96,83,87,98,89,91,93,100,95,97,99,102,104,106,101,103,108,105,107,110,109,112,114,111,116,113,117,118,120,119,121,123,122,125,185,124,179,8309,8311,126,176,8313,8315]
      %2      - mod 2 (vectorises)           [ 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1,  0, 1, 1, 1,  0,  0,  0,  1,  1,  0,  1,  1,  0,  1,  0,  0,  1,  0,  1,  1,  0,  0,  1,  1,  1,  0,  1,  1,  0,  1,   1,   1,  0,  0,   1,   1]
        s8    - split into chunks of 8       [[1,1,0,0,0,0,1,0], [1,1,1,1,0,1,1,0], [0,0,1,0,0,1,1,0], [1,0,1,0,0,1,1,0], [0,0,0,0,0,1,0,0], [0,1,0,0,0,0,1,0], [1,1,1,1,0,1,1,0], [1,1,1,0,1,1,1,0], [0,0,1,1,0,1,1,0], [1,0,0,1,0,1,1,0], [0,1,1,1,0,1,1,0], [1,1,1,0,0,1,1]]
          U   - upend (vectorises)           [[0,1,0,0,0,0,1,1], [0,1,1,0,1,1,1,1], [0,1,1,0,0,1,0,0], [0,1,1,0,0,1,0,1], [0,0,1,0,0,0,0,0], [0,1,0,0,0,0,1,0], [0,1,1,0,1,1,1,1], [0,1,1,1,0,1,1,1], [0,1,1,0,1,1,0,0], [0,1,1,0,1,0,0,1], [0,1,1,0,1,1,1,0], [1,1,0,0,1,1,1]]
           Ḅ  - binary to int (vectorises)   [67, 111, 100, 101, 32, 66, 111, 119, 108, 105, 110, 103]
            Ọ - to character (vectorises)    ['C', 'o', 'd', 'e', ' ', 'B', 'o', 'w', 'l', 'i', 'n', 'g']
              - implicit print               Code Bowling

```

# Answer
> 6 votes
# Röda, 33

```
{["ode B\x6fwling"]|push chr(3*4+57-2).._}

```

Try it online!

I tried to follow all rules. It works by first pushing the string `ode Bowling!` to the stream and then inserting `C`=3\*4+57-2 to the front.

# Answer
> 6 votes
# C, 73

*Thanks to @Laikoni!*

```
F(){printf("Code B\157wli%cg",48+strlen("!#$&'*-../2369:<=>?@ADEGHIJKLMNOPQRSTUVWXYZ[]^_`abhjkmquvxyz|~"));}

```

Try it online!

# C,  ~~31~~   ~~33~~  35

```
F(){printf("Code B\157wli%cg",96|0xD+3*4/8);}

```

*Thanks to @ceilingcat and @DLosc for two more points and thanks to @Ørjan Johansen for another two more points!*

Try it online!

# Answer
> 6 votes
# Cardinal 20

23 non whitespace characters
%#\>/NI"CodeB8^o)wl,ing

-3 for repeated "o"

```
   I
 >\/N
%# "CodeB
 8^o
 ) w
   l
 , i
   n
   g

```

## Pointer paths:

**Step 1:**
Pointer created at % going right

**Step 2:**
Pointer splits at # to go up, right and down (P1,P2,P3)

**Step 3**:
P1 Sent right by \>
P2 Going right
P3 Set wait for 3 steps at 8

**Step 4:**
P1 Reflected down by \\. \ changed to /
P2 Set to print mode by "
P3 Wait for 2 ticks at 8

**Step 5:**
P1 Heading down
P2 Print C
P3 Wait for 1 tick at 8

**Step 6:**
P1 Sent up by ^
P2 Print o
P3 Finish wait at continue, pick up ASCII value of " " (32) from )

**Step 7:** P1 Heading up
P2 Print d
P3 Heading down

**Step 8:** P1 Reflected right by \ which was changed to /
P2 Print e
P3 Print character with ASCII value=32 from , operation

**Step 9:**
P1 Reflected up by / which is changed to \
P2 Print B
P3 Reached end of field and stops

**Step 10:**
P1 Reflected down by I
P2 Reached end of field and stops

**Step 11:**
P1 Reflected right by / which was changed to \\. Changes back to /

**Step 12:**
P1 Reflected left by N

**Step 13:**
P1 Reflected down by /

**Step 14:**
P1 Set to print mode by "

**Step 15:**
P1 Print o

**Step 16:**
P1 Print w

**Step 17:**
P1 Print l

**Step 18:**
P1 Print i

**Step 19:**
P1 Print n

**Step 20:**
P1 Print g

**Step 21:**
P1 Reaches end of field and stops.

Try it Online

# Answer
> 4 votes
# Brainfuck: -204

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

```

Well, awful score, but was fun to write.

* 122 characters long
* repeated alnum: -0 ()
* repeated punctuation: -134 (--\[---\].-----------..--\[---\]-.\[-\].-\[---\]..-----------.---..-------.)
* repeated other: -192 (+++++++\>+\>+\<\>++++\>+\<\>+\>++\<\>\>+\<\>+++++++++++++++++)
* whitespace characters: -0 ()
* exotic characters: -0 ()

# Answer
> 3 votes
# Java 8, ~~2~~ ~~3~~ ~~5~~ ~~13~~ ~~17~~ ~~18~~ ~~19~~ ~~20~~ ~~21~~ ~~24~~ ~~77~~ 78 points

+53 score (24 → 77) thanks to *@Laikoni*.

```
v->(char)"!#$%&'*,/0234689:;<=?@ADEFGHIJKLMNOPQRSTUVWXYZ[]^_`bfjkmpqsuxyz{|}~".length()+"\157de Bowling"

```

104 characters long
\- repeated alnum: -15 (`helng`)
\- repeated punctuation: -10 (`"()""`)
\- repeated other ASCII: none
\- whitespace characters: -1
SCORE: 78

Try it online.

---

Old **24 bytes** answer:

```
v->"C\157de Bowlin"+(char)103;

```

30 characters long
\- repeated alnum: -3 (`1`)
\- repeated punctuation: -2 (`"`)
\- repeated other ASCII: none
\- whitespace characters: -1
SCORE: 24

Try it online.

# Answer
> 3 votes
## Batch, 19 characters

```
@echO(Cod%TMP:~5,1% Bowling

```

Starting with Windows Vista, `TMP` begins with `C:\Users\` and therefore `%TMP:~5,1%` is a verbose way of writing `e`, despite requiring a double `%` at -4 penalty.

# Answer
> 3 votes
# 05AB1E, 94 points

```
”X1234bcde5fghijk68l9<mn>,o.p|q\/{})r(_-+s=tu*vwxyzAB&YDEFG^HI%$ZK#L@!MNO~PQR`ST':UVW[0];"”€a7ôJCç€?

```

Try it online!

---

```
- 100 characters long
- repeated alnum:       -0 ()
- repeated punctuation: -0 ()
- repeated other:       -0 ()
- whitespace characters:  -0 ()
- exotic characters:  -6 (””€ôç€)

Total score: 94

```

---

Basically converts (The Binary ASCII of Code Bowling):

```
['1000011', '1101111', '1100100', '1100101', '0100000', '1000010', '1101111', '1110111', '1101100', '1101001', '1101110', '1100111']

```

Into a string of 1's and 0's, then it replaces each 1 with a letter in the alphabet, and each 0 with a space character or a symbol or a digit.

```
”X1234bcde5fghijk68l9<mn>,o.p|q\/{})r(_-+s=tu*vwxyzAB&YDEFG^HI%$ZK#L@!MNO~PQR`ST':UVW[0];"”

```

Is the string, where 1's are letters and 0's are symbols, numbers or anything else. We then iterate through, seeing which are alphabetical, pushing 1 for alphabetical 0 for nonalphabetical. We then split into groups of 7, convert back to ASCII and print each character.

# Answer
> 3 votes
# ;#, score -1163

I don't think this would be much competition even if it could compete.

```
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#

```

Try it online! Note: TIO has no ;# interpreter, only ;#+.

# Answer
> 2 votes
# Perl: 29, 33

```
$_=OWLING;printf%s,"C\157de".chr(30+8/4).B.lc

```

**Score:**

```
- 46 characters long
- repeated alnum:       -6 (rc)
- repeated punctuation: -6 ("..)
- repeated other:       -0 ()
- whitespace characters:  -1 (
)
- exotic characters:  -0 ()

Total score: 33

```

# Answer
> 2 votes
# stacked, 42

```
(67:43,1 ab)2 9*pf sum 8/0\|>+chr'de Bowling',EPS#`

```

Try it online!

Leaves output on stack. Here's the breakdown:

```
length: 51
repeated alnum:        -0 ()
repeated punct:        -4 (',)
repeated other:        -0 ()
whitespace characters: -5 (     )
exotic characters:     -0 ()
total score: 42

```

I could probably make it higher, but it's at 42 soo....

Another contender, 40:

```
(67:43,sum)9 pf 2%MIN 0\|>+chr'de Bowling',EPS#`

```

---

I used this script for scoring it.

# Answer
> 2 votes
# CJam, score 93

```
"g!#$&'()n*+/0134i5689:;<l=>?@ADEwFGHIJKLoMNOPQRSBTUVWXYZ [\]^_`aebcfhjkmdqrstuvxpyz{|}  C"7~%2,.-

```

Try it online

Inspired from TidB's Python answer.
Not sure if there's any way to avoid the repetition of the double quotes.

**Explanation:**

The string contains "Cpde Bowling" in reverse, every 8th character.
`7~%` extracts "Cpde Bowling" (`7~` = `-8`)
`2,.-` decrements the p character (`2,` = `[0 1]`)

# Answer
> 2 votes
# evil, -81

Better than Brainfuck!

```
aeeaeuwkaaeeuwygaeaeclaaxjlwalusbdgueuewguwpweewpuuuwuuuwpuweew

```

## Explanation

```
aeeaeuw //Write 'C'
k       //Set P[0] to 'C'
aaeeuw  //Write 'O'
y       //Set W[0] to 'O'
gaeae   //Set Accumulator to 'D'
claa    //Create new Wheel cell at index 0, swap with Accumulator, add 2
xj      //Set alternate marker mode and drop marker
lwa     //Write value of W[0], add 1
lu      //Put it back, subtract 1 from Accumulator
sb      //Go to 'j' if Accumulator != 0
d       //Delete W[0]
        //The above loop writes 'D' and 'E'
gueuew  //Write ' '
guw     //Write 'B'
pw      //Write 'o'
eew     //Write 'w'
puuuw   //Write 'l'
uuuw    //Write 'i'
puw     //Write 'n'
eew     //Write 'g'

```

Submitted because nobody does anything in evil but it's kind of fun.

## Score:

Length = 63

```
a*8  = -24
e*12 = -36
g*2  = -6
l*2  = -6
p*2  = -6
u*12  = -36
w*10  = -30

```

Try it online!

EDIT: TiO seems to incorrectly handle creation and deletion of new Wheel cells - I've filed a bug report on the subject. It won't work properly on there, but I ran it on my own interpreter and it works and you can trust me so I wouldn't worry about it ;)

# Answer
> 2 votes
# T-SQL, ~~65~~ ~~18~~ 32! points

```
PRINT char(78-9605*43%12) + 'ode Bowling'

```

Inspired by a trick in Dlosc's QBasic answer, I found a way to include all 10 digits and most of the mathematical operators (`%` is remainder/modulo, missing only `/`), mostly via trial and error . I don't *think* there is any way to get a 67 by removing any combination of digits/symbols, but you're welcome to try.

**Version 2 (18 points, trivial):**

```
DECLARE @ char(12)='Code Bowling'PRINT @

```

Not a great score, but this is what my first version simplified to (thanks, MickyT). Everything else I tried (encoding and decoding hex64, picking individual elements out of a string, converting ASCII values, etc) all had too many repeated characters (especially `ECR` and symbols `(),@`) that drive it into the negative.

**Version 1 (65 points, invalid):**

```
DECLARE @ char(123)=
'Code Bowling FGHJKMOQSUVWXYZbjkmpqsuvxyz045789 [!?.-":;]{`~#$%^&*_+|\><}'
PRINT left(@,LEN(@)/6)

```

I used the length of the string to determine how many characters I use from the left side, so removing any *single* character from the string will drop the integer division result down to 11, outputting only `Code Bowlin`.

# Answer
> 2 votes
# Whitespace, score: 0

```
[S S T  T   N
_Push_-1_g][S S S T T   S N
Push_6_n][S S S T   N
Push_1_i][S S S T   S S N
_Push_4_l][S S S T  T   T   T   N
_Push_15_w][S S S T T   T   N
Push_7_o][S S T T   S S T   T   S N
_Push_-38_B][S S T  T   S S T   S S S N
_Push_-71_space][S S T  T   T   N
_Push_-3_e][S S T   T   S S N
_Push_-4_d][S S S T T   T   N
Push_7_o][S S T T   S S T   S T N
_Push_-37_C][N
S S N
_Create_Label_LOOP][S S S T T   S T S S S N
_Push_constant_104][T   S S S _Add_top_two][T   N
S S _Print_as_character][N
S N
N
_Jump_to_Label_LOOP]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

Uses this Whitespace tip of mine to print the output. The optimal constant `104` is generated by this Java program. Since all the characters (except for the `o`) are unique, I couldn't use any duplicates or copies to save bytes (copy the value of `o` would be 1 byte longer than pushing the value of `o` again).

**Score:** 117 characters long - 117 whitespace characters = 0
Still better than some of the negative scoring answers. ;)

# Answer
> 1 votes
# CJam, score 47

```
"'#?GyQ2wE(s6&␟JI!gF$u*Aq;0p4BvOKkHLhM"3/{:i~-z+c}%

```

Hopefully no problems with this...

Uses one exotic character (Unit Separator, ASCII 31, represented by ), and one repeated character (`"`). I think it could be made longer still, but I'll leave it as is for now.

Try it online!

The program works by taking that long string and splitting it into length-3 substrings. Each substring is then mapped to the block, which converts its characters to their ASCII values, dumps the values on the stack, takes the absolute difference of the second two, adds the result with the first, then converts the final result back to an ASCII character.

# Answer
> 1 votes
# PHP, 33 points

This was quite difficult to come up with.

The score may be inproved in the future.

```
<?echo IHASZODECG9F^"
'%6z\r+2/.W!";

```

The newline is assumed to be a Linux-style newline! Windows-style and Old-Mac-Style won't work properly.

# Answer
> 1 votes
# Ruby, 75

Approximately a port of the Python answer, but Ruby doesn't have that cool step function so I use `gsub` instead. Also I decided to have a little fun with the exotic characters by throwing phrases into Google Translate

Try it online!

```
print"Cachjkmq\x6fvyzADEFdGHIJKLMeNOPQRST UVWXYZ0B234589[o!?-:;]`w~@\#$%^&l*_+=|><i コードゴルフn 代碼保齡球 gκωδικός".gsub /(.).{7}/,'\1'

```

# Answer
> 1 votes
# USML, 12 or 9 points (non-competing)

```
"Code\tBowling'

```

Try it online!

This answer cheats a bit by abusing how HTML renders. The string actually created by this is `"Code\tBowling "`. Points are lost for repeating the "o" character.

For a non-cheatsy answer:

```
"Code Bowling

```

USML is still fairly early in development and is not yet capable of increasing the size of the program any further yet.

# Answer
> 1 votes
# Cubix, 85

```
Codeha1spqumtr;$"gnilwoB"Sv"ADEFH%IJK2f!OPUzQ0V3XY&*[-|L:]\T`~#x>MR56cGk'?W<()b4j}.{Z_^/978@

```

Try it online!

Cubified with insignificant characters replaced with .

```
        C o d e
        . . . .
        . . u .
        . . ; .
" g n i l w o B " S v " . . . .
. . . . . . . ! . . U . . . . .
. . . . . . . L . . \ . . . . .
> . R . . . . . . . W < . . . .
        . . . {
        . . ^ /
        . . . @
        . . . .

```

I think I have made the path fragile enough that removing characters will break it quite badly.

Watch it run

```
- 92 characters long
- repeated alnum:       -3 (o)
- repeated punctuation: -4 ("")
- repeated other:       -0 ()
- whitespace characters:  -0 ()
- exotic characters:  -0 ()

Total score: 85

```

# Answer
> 1 votes
# Zsh `--nocaseglob`, score 79

```
>' "%&+,.:<=@ADEGHJKMOQSUVWXYZ^_abfhjkmpqrtuvxyz~'>0
?()${(#)9}*/PRINTF Code\ Bowling;[!] 1 2 3 4 5 6 7 8 `ls|wc -L`

```

Try it online!

Previous version (score 84):

```
>\";?()/*/PRINTF %s g${9:8|#0}
rev <([!-+] A D E G H J K L '&,.=@^_`~1234567MOQSUVWXYZabcfhjkmpqtuxyz nilwoB edoC')

```

Try it online!

Unfortunately, this wasn't irreducible for a number of reasons. Here is the limit of reducibility:

```
>\";?()/*/PRINTF g$8
rev <([!] A D E G H J K 'nilwoB edoC')

```

Try it online!

# Answer
> 0 votes
# Acc!!, score -197

```
119
Write _-52
Write _-8
Count i while i-2 {
	Write _-19+i
}
32
Write _
_+34
Write _
_+45
Write _
_+8
Write _
_-11
Write _
Count i while i-2 {
	Write 105+i*5
}
_-5
Write _

```

Try it online!

*Acc*!! works well for this challenge as whitespace is necessary and loops are costly. I made use of the *Acc*umulator here, but poorly, to increase chars. Here is a brief overview from the page:

> `Accumulator` Any expression standing by itself is evaluated and assigned to the accumulator (which is accessible as `_`). Thus, e.g., 3 is a statement that sets the accumulator to 3; _ + 1 increments the accumulator; and _ * N reads a character and multiplies the accumulator by its charcode. (N gets input)
>
> `Write <charcode>` Outputs a single character with the given ASCII/Unicode value to stdout. The charcode can be any expression.

Loops in Acc, at least for golfing, are a pain. They require braces, and all whitespace is necessary. Otherwise it's pretty self-explanatory.

# Answer
> 0 votes
# Lenguage, 94

*Reduced by 450947698176028388843917607537842418986035722486451998047037459476165368967293205287214703816225093120721837128 bytes thanks to @ovs.*

```
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~                    ...238120765277364887435892673116228159402534303033563968545104627044479808894 spaces omitted...

```

This gets converted to the brainf\*** program `+[[-<+<+>>>]>+<<<<+]>>>>>>++++.<<+.<<--.+.>>>>>--.<-.<<.>++++.<---.---.+++++.<<++.` using the algorithm described here, which outputs `Code Bowling`. This gets the maximum score achievable for this challenge and at the same time is the longest program here!

---
Tags: string, restricted-source, code-bowling, pangram
---


title: N-dimensional pyramid numbers

text:
# Question
Title: N-dimensional pyramid numbers
Given two inputs, a number n and a dimension d, generate the nth d-dimensional pyramid number.

That was confusing, let me try again.

For d = 1, the numbers start 1,2,3,4,5 and is the number of points in a line n points long.

For d = 2, the numbers start 1,3,6,10,15 and is the number of points in a triangle with side length n, also known as the triangle numbers e.g.

```
     0
    0 0
   0 0 0
  0 0 0 0

```

For d=3, the numbers start 1,4,10,20,35 and is the number of points in a pyramid of side n. For d=4, it's a 4-d pyramid, and so on.

Beyond this, visualization gets a bit tricky so you will have to use the fact that the nth d-dimensional pyramid number is equal to the sum of the first n d-1-dimensional pyramid numbers.

For example, the number of dots in a 3-d pyramid of side 5 is the sum of the first 5 triangle numbers: 1+3+6+10+15 = 35.

You can expect reasonable input (within your languages boundaries), although Standard loopholes apply. No builtins explicitly for this purpose (looking at you, Mathematica)

Numbers are 1-indexed, unless you specify otherwise.

Example recursive code in Javascript:

```
function pyramid(dim,num){                          //declare function
  if(dim == 0){                                     //any 0-dimensional is a single point, so return 1
    return 1;
  } else {                                          //otherwise
    function numbersUpTo(x){                        //helper function to get the numbers up to x
      if(x==0){                                     //no numbers up to 0
        return [];
      } else {                                      //otherwise recurse
        return [x].concat(numbersUpTo(x-1));
      }
    }
    var upto = numbersUpTo(num).map(function(each){ //for each number up to num
      return pyramid(dim-1,each);                   //replace in array with pyramid(dimension - 1,the number)
    });
    return upto.reduce((a,b)=>a+b);                 //get sum of array
  }
}

```

This is code-golf, so fewest bytes wins.

# Answer
> 7 votes
# JavaScript (ES6), 24 bytes

Expects `(n)(d)`.

```
n=>g=d=>d?n++/d*g(d-1):1

```

Try it online!

# Answer
> 6 votes
# APL(Dyalog Unicode), ~~7~~ 6 bytes SBCS

```
⊢!1-⍨+

```

Try it on APLgolf!, Old version(8 bytes)

-1 from rak1507.

A train submission which takes `n` on the left and `d` on the right.

Uses the combination based formula mentioned in the question comments.

1-indexed.

## Explanation

```
⊢!1-⍨+
     + n + d
  1-⍨  - 1
 !     choose
⊢      d

```

# Answer
> 5 votes
# Jelly, 3 bytes

```
+’c

```

Try it online!

Accepts `n` as the first argument and `d` as the second argument. Uses the formula $$n+d-1 \choose d$$

## Explanation

```
+’c   Main dyadic link
+     Sum
 ’    Decrement
  c   Combinations with the right argument

```

# Jelly, 8 bytes

```
’çⱮSɗṛ’?

```

Try it online!

Accepts `d` as the first argument and `n` as the second argument. Uses the algorithm described in the challenge.

## Explanation

```
’çⱮSɗṛ’?   Main dyadic link
       ?   If
      ’    d-1 ≠ 0
    ɗ      then (
’            d-1
 ç           Apply this link
  Ɱ            with each [1..n] as the right argument
   S         Sum
    ɗ      )
     ṛ     else n

```

For some reason, this does not work with `ß` instead of `ç`. It would be nice if someone explained why.

# Answer
> 3 votes
# Whispers v2, ~~52~~ 49 bytes

```
> Input
> Input
>> 1+2
>> ≺3
>> 4C2
>> Output 5

```

Try it online!

Inputs the numbers from STDIN.

-3 bytes from Michael Chatiskatzi.

If floating point output is not allowed, then 63 bytes.

# Answer
> 3 votes
# , 6 bytes

```
[!<:@+

```

Try it online!

# Answer
> 2 votes
# Perl 5, 41 bytes

```
sub f{($n,$d)=@_;$d?$n/$d*f($n+1,$d-1):1}

```

Try it online! Influenced by Arnaulds javascript answer.

```
$D=$_,print"d=$D:   ".join(" ",map f($_,$D), 1..10)."\n" for 1..4;

d=1:   1 2 3 4 5 6 7 8 9 10
d=2:   1 3 6 10 15 21 28 36 45 55
d=3:   1 4 10 20 35 56 84 120 165 220
d=4:   1 5 15 35 70 126 210 330 495 715

```

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

```
Binomial[##-1,#]&

```

Try it online!

The boring answer. Input `[d, n]`.

---

### 29 bytes

```
Nest[Tr@*Array~Curry~2,1&,#]&

```

Try it online!

Input `[d][n]`.

Returns the `d`-pyramid function, constructed using the given recursive definition. Call it on `n` for the `n`th `d`-pyramid number.

# Answer
> 2 votes
# Haskell, 25 bytes

```
0#n=1
d#n=(d-1)#(n+1)*n/d

```

Try it online!

This was my old solution, same idea, but much longer, 37 bytes

```
a%b=product[a+1..b-1]
d#n=d%(n+d)/0%n

```

Try it online!

# Answer
> 1 votes
# Python 3, ~~56~~ ~~55~~ 51 bytes

Saved a byte thanks to Kevin Cruijssen!!!
Saved 4 bytes thanks to ovs!!!

```
f=lambda n,d:d<1or sum(f(i+1,d-1)for i in range(n))

```

Try it online!

# Answer
> 1 votes
# 05AB1E, ~~9~~ ~~7~~ 4 bytes

```
+<Ic

```

\\$a(n,d) = {n+d-1\choose d}\\$

The inputs are in the order \\$n,d\\$.

Try it online or verify some more test cases.

**Previous 7 bytes answers:**

```
L©<+®/P

```

The inputs are in the order \\$d,n\\$ and the output is a float.

Try it online or verify some more test cases.

*Equal-bytes alternative by porting* @Razetime*'s APL answer**:*

```
LIGηO}θ

```

The inputs are in the order \\$n,d\\$.

Try it online or verify some more test cases.

**Explanation:**

```
+        # Add the two (implicit) inputs together
 <       # Decrease it by 1
  I      # Push the second input `d`
   c     # Get the number of combinations / the binomial coefficient: `n+d-1` choose `d`
         # (after which it is output implicitly as result)

L        # Push a list in the range [1, first (implicit) input `d`]
 ©       # Store it in variable `®` (without popping)
  <      # Decrease each by 1 to make the range [0,`d`)
   +     # Add the second (implicit) input-integer `n` to each: [`n`,`n+1`,...,`n+d-1`]
    ®    # Push list [1,`d`] from variable `®` again
     /   # Divide the items at the same positions in the two lists:
         #  [`n/1`,`(n+1)/2`,...,`(n+d-1)/d`]
      P  # Take the product of this list
         # (after which it is output implicitly as result)

L        # Push a list in the range [1, first (implicit) input `n`]
 IG      # Loop the second input `d` - 1 amount of times:
   η     #  Get the prefixes of the current list
    O    #  And sum each prefix together
  }θ     # After the loop: pop and leave just the last item
         # (after which it is output implicitly as result)

```

# Answer
> 1 votes
# Julia, ~~26~~ 22 bytes

```
d>n=d<1||sum(~-d.>1:n)

```

Try it online!

# Answer
> 1 votes
# MathGolf, 8 bytes

```
r+k╒m╠ε*

```

First input \\$d\\$ as an integer, second input \\$n\\$ as a float.

Port of my 05AB1E answer.

Try it online.

**Explanation:**

```
r         # Push a list in the range [0, first (implicit) input `d`)
 +        # Add the second (implicit) input `n` to each: [`n`,`n+1`,...,`n+d-1`]
  k       # Push the first input `d` again
   ╒      # Pop and push a list in the range [1,`d`]
    m╠    # Divide the values at the same positions from one another:
          #  [`n/1`,`(n+1)/2`,...,`(n+d-1)/d`]
      ε*  # Take the product (reduce by multiplying)

```

# Answer
> 1 votes
# Haskell, 44 39 bytes

```
d#n=sum$iterate(scanl(+)0)[1..n]!!(d-1)

```

Try it online!

# Answer
> 1 votes
# , ~~33~~ 28 bytes

```
function(n,d)choose(n+d-1,d)

```

Try it online!

5 bytes saved by Dominic van Essen.

# Answer
> 1 votes
# Rust, ~~63~~ 58 bytes

```
|n,d|(n..=n+d-1).product::<u32>()/(1..=d).product::<u32>()

```

Try it online! (with calling code)

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

*-1 byte thanks to att!*

```
Last@Nest[Accumulate,1~Table~#,#2]&

```

Try it online!

Just to prove that Mathematica can do things without builtins! One nice thing about this function is that it calculates the pyramidal numbers exactly according to the definition, by summing (using `Accumulate`) over pyramidal numbers of one dimension less (hence recursively starting from the 0-dimensional pyramidal numbers, here generated as an array of `1`s of the correct length, using `1&~Array~#`).

# Answer
> 1 votes
# Python 3, 33 bytes

```
f=lambda n,d:d<1or n/d*f(n+1,d-1)

```

Try it online!

# Answer
> 0 votes
# Husk, 5 bytes

```
→!¡∫ḣ

```

Try it online!

Same idea as my APL answer. Takes n and k, both 1 indexed, as command line args.

# Answer
> 0 votes
# Charcoal, ~~18~~ 13 bytes

```
≔…¹ＮθＩ÷Π⁺ＮθΠθ

```

Try it online! Link is to verbose version of code. Explanation: Now inspired by @KevinCruijssen's 05AB1E answer.

```
≔…¹Ｎθ

```

Input `n` and generate an exclusive range from `1` to `n`.

```
Ｉ÷Π⁺ＮθΠθ

```

Input `d` and vectorised add it to the range, then divide the product of that range by the product of the original range.

# Answer
> 0 votes
# Java (JDK), 48 bytes

```
int f(int n,int d){return d<1?1:f(n+1,d-1)*n/d;}

```

Try it online!

# Answer
> 0 votes
# Groovy, 27 bytes

```
f={n,d->d?f(n+1,d-1)*n/d:1}

```

Try it online!

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


# Question
Title: Average an array until all numbers are (almost) equal
Given an array of numbers, find out how many iterations of averaging\* it takes for the average of every element to be no more than 1 higher or lower than the first element (absolute difference between the array's average and the first element is less than or equal to 1).

# \*Array averaging

To "average" a number in our array, we take the average of itself, the number behind it, and the number ahead of it. The last number of the array assumes the number ahead of it is the first number of the array (wrapping). **Do this for all but the first number of the array, it needs to stay constant.** The averages should all be applied at the same time (i.e. don't take the average of a number, put it back into the array, then average the next number).

# Example:

```
ITERATION 0: [-1,4,3.5,7]
          1: [-1, 2.1666666666666665, 4.833333333333333, 3.1666666666666665]
          2: [-1, 2.0, 3.388888888888889, 2.3333333333333335]
          3: [-1, 1.462962962962963, 2.5740740740740744, 1.5740740740740742]
          4: [-1, 1.0123456790123457, 1.8703703703703705, 1.049382716049383]
          5: [-1, 0.6275720164609054, 1.3106995884773662, 0.6399176954732511]
          6: [-1, 0.31275720164609055, 0.8593964334705076, 0.3168724279835391]
          7: [-1, 0.057384545038866065, 0.4963420210333791, 0.058756287151348875]
abs(AVERAGE - FIRST_ELEMENT) = 0.903120713306 (IS LESS THAN 1)
OUTPUT: 7

```

# Other I/O

```
INPUT >> OUTPUT
[-3, 9]  >>  2
[0, 0, 0, 0]  >>  0
[64, -66, -9, 78, -60]  >>  29
[9, 4, 5, 3, 3, 3, 10, 1, 1, 1]  >>  44
[-6, 5, -4, 3, -2, 1, -1, 2, -3, 4, -5, 6]  >>  70
[100000000, 2.11, 0.0, 16.88, 8.44, 6.33, 16.88, 100000000]  >>  348
[-8245, 6832, 9525, -3397, 5595, -9242, 1954, 6427, 36, -9647, -8887, 3062, -4424, -4806, -3803, 3608, -5115, -3725, -3308, -277]  >>  1038

```

**Though not a part of the challenge**; technically we are dealing with absolute values therefore complex numbers should also work. **Your program does NOT need to handle complex numbers.**:

```
[(20-1j), (5-4j), 7, (-0-100j)]  >>  15

```

# Notes:

* Other mathematical methods are accepted
* You are to assume there are at least two elements in the array
* This is so the shortest code in bytes wins

# Answer
> 6 votes
# Perl 6,  ~~83~~  82 bytes

```
->\a(\b,|c){(c,{[(b,|$_,b).rotor(3=>-2).map: *.sum/3]}...{(b+.sum)/a~~b-1..b+1})-1}

```

Try it

```
->\a(\b,|c){(c,{[(b,|$_,b).rotor(3=>-2).map: *.sum/3]}...{1>abs (b+.sum)/a -b})-1}

```

Try it (also works for complex numbers

## Expanded

```
->      # pointy block lambda

  \a    # the input array
  (
    \b, # the first value
    |c  # all the rest of the values
  )

{
  (
    # generate a sequence

    c,                 # initialize the sequence starting with the second value

    {                  # bare block lambda with implicit parameter ｢$_｣

      [                # turn the result from a Seq into an array

        ( b, |$_, b )  # re-add the first element
                       # and add it to the end

        .rotor(3=>-2)  # grab 3 at a time, backing up 2

        .map: *.sum/3  # return the average for each sub sequence

      ]
    }

    ...                # keep calling that to generate values until

    {
      1 > abs ( b + .sum )/a - b     # they are almost equal
    }

  ) - 1 # count them and reduce by one (ignore initial value)
}

```

# Answer
> 4 votes
# , ~~107~~ ~~101~~ ~~98~~ 95 bytes

*Edit: -6 bytes thanks to Giuseppe (who has now outgolfed this with his own shorter answer)*

```
function(x){while(abs(mean(x)-x)>1){for(j in seq(y<-x)[-1])x[j]=mean(c(y,y)[j+-1:1]);F=F+1};+F}

```

Try it online!

# Answer
> 3 votes
# Jelly, 30 bytes

```
L‘ṁ@µ+3\÷3;@Ḣ
ÇµS÷L_1ị$Ị¬µÐ¿L’

```

A monadic link taking the list and returning the number of iterations required.

Test suite at **Try it online!**

### How?

```
L‘ṁ@µ+3\÷3;@Ḣ - Link 1, perform an iteration: list x
L             - length of x
 ‘            - incremented
  ṁ@          - mould with swapped @rguments (i.e.. [a,b,c,...] -> [a,b,c,...,a])
    µ         - monadic chain separation (call that v)
      3\      - three-wise reduce v with:
     +        -    addition (sum up the overlapping slices of 3)
        ÷3    - divide those by three (get the averages)
            Ḣ - head v (get the first element)
          ;@  - concatenate with swapped @rguments

ÇµS÷L_1ị$Ị¬µÐ¿L’ - Main link: list a
 µ         µÐ¿   - collect results while loop
Ç                -   body: call last link as a monad
                 -   condition:
  S              -     sum
    L            -     length
   ÷             -     divide (average)
        $        -     last two links as a monad:
      1          -       literal one
       ị         -       index into (the first element)
     _           -     subtract
         Ị       -     insignificant (absolute value is less than or equal to 1)
          ¬      -     not
              L  - length (count the results)
               ’ - decrement (the first result is number zero)

```

# Answer
> 2 votes
# Python 2, 130 bytes

```
x=map(float,input())
l=len(x)
q=0
while abs(x[0]-sum(x)/(l+.0))>=1:x=x[:1]+[sum((x+x)[i-1:i+2])/3for i in range(1,l)];q+=1
print q

```

~~Slightly off for the larger test cases~~ Apparently not!

**BONUS:** Change `float` to `complex` and it will be able to handle complex numbers correctly (at a cost of two bytes).

*Edited once* ehhh.... I found a bug.... fixed now!

# Answer
> 2 votes
# Mathematica, 83 bytes

```
(a=#;0//.n_/;Mean@a-First@a>=1:>(a={#&@@a,##}&@@Mean/@Partition[a,3,1,{1,2}];n+1))&

```

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

```
f=(a,l=a.length,m=a.reduce((s,e)=>s+e-a[0],0))=>m>l|m<-l&&1+f(a.map((e,i)=>i?(a[i-1]+e+a[++i<l?i:0])/3:e))

```

# Answer
> 2 votes
## Haskell, 81 bytes

```
g l@(a:_)|abs(sum l/sum(1<$l)-a)<1=0|1<2=1+g(a:[(x+y+z)/3|x:y:z:_<-scanr(:)[a]l])

```

Usage example: `g [64,-66,-9,78,-60]` -\> `29`. Try it online!

How it works

```
g l@(a:b)                -- function g takes a list l where the first element
                         -- is bound to a
    |abs (      ) = 0    -- if the end condition is true, return 0
          sum(1<$l)      -- computes the length of l. The library function "length"
                         -- won't work, because it returns an "Int"
    | 1+g                -- else return 1 + a recursive call with one step of
                         -- averaging
  x:y:z:_<-scanr(:)[a]l  -- picks all 3 element sublists of l appended by a
                         -- the elements are bound to x, y and z

```

# Answer
> 2 votes
# Octave, 146 bytes

```
function k=f(a)n=numel(a);I=eye(n-1,n)/3;A=[resize(1,1,n);I+circshift(I,[0,1])+circshift(I,[0,2])];k=0;while(abs(mean(a)-a(1))>1)k++;a=A*a;end;end

```

Try it online!

Multi-line version:

```
function k = f(a)
    n = numel(a);
    I = eye(n - 1, n) / 3;
    A = [resize(1, 1, n);
         I + circshift(I, [0, 1]) + circshift(I, [0, 2])];
    k = 0;
    while(abs(mean(a) - a(1)) > 1)
        k++;
        a = A * a;
    end;
end

```

Pretty sure it's rather suboptimal.

# Answer
> 2 votes
# Jelly, 22 bytes

```
;®Æm3Ƥ®;µḷ/©ạÆmỊ¬µÐ¿L’

```

Try it online!

## How it works

```
;®Æm3Ƥ®;µḷ/©ạÆmỊ¬µÐ¿L’ - Main link. Takes an array A on the left
                  Ð¿   - While loop, collecting the results
                 µ     -   Condition:
         ḷ/            -     Get the first element of A
           ©           -     Save into the register R
             Æm        -     Get the mean of A
            ạ          -     Absolute difference
               Ị       -     Less than or equal to 1?
                ¬      -     Logical NOT
        µ              -   Body:
 ®                     -     Retrieve the first element of A
;                      -     Append to A
    3Ƥ                 -     Over overlapping windows of size 3:
  Æm                   -       Return the mean
      ®                -     Retrieve the first element of A
       ;               -     Prepend to the means
                    L  - Count the steps of the while loop
                     ’ - Decrement to account for the first iteration (A)

```

# Answer
> 2 votes
# APL (Dyalog Unicode), ~~35~~ 33 bytes

Saved 2 bytes thanks to Adám (and would have saved 1 with a tip from Bubbler)

```
{1≥|⊃⍵-⍵⌹=⍨⍵:0⋄1+∇h,3÷⍨3+/⍵,h←⊃⍵}

```

Try it online!

A recursive function.

Adám's idea of using ⌹ to find the average is really cool. See their explanation in the comments. `R` is the result of `X⌹Y`, and it's chosen to minimize the square of the difference between `X` and the matrix product of `R` and `Y`. In this case, since `Y` is a vector of all 1s, the average of `X` minimizes that squared difference.

Explanation:

```
{
  1≥|⊃⍵-(+/÷≢)⍵: 0        ⍝ Base case: If it's the last iteration, return 0
         ⍵⌹=⍨⍵           ⍝ Average of ⍵ (the array)
            =⍨⍵           ⍝ Compare ⍵ to itself to create an array of 1s the same size as ⍵
         ⍵⌹               ⍝ ⍵ divided by that (matrix division)
       ⍵-                  ⍝ Subtract that from all elements of ⍵
      ⊃                    ⍝ Take only the first of those differences
     |                     ⍝ Absolute value
   1≥                      ⍝ Is it less than or equal to 1?
⋄1+∇h,3÷⍨3+/⍵,h←⊃⍵
               h←⊃⍵        ⍝ Assign the first element of ⍵ to h
            ⍵,             ⍝ Append to ⍵ (because of wrapping)
         3+/               ⍝ Take groups of 3 adjacent elements and sum each
      3÷⍨                  ⍝ Divide each sum by 3 (to get average)
    h,                     ⍝ Prepend h, which stays constant
   ∇                       ⍝ Call on this new iteration
 1+                        ⍝ Add 1 to that
}

```

# Answer
> 2 votes
# Husk, 18 bytes

```
←V§≈←A¡λ:←¹mAX3S:←

```

Try it online!

### Explanation

```
←V§≈←A¡λ:←¹mAX3S:←
      ¡λ             Infinitely iterate the following function and build a list of results
               S:←   Append the first element to the list
             X3      Get all the contiguous sequences of 3 elements
           mA        Compute the average of each
        :←¹          Prepend the first element of the original list to this result
                     Now we have an infinite list with all the steps
 V§                  Find the index of the first position where:
     A                 the average
   ≈                   is similar (absolute difference <=1)
    ←                  to the first element
←                    Finally, subtract 1 (lists in Husk are 1-indexed)

```

# Answer
> 2 votes
# 05AB1E, 22 bytes

```
[¬UDÅAXα1›≠#Ćü3ÅAXš¼}¾

```

Try it online or verify all test cases.

**Explanation:**

```
[           # Start an infinite loop:
 ¬          #  Get the first item of the list (without popping the list itself)
            #  (which will use the implicit input-list in the first iteration)
  U         #  Pop and store this first item in variable `X`
 D          #  Duplicate the list
  ÅA        #  Pop and get the arithmetic mean
    Xα      #  Get the absolute difference with `X`
      1›≠   #  If this is NOT larger than 1 (thus it's <=1):
         #  #   Stop the infinite loop
  Ć         #  Enclose the list; append its own first item
   ü3       #  Create overlapping triplets
     ÅA     #  Get the arithmetic mean of each inner triplet
       Xš   #  Prepend `X` at the front of this list
 ¼          #  Increase the counter variable by 1 (0 by default)
}¾          # After the infinite loop: push the counter variable
            # (after which it is output implicitly as result)

```

# Answer
> 2 votes
# Ruby, 88 bytes

```
f=->a{x,=a;(x-1.0*a.sum/a.size).abs>1?f[[x,*[*a,x].each_cons(3).map{|a|a.sum/3.0}]]+1:0}

```

Try it online!

Recursive lambda, works with complex numbers. As usual, 2 bytes can be saved in Ruby 2.7+ by using a numbered block parameter. If we can assume that array values will always be provided as floats, we can save some more by avoiding float conversions.

# Answer
> 1 votes
# , 90 bytes

```
function(l){while(abs(mean(l)-l)>1){l[-1]=colMeans(array(l,sum(l|1)+1:0)[1:3,])
F=F+1}
+F}

```

Try it online!

Test harness stolen from Dominic van Essen's answer.

Uses R's recycling to construct the appropriate neighbor-means to replace in the original array.

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


title: Interpreting Fish (no, not that Fish)

text:
# Question
Title: Interpreting Fish (no, not that Fish)
Consider these five ASCII art sea creatures:

1. Standard fish: `><>` or `<><`
2. Speedy fish: `>><>` or `<><<`
3. Sturdy fish: `><>>` or `<<><`
4. Stretchy fish: `><<<>` or `<>>><`
5. Crab: `,<..>,`

Write a program that accepts an arbitrary string of the characters `<>,.`. If there is a way to interpret the *entire* string as a series of non-overlapping sea creatures, then the string should be reprinted with single spaces inserted between creatures. If this interpretation is impossible, nothing should be output (the program silently ends).

For example, the string `<><><>` can be interpreted as two standard fish back-to-back. The corresponding output would be `<>< ><>`.

As another example, the string `><>><>>` contains "instances" of...
(brackets only added as indicators)

* a couple standard fish: `[><>][><>]>`
* a speedy fish: `><[>><>]>`
* a sturdy fish in a couple ways: `[><>>]<>>` and `><>[><>>]`

however, only the pairing of a standard fish and a sturdy fish `[><>][><>>]` spans the entire length of the string with no fish sharing characters (no overlaps). Thus the output corresponding to `><>><>>` is `><> ><>>`.

If there are multiple ways the string could be interpreted, you may print any one of them. (And only print *one* of them.) For example, `<><<<><` can be interpreted as a standard fish and a sturdy fish: `[<><][<<><]`, or as a speedy fish and a standard fish: `[<><<][<><]`. So either `<>< <<><` or `<><< <><` would be valid output.

---

The crabs are just for fun. Since they don't start or end with `<` or `>`, they are much easier to identify (at least visually). For example, the string

```
,<..>,><<<>,<..>,><>,<..>,<>>><,<..>,><>>,<..>,<<><,<..>,<><,<..>,>><>

```

would obviously produce the output

```
,<..>, ><<<> ,<..>, ><> ,<..>, <>>>< ,<..>, ><>> ,<..>, <<>< ,<..>, <>< ,<..>, >><>

```

---

Here are some examples of strings (one per line) that produce no output:

```
<><>
,<..>,<..>,
>>><>
><<<<>
,
><><>
,<><>,
<<<><><<<>>><>><>><><><<>>><>><>>><>>><>><>><<><

```

The last string here can be parsed if you remove the leading `<`:

```
<<>< ><<<> >><> ><> ><> <>< <>>>< >><> >><> >><> ><>> <<><

```

(There may be other possible outputs.)

### Details

* The input string will only contain the characters `<>,.`.
* The input string will be at least one character long.
* Take input in any common way (command line, stdin) and output to stdout.
* The shortest code in bytes wins. (Handy byte counter.) Tiebreaker is earlier post.

# Answer
# Pyth, ~~64~~ ~~48~~ 50 bytes

```
#jdhfqzsTsm^+msXtjCk2U2"<>""
\r.1"",<..>,"dlzB

```

Test case.

---

Version that doesn't take forever (`O(9<sup>n/3</sup>)`) here, in 52 bytes.

---

This is the brute force approach, generate all sequences and check whether any sum to the input. Fish diagrams compressed as characters, whose binary representations are the `>` and `<`. The whole thing is wrapped in a try-catch block so that no output occurs when no results are found.

This is an `O(9<sup>n</sup>)` solution.

Some characters are stripped above, because control characters are used. They are reproduced faithfully at the link above.

xxd output:

```
0000000: 236a 6468 6671 7a73 5473 6d5e 2b6d 7358  #jdhfqzsTsm^+msX
0000010: 746a 436b 3255 3222 3c3e 2222 0a5c 7212  tjCk2U2"<>"".\r.
0000020: 141b 1d2e 3122 222c 3c2e 2e3e 2c22 646c  ....1"",<..>,"dl
0000030: 7a42                                     zB

```
> 21 votes

# Answer
# Non-deterministic Turing Machine, 20 states, 52 transitions (882 bytes maybe)

How do you convert this to bytes? I've written the files (absolutely not golfed) to execute this machine with Alex Vinokur's Simulator of a Turing Machine1. `wc -c` outputs the following (excluding the description file and the input files):

```
 12 alphabet
 49 meta
740 rules
 81 states
882 total

```

Anyways, I was preparing for my Computer Science A-Levels, so I thought this would be a good exercise (I don't know what I was thinking). So here's the definition:

$$\begin{align\*} M & = (Q, \Sigma, \iota, \sqcup, A, \delta) \\ Q & = \\{q\_{0},q\_{1},q\_{2},q\_{3},q\_{4},q\_{5},q\_{6},q\_{7},q\_{8},q\_{9},q\_{10},q\_{11},q\_{12},q\_{13},q\_{14},q\_{15},q\_{16},q\_{17},q\_{18},q\_{19}\\} \\ \Sigma & = \\{\< \\: ; \\: \> \\: ; \\: , \\: ; \\: . \\: ; \\: X \\: ; \\: $\\} \\ \iota & = q\_0 \\ \sqcup & = $ \\ A & = \\{q\_0, q\_5\\} \end{align\*}$$

*(the transition function)*

Excuse the bad image, but I couldn't be bothered with redrawing this thing on a computer. If you actually want to decipher the transition rules, I recommend you read through the rules file I linked above.

---

I've used `X`s instead of spaces because spaces are hard to visualize here and the simulator doesn't accept spaces in the alphabet.

The concept is fairly simple - q1 to q4 are used to catch right-facing fishes, q11 to q14 are used to catch left-facing fishes, q15 to q19 for crabs and the q5 to q10 blob is simply for inserting a space and moving all following characters one to the right.

If the string is interpretable, it accepts the string and the tape contains the string with spaces inserted. Otherwise it rejects the string (I guess this counts as no output - emptying the tape would be pretty easy but would require lots of transition rules and I don't think it would make the transition function prettier to look at).

---

*1 Note: It's difficult to compile. I had to edit the `src/tape.cpp` file and replace `LONG_MAX` with `1<<30` and then go to the `demo` directory, edit the Makefile to replace `EXE_BASENAME` with `turing.exe` and execute `make`. Then go to the directory with the files I've written and execute `/path/to/turing/download/src/turing.exe meta`.*
> 29 votes

# Answer
# fish (yes, that fish), 437 bytes

This strikes me as one of those programming tasks where exactly one language is right.

```
#!/usr/bin/fish

set the_fishes "><>" "<><" ">><>" "<><<" "><>>" "<<><" "><<<>" "<>>><" ",<..>,"
set my_fishes

function startswith
        set -l c (echo -n $argv[2]|wc -c)
        echo $argv[1]|cut -c(math $c+1)-
        test $argv[2] = (echo $argv[1]|cut -c-$c)
end

function pickafish
        set -l fix 1
            while true
                if test $fix -gt (count $the_fishes); return 1; end

                if not set rest (startswith $argv[1] $the_fishes[$fix])
                            set fix (math $fix+1)
                        continue
                end
                set my_fishes $my_fishes $the_fishes[$fix]
                    if test -z $rest
                        echo $my_fishes
                            exit
                    end
                    if not pickafish $rest
                    set my_fishes $my_fishes[(seq (math (count $my_fishes) - 1))]
                    set fix (math $fix+1)
                        continue
                end
        end
end

pickafish $argv[1]

```

The following version is still the longest answer to the challenge,

```
set t "><>" "<><" ">><>" "<><<" "><>>" "<<><" "><<<>" "<>>><" ",<..>,";set m;function p;set -l i 1;while true;test $i -gt 9; and return 1;if not set r (begin;set c (echo $t[$i]|wc -c);echo $argv[1]|cut -c$c-;test $t[$i] = (echo $argv[1]|cut -c-(math $c-1));end);set i (math $i+1);continue;end;set m $m $t[$i];if test -z $r;echo $m;exit;end;if not p $r;set m $m[(seq (math (count $m)-1))];set i (math $i+1);continue;end;end;end;p $argv[1]

```

but since this was done mostly for the pun (you'll excuse, I hope), better golfing is left as an exercise to the reader.
> 23 votes

# Answer
## **\>\<\>, 602 bytes**

```
0&>i:0)?vr>:5%4-?v}:5%?;}:5%1-?;}:5%1-?;}:5%2-?;}:5%4-?;}&~0& v
  \     /        >:5%2-?v}:5%2-?v}:5%?v}:5%2-?v}              v
 &:?v;>*} ^      v      <       >:5% ?v}:5%?v} :5% ?v}:5%2-?v}v
v&-1< ^48<                                  >: 5%2-?v}:5%2-  ?v&1+&0}}v
>    :?v~^       >:5%?v}:5%?v}:5%2-  ?v}:5%  ?v}              v
^~v?%8:<                    >:5%2-?v}: 5%2-?v} :5%2- ?v}:5%?v}v
^{<        >0>=?;:v                         >: 5%    ?v}:5%  ?v&1+&0}}v
           ^lo~<  <   >            >  >       >     > >     >  02.
          \}*48^?=i:                                          <       <

```

A solution in Fish, probably very golfable but it's my first \>\<\> program. It takes its input from the input stack and runs on the online \>\<\> interpreter.

## How it works :

A loop reads all the input and stacks it, reverse it and put a -1 on the bottom wich will mark that parsing is complete (all characters stay on the stack until the string is deemed parsable).
The parsing uses the fact all characters are different modulo 5, and all patterns are deterministic except \<\>\<\< and \>\<\>\>. Parsed characters are put on the bottom of the stack.
When a pattern is complete, if -1 is on top, all characters are printed, otherwise a space is added and the program loops.
If \<\>\<\< or \>\<\>\> are encountered, the register is incremented (0 at the start), and a 0 is placed on the stack before the last character (so that \<\>\< or \>\<\> stays after rollback). If an error appears afterwards during parsing, the register is decreased, all characters after the 0 are put back on top (except spaces thanks to a %8=0 test).
If an error is detected while the register is 0, or inside the crab, the program just ends immediately.
> 21 votes

# Answer
## Python 3, 156

```
*l,s=[],input()
for _ in s:l+=[y+[x]for x in"><> >><> ><>> ><<<> <>< <><< <<>< <>>>< ,<..>,".split()for y in l]
for y in l:
 if"".join(y)==s:print(*y);break

```

The strategy is to generate lists of fish and compare their concatenation to the input string.

This takes impossibly long. If you actually want to see an output, replace `for _ in s` with `for _ in [0]*3`, where 3 is the upper bound for the number of fish. It works to use `s` because `s` contains at most one fish per char.

Thanks to Sp3000 for bugfixes and a char save on input.

Old 165:

```
f=lambda s:[[x]+y for x in"><> >><> ><>> ><<<> <>< <><< <<>< <>>>< ,<..>,".split()for y in f(s[len(x):])if s[:len(x)]==x]if s else[[]]
y=f(input())
if y:print(*y[0])

```
> 13 votes

# Answer
# Perl, 81 + 1 bytes

```
/^((>><>|><(|>|<<)>|<><<|<(|<|>>)><|,<\.\.>,)(?{local@a=(@a,$2)}))*$(?{say"@a"})/

```

Try this code online.

This code expects the input in the `$_` variable; run this with Perl's `-n` switch (counted as +1 byte) to apply it to each input line, e.g. like this:

```
perl -nE '/^((>><>|><(|>|<<)>|<><<|<(|<|>>)><|,<\.\.>,)(?{local@a=(@a,$2)}))*$(?{say"@a"})/'

```

This code uses Perl's regexp engine (and specifically its embedded code execution feature) to perform an efficient backtracking search. The individual fishes found are collected in the `@a` array, which is stringified and printed if the match is successful.

This code also uses the Perl 5.10+ `say` feature, and so must be run with the `-E` or `-M5.010` switch (or `use 5.010;`) to enable such modern features. By tradition, such switches used solely to enable a particular version of the language are not included in the byte count.

Alternatively, here's a 87-byte version that requires no special command-line switches at all. It reads one line from stdin, and prints the result (if any) to stdout, without any trailing linefeed:

```
<>=~/^((>><>|><(|>|<<)>|<><<|<(|<|>>)><|,<\.\.>,)(?{local@a=(@a,$2)}))*$(?{print"@a"})/

```

**Ps.** If printing an extra space at the beginning of the output was allowed, I could trivially save two more bytes with:

```
/^((>><>|><(|>|<<)>|<><<|<(|<|>>)><|,<\.\.>,)(?{local$a="$a $2"}))*$(?{say$a})/

```
> 12 votes

# Answer
# Python 2, 234 bytes

I tried a Python regex solution first, but there seems to be no way to extract the groups after a match on multiple patterns. The following is a recursive search which seems to do well on the test cases.

```
a='><> >><> ><>> ><<<> <>< <><< <<>< <>>>< ,<..>,'.split()
def d(t,p=0):
 if p<len(t):
  for e in a:
   z=p+len(e)
   if e==t[p:z]:
    if z==len(t):return[e]
    c=d(t,z)
    if c:return[e]+c
c=d(raw_input())
if c:
 print' '.join(c)

```

An example test:

```
$ echo ",<..>,><<<>,<..>,><>,<..>,<>>><,<..>,><>>,<..>,<<><,<..>,<><,<..>,>><>" | python soln.py
,<..>, ><<<> ,<..>, ><> ,<..>, <>>>< ,<..>, ><>> ,<..>, <<>< ,<..>, <>< ,<..>, >><>

```

And the ungolfed version:

```
fishtypes = '><> >><> ><>> ><<<> <>< <><< <<>< <>>>< ,<..>,'.split()

def getfish(t, p=0):
    if p < len(t):
        for afish in fishtypes:
            z = p+len(afish)
            if afish == t[p:z]:
                if z == len(t) :
                    return [afish]
                fishlist = getfish(t, z)
                if fishlist :
                    return [afish]+fishlist

fishlist = getfish(raw_input())
if fishlist:
    print ' '.join(fishlist)

```
> 6 votes

# Answer
# Python 3, ~~196~~ 186 bytes

```
F="><> >><> ><>> ><<<> <>< <><< <<>< <>>>< ,<..>,".split()
def g(s):
 if s in F:return[s]
 for f in F:
  i=len(f)
  if f==s[:i]and g(s[i:]):return[f]+g(s[i:])
R=g(input())
if R:print(*R)

```

Simple recursion. `g` either returns a list of parsed fish, or `None` if the input string is unparseable.
> 6 votes

# Answer
# C# - 319 bytes

This solution is shamefully simple, hardly anything to Golf. It's a complete program, takes input as a line from STDIN, and outputs the result to STDOUT.

```
using C=System.Console;class P{static void Main(){C.Write(S(C.ReadLine()));}static string S(string c){int i=c.LastIndexOf(' ')+1;foreach(var o in"<>< ><> <<>< ><>> >><> <><< ><<<> <>>>< ,<..>,".Split()){string k=c+"\n",m=c.Substring(i);if(m==o||m.StartsWith(o)&&(k=S(c.Insert(i+o.Length," ")))!="")return k;}return"";}}

```

It simply attempts to match each fish to the first position after a space (or at the start of the string), and matches each type of fish with it. If the fish fits, then it recursively calls the solver after inserting a space after the fish, or simply returns it's input (with a \n for output reasons) if the unmatched string is literally the fish (i.e. we've found a solution).

I haven't made much of an attempt to give the fish string the usual kolmogorov treatment, because it isn't all that long, and I can't find a cheap way to reverse a string in C# (I don't think LINQ will pay), so there may be some opportunity there, but I somewhat doubt it.

```
using C=System.Console;

class P
{
    static void Main()
    {
        C.Write(S(C.ReadLine())); // read, solve, write (no \n)
    }

    static string S(string c)
    {
        int i=c.LastIndexOf(' ')+1; // find start of un-matched string

        // match each fish
        foreach(var o in"<>< ><> <<>< ><>> >><> <><< ><<<> <>>>< ,<..>,".Split())
        {
            string k=c+"\n", // set up k for return if we have finished
            m=c.Substring(i); // cut off stuff before space
            if(m==o|| // perfect match, return straight away
               m.StartsWith(o)&& // fish matches the start
               (k=S(c.Insert(i+o.Length," "))) // insert a space after the fish, solve, assign to k
               !="") // check the solution isn't empty
                return k;
        }

        // no fish match
        return"";
    }
}

```
> 4 votes

# Answer
# Haskell(Parsec) - 262

```
import Text.Parsec
c=words"><> >><> ><>> ><<<> <>< <><< <<>< <>>>< ,<..>,"
p c d=choice[eof>>return[],lookAhead(choice$map(try.string)d)>>=(\s->try(string s>>p c c>>=(\ss->return$s:ss))<|>p c(filter(/=s)c))]
main=interact$either show unwords.runParser(p c c)()""

```
> 3 votes

# Answer
```
import sys

def unfish(msg,dict,start):
    if(len(msg[start:])<3):
        return "";
    for i in range(3,6):
        if (msg[start:start+i] in dict):
            if(start+i==len(msg)):
                return msg[start:start+i];
            else:
                ret = unfish(msg,dict,start+i);
                if ret != "":
                    return msg[start:start+i]+" "+ret;
    return ""

dict = {'><>':1,'<><':1,'>><>':1,'<><<':1,'><>>':1,'<<><':1,'><<<>':1,'<>>><':1,',<..>,':1};

print unfish(sys.argv[1],dict,0);

```

im a bit of a python noob so ignore the weirdness :P
> 2 votes

# Answer
# Ruby, 177 bytes

Not the shortest but the first one in ruby:

```
def r(e,p,m)t='';p.each{|n|t=e.join;return r(e<<n,p,m)if m=~/^#{t+n}/};(m==t)?e:[];end
puts r([],%w(><<<> <>>>< ><>> <<>< >><> <><< ><> <>< ,<..>,),gets.strip).join(' ')

```

The attempt here is to recursively extend a regexp and match it against the input.
If a longer match is found r() will recurse, if not it will check if the last match consumes the whole input string and only then output it with added spaces.
> 2 votes

# Answer
# Jelly, 35 bytes

```
“¦¿Æ×‘B;¬$ị⁾<>“,<..>,”ṭ
J¢ṗẎẎ⁼¥Ƈ⁸ḢK

```

Try it online!

This is *brutally* inefficient, clocking in at around (I believe) \\$O(9^{n^2})\\$, and times out on TIO for strings of length \\$7\\$ or more

Returns `0` if the input cannot be interpreted as fish

A much faster version is 38 bytes, timing out for length \\$21\\$ or more

## How it works

Similar to isaacg's Pyth answer, we generate all possible fish strings, then look for the one(s) equal to the input

```
“¦¿Æ×‘B;¬$ị⁾<>“,<..>,”ṭ - Helper link. Returns a list of fish
“¦¿Æ×‘                  - [5,11,13,17]
      B                 - Convert to binary; [[1,0,1],[1,0,1,1],[1,1,0,1],[1,0,0,0,1]]
        ¬               - Logical NOT of each bit; [[0,1,0],[0,1,0,0],[0,0,1,0],[0,1,1,1,0]]
       ; $              - Concatenate to the bits; [[1,0,1],[1,0,1,1],...,[0,0,1,0],[0,1,1,1,0]]
          ị⁾<>          - Index into "<>", replacing 1 with < and 0 with >
              “,<..>,”  - Yield the crab
                      ṭ - Append it to the fish

J¢ṗẎẎ⁼¥Ƈ⁸ḢK - Main link. Takes a fish F of length n on the left
J           - Yield [1, 2, ..., n]
 ¢          - Get the list of fish
  ṗ         - For each i in 1,2,...,n get the i'th Cartesian power of the fish
   Ẏ        - Concatenate into a list of lists
      ¥Ƈ    - Keep those lists for which the following is true:
    Ẏ       -   When concatenated into a flat list of characters,
     ⁼      -   the list equals
        ⁸   -   the input F
         Ḣ  - Take the first list of fish
          K - Join by spaces

```
> 2 votes

# Answer
# CJam, ~~111 96~~ 91 (or 62 bytes)

An iterative greedy approach to keep figuring out what all fish combinations are possible as you iterate. Really not golfed right now.

```
q_aa\,{{" È÷®µãÑø"255b5b" ><,."f=S/\f{)_3$#{;;;}{2$,>:P@a\a++}?PR+!{S:R*W<o}*}~}%}*];

```

The code contains some unprintable characters, so use the link below for reference.

*Update* Encoded the string

Will add explanation once done golfing

Try it online here

---

# 62 bytes

Super slow version. This basically creates all the combinations and checks which are equal to the input.

```
L"¬ééãLù:9$"255b6b5," ><,."erS/aq:Q,*{m*}*{sQ=}=`"[]\""-

```

This also contains unprintable characters, so rely on the below link.

Try it online here
> 1 votes

# Answer
# Haskell, ~~148~~ 146 bytes

```
main=mapM_ putStr.take 1.filter(all(`elem`words"><> >><> ><>> ><<<> <>< <><< <<>< <>>>< ,<..>,").words).map concat.mapM(\a->[[a],a:" "])=<<getLine

```

Testing:

```
$ echo "><>><>>>" | runhaskell fishes.hs

```

$ echo "\>\<\>\>\<\>\>" | runhaskell fishes.hs

> \<\> \>\<\>\>

## Explanation

Based on my earlier answer to a similar question. The algorithm runs in exponential time.

This reads from right to left.

```
=<<getLine              -- Read a line from STDIN.
mapM(\a->[[a],a:" "])   -- Replace each letter 'a' by "a" or "a " in
                        -- all possible ways, collect results to a list.
map concat              -- Concatenate those lists-of-strings into strings.
filter(all(...).words)  -- Keep those whose words are correct fish.
take 1                  -- Discard all but the first one.
mapM_ putStr            -- Print each string in that 1- or 0-element list.
main=                   -- That is the main function.

```

This will not print a string that ends with a space, even though such strings are generated too, because its no-space counterpart is generated first.
> 1 votes

# Answer
# JavaScript (ES6), 164

Recursive, depth first scan.
As a program with I/O via popup:

```
alert((k=(s,r)=>'><>0<><0>><>0<><<0><>>0<<><0><<<>0<>>><0,<..>,'.split(0)
.some(w=>s==w?r=w:s.slice(0,l=w.length)==w&&(t=k(s.slice(l)))?r=w+' '+t:0)?r:'')
(prompt()))

```

As a testable function:

```
k=(s,r)=>'><>0<><0>><>0<><<0><>>0<<><0><<<>0<>>><0,<..>,'.split(0)
.some(w=>s==w?r=w:s.slice(0,l=w.length)==w&&(t=k(s.slice(l)))?r=w+' '+t:0)?r:''

```

Test suite (run in Firefox/FireBug console)

```
t=['<><><>', '><>><>>', '<><<<><',',<..>,><<<>,<..>,><>,<..>,<>>><,<..>,><>>,<..>,<<><,<..>,<><,<..>,>><>',
'<><>',',<..>,<..>,','>>><>','><<<<>',',','><><>',',<><>,',
'<<<><><<<>>><>><>><><><<>>><>><>>><>>><>><>><<><','<<><><<<>>><>><>><><><<>>><>><>>><>>><>><>><<><']

t.forEach(t=>console.log(t + ': ' +k(t)))

```

*Output*

```
<><><>: <>< ><>
><>><>>: ><> ><>>
<><<<><: <>< <<><
,<..>,><<<>,<..>,><>,<..>,<>>><,<..>,><>>,<..>,<<><,<..>,<><,<..>,>><>: ,<..>, ><<<> ,<..>, ><> ,<..>, <>>>< ,<..>, ><>> ,<..>, <<>< ,<..>, <>< ,<..>, >><>
<><>:
,<..>,<..>,:
>>><>:
><<<<>:
,:
><><>:
,<><>,:
<<<><><<<>>><>><>><><><<>>><>><>>><>>><>><>><<><:
<<><><<<>>><>><>><><><<>>><>><>>><>>><>><>><<><: <<>< ><<<> >><> ><> ><> <>< <>>>< >><> >><> >><> ><>> <<><

```

**Ungolfed** just the k function

```
function k(s)
{
  var f='><>0<><0>><>0<><<0><>>0<<><0><<<>0<>>><0,<..>,'.split(0)
  var i, w, l, t

  for (w of f)
  {
    if (s == w)
    {
      return w
    }
    l = w.length
    if (s.slice(0,l) == w && (t = k(s.slice(l))))
    {
      return w + ' ' + t
    }
  }
  return ''
}

```
> 1 votes

# Answer
# Python 3, ~~166~~ 164 bytes

```
def z(s,p=''):[z(s[len(f):],p+' '+s[:len(f)])for f in'<>< <><< <<>< <>>>< ><> >><> ><>> ><<<> ,<..>,'.split(' ')if s.startswith(f)]if s else print(p[1:])
z(input())

```

Recursive solution. Late to the party, but I thought I'd post it anyway since it beats Sp3000's by ~~20~~ 22 bytes without having to brute-force the answer.
> 1 votes

# Answer
# Haskell, ~~148~~ 142

```
p[]=[[]]
p s=[i:j|i<-words"><> >><> ><>> ><<<> <>< <><< <<>< <>>>< ,<..>,",i==map fst(zip s i),j<-p$drop(length i)s]
    g s=unwords$head$p s++p[]

```

this uses list comprehensions to iterate over the fish, pick the ones who match the start and continue recursively.
> 0 votes

# Answer
# Javascript (~~122~~ 135 bytes)

Not the most golfed here, could be stripped down a little.

This one is regex based, and a tad hard to figure out what is going on.

```
alert(prompt(R=RegExp,r='(<<?><|><>>?|,<\.\.>,|>><>|><<<>|<><<|<>>><)').match(R('^'+r+'+$'))[0].split(R(r+'(?=[>,]|$)','g')).join(' '))

```

This one is a one-liner.

Basically, I check the syntax and then I split the string based on the chars and join it together.
It throws an exception when you give it an invalid input.

If it can't throw exceptions (~~126~~ 139 bytes):

```
(i=prompt(R=RegExp,r='(<<?><|><>>?|,<\.\.>,|>><>|><<<>|<><<|<>>><)')).match(R('^'+r+'+$'))&&alert(i.split(R(r+'(?=[>,]|$)','g')).join(' '))

```

Both are one-liners.
Both work the same way.

---

Thank you @edc65 for detecting the edge case that wasn't working well.

---

You can test it here (output will be written to the document).

It is based on the version that throws exceptions when you introduce invalid code.

```
var alert=console.log=function(s){document.write(s)+'<br>';};
try{
alert(prompt(R=RegExp,r='(<<?><|><>>?|,<\.\.>,|>><>|><<<>|<><<|<>>><)').match(R('^'+r+'+\x24'))[0].split(R(r+'(?=[>,]|\x24)','g')).join(' '));
}catch(e){console.log(e);}
```

(Currently, there's a bug on stack snippets, ~~I've posted in on meta~~ It was already asked yesterday. For it to work, I've replaced `$` with `\x24`, which has the same output. You can read about the bug here: http://meta.codegolf.stackexchange.com/questions/5043/stack-snippets-messing-with-js)
> 0 votes

# Answer
# Scala, 299 Bytes

```
type S=String
type L[T]=List[T]
def c(s:S):L[L[S]]={val f=List("><>","<><",">><>","<><<","><>>","<<><","><<<>","<>>><",",<..>,").filter(s.startsWith);if(f.isEmpty)List(List(s)) else f.flatMap(i => c(s.drop(i.size)).map(i::_))}
def p(s:S)=println(c(s).find(_.last.isEmpty).fold("")(_.mkString(" ")))

```

# Test Cases

```
val tests = Seq("><>", "<><", ">><>", "<><<", ">><>", "<><<", "><<<>", "<>>><", ",<..>,", "><>><>", "><><><", ",<..>,<><", "<<<><><<<>>><>><>><><><<>>><>><>>><>>><>><>><<><", "<<><><<<>>><>><>><><><<>>><>><>>><>>><>><>><<><")
tests.foreach(p)

```

Output

```
><>
<><
>><>
<><<
>><>
<><<
><<<>
<>>><
,<..>,
><> ><>
><> <><
,<..>, <><

<<>< ><<<> >><> ><> ><> <>< <>>>< >><> >><> >><> ><>> <<><

```
> 0 votes

# Answer
**Java, 288 bytes**

```
public class F{public static void main(String[]q){d("",q[0]);}static System y;static void d(String a,String b){if(b.isEmpty()){y.out.println(a);y.exit(0);}for (String s : "><> <>< >><> <><< ><>> <<>< ><<<> <>>>< ,<..>,".split(" "))if(b.startsWith(s))d(a+" "+s,b.substring(s.length()));}}

```

Formatted:

```
public class F {
    public static void main(String[] q) {
        d("", q[0]);
    }

    static System y;

    static void d(String a, String b) {
        if (b.isEmpty()) {
            y.out.println(a);
            y.exit(0);
        }
        for (String s : "><> <>< >><> <><< ><>> <<>< ><<<> <>>>< ,<..>,".split(" "))
            if (b.startsWith(s)) d(a + " " + s, b.substring(s.length()));
    }
}

```
> 0 votes

# Answer
I wasn't going for size, but here is an easy to understand way of doing this in Dart.

```
const List<String> fish = const [
  "><>",
  "<><",
  ">><>",
  "<><<",
  "><>>",
  "<<><",
  "><<<>",
  "<>>><",
  ",<..>,"
];

String fishy(String input) {
  var chars = input.split("");
  if (chars.isEmpty || !chars.every((it) => [">", "<", ",", "."].contains(it))) {
    throw new Exception("Invalid Input");
  }

  var result = [];
  var i = 0;
  var buff = "";
  while (i < chars.length) {
    buff += chars[i];

    if (fish.contains(buff)) {
      result.add(buff);
      buff = "";
    } else if (chars.length == 6) {
      return "";
    }

    i++;
  }

  return result.join(" ");
}

void main() {
  print(fishy(",<..>,><<<>,<..>,><>,<..>,<>>><,<..>,><>>,<..>,<<><,<..>,<><,<..>,>><>"));
}

```
> 0 votes

---
Tags: code-golf, ascii-art, kolmogorov-complexity
---