title: Binary Images of Triangle Counts

text:
# Question
Title: Binary Images of Triangle Counts
My challenges tend to be a little bit hard and unattractive. So here something easy and fun.

## Alcuin's sequence

Alcuin's sequence `A(n)` is defined by counting triangles. `A(n)` is the number of triangles with integer sides and perimeter `n`. This sequence is called after Alcuin of York.

The first few elements of this sequence, starting with `n = 0` are:

```
0, 0, 0, 1, 0, 1, 1, 2, 1, 3, 2, 4, 3, 5, 4, 7, 5, 8, 7, 10, 8, ...

```

For instance `A(9) = 3`, because the only triangles with integer sides and perimeter `9` are `1 - 4 - 4`, `3 - 3 - 3` and `2 - 3 - 4`. You can see the 3 valid triangles down below.

There are some quite interesting pattern in this sequence. For instance `A(2*k) = A(2*k - 3)`.

For more information, see A005044 on OEIS.

## Challenge

But your challenge is about the binary representation of these numbers. If we convert each sequence number to it's binary representation, put them in column vectors and line them up, it creates a quite interesting binary picture.

In the following picture you can see the binary representation of the sequence numbers `A(0), A(1), ..., A(149)`. In the first column you can see the binary representation of `A(1)`, in the second column the representation of `A(1)`, and so on.

You can see some sort of repeating pattern in this picture. It even looks kinda like fractals, if you look for instance at the image with the sequence numbers `A(600), A(601), ..., A(899)`.

Your job is to generate such an image. Your function, your script will receive two integer `0 <= m < n`, and it has to generate the binary image of Alcuin's sequence `A(m), A(m+1), A(m+2), ..., A(n-2), A(n-1)`. So the input `0, 150` generates the first picture, the input `600, 900` the second picture.

You can use any popular graphics format you want. Let's say every format that can be converted to png using image.online-convert.com. Alternatively, you may display the image on screen. No leading white rows are allowed!

This is code-golf. So the shortest code (in bytes) wins.

# Answer
> 3 votes
# J (~~52~~ 45 (Codepage 437))

This would be allowed (I think)

```
[:|:' █'{~[:#:[:([:<.48%~*:+24+6*]*2|])(}.i.)

```

### Hex dump

(Nothing special really, the black square is DB16 or 21910 in codepage 437.)

```
0000: 5b 3a 7c 3a 27 20 db 27 7b 7e 5b 3a 23 3a 5b 3a   [:|:' .'{~[:#:[:
0010: 28 5b 3a 3c 2e 34 38 25 7e 2a 3a 2b 32 34 2b 36   ([:<.48%~*:+24+6
0020: 2a 5d 2a 32 7c 5d 29 28 7d 2e 69 2e 29            *]*2|])(}.i.)

```

### Usage

This outputs as follows (The code tags mess it up by adding space between the lines):

```
   A=:[:|:' █'{~[:#:[:([:<.48%~*:+24+6*]*2|])(}.i.)
   0 A 100
                                                                             █ █████████████████████
                                                     █ ██████████████████████ █              █ █████
                                     █ ██████████████ █          █ ██████████ █      █ ██████ █
                         █ ██████████ █      █ ██████ █    █ ████ █    █ ████ █  █ ██ █  █ ██ █  █ █
                 █ ██████ █    █ ████ █  █ ██ █  █ ██ █  █  █  █  █  █  ██ ██ ██  ██  ██  ██  ██  ██
           █ ████ █  █ ██ █  █  █  █  ██  ██  ██  ██  ██  █  █  █  █ ██ █  █ ████ █
       █ ██ █  █  ██  ██  ██  █  █ ██ █                █ ██ █  █  ██  ██  ██  █  █ ██ █
   █ ██ ██  ██ ██ █        █ ██ ██  ██ ██ █        █ ██ ██  ██ ██ █        █ ██ ██  ██ ██ █        █
   2000 A 2100
████████████████████████████████████████████████████████████████████████████████████████████████████

████████████████████████████████████████████████████████████████████████████████████████████████████
                                                                             █ █████████████████████
                             █ ██████████████████████████████████████████████ █
     █ ██████████████████████ █                      █ ██████████████████████ █
█████ █          █ ██████████ █          █ ██████████ █          █ ██████████ █          █ █████████
 ████ █    █ ████ █    █ ████ █    █ ████ █    █ ████ █    █ ████ █    █ ████ █    █ ████ █    █ ███
█  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █
██  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █ ██ ██ █
 █ ██ ██ ██ ██ ██ █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  █  ██ ██ ██ ██ ██  █  █
  ██ ██ ██  █  █  ██ ██ ██  █  █  █  █  █  █  █  █  █  █  █  █  █  █ ██ ██ ██ █  █  █  █ ██ █  █ ██
 █ ██ █  █ ██ █  █ ██ █  █ ██ █  █  █  █  █  █  █  █  █  █  ██ ██ ██  █  █  ██  ██ ██ ██  ██  ██  ██
  ██  ██  ██  ██  ██  ██  ██  ██ ██ ██  █  █  █  █  █  █ ██ █  █ ██ █  █ ████ █    █ ██████ █
█ █                        █ ████ █  █ ██ █  █  █  █  ██  ██  ██  ██  ██  █  █  █  █ ██ █  █ ████ █
 █ ██ █                █ ██ █  █  ██  ██  ██  █  █ ██ █                █ ██ █  █  ██  ██  ██  █  █ █
██  ██ ██ █        █ ██ ██  ██ ██ █        █ ██ ██  ██ ██ █        █ ██ ██  ██ ██ █        █ ██ ██

```

In the standard J console, there is no spacing between lines, so I call the rule 'Alternatively, you may display the image on screen.' (Nowhere did it say that this image had to be represented as a sensible image format internally)

EDIT: Jconsole (as opposed to JQT) uses codepage 437 as a default, and DOES render the rectangles correctly when using them from a string.

# Answer
> 9 votes
# Mathematica, ~~126~~ ~~122~~ ~~121~~ 89 bytes

```
Image[1-Thread@IntegerDigits[l=Round[(#+3#~Mod~2)^2/48]&/@Range@##,2,⌈2~Log~Max@l⌉]]&

```

This defines an unnamed function taking the two integers as parameters and displaying the image on screen. It plots each square as a single pixel, but if you like you can actually zoom in.

I'm now using an explicit formula given in the OEIS article (first one in the Mathematica section, thanks to David Carraher for pointing that out). It's also blazingly fast now.

Here is the indented code with a few comments:

```
Image[1-Thread@IntegerDigits[   (* 3. Convert each number to padded binary, transpose
                                      invert colours, and render as Image. *)
    l = Round[
      (#+3#~Mod~2)^2/48
    ] & /@ Range@##,            (* 1. Turn input into a range and get the Alcuin
                                      number for each element. *)
    2,
    ⌈2~Log~Max@l⌉               (* 2. Determine the maximum number of binary digits. *)
]] &

```

Here is the output for `0, 600`:

# Answer
> 8 votes
## CJam (56 55 53 chars) / GolfScript (64 chars)

CJam:

```
"P1"q~,>{_1&3*+_*24+48/}%_:e>2b,\2_$#f+2fbz(,@@:~~]N*

```

GolfScript:

```
"P1"\~,>{.1&3*+.*24+48/}%.$-1=2base,\{2.$?+2base}%zip(,@@{~}/]n*

```

Both produce output in NetPBM format, and they're essentially ports of each other.

### Dissection

```
CJam                 GolfScript           Explanation

"P1"                 "P1"\                NetPBM header
q~,>                 ~,>                  Create array [m .. n-1]
{_1&3*+_*24+48/}%    {.1&3*+.*24+48/}%    Map the sequence calculation
_:e>2b,\             .$-1=2base,\         Compute image height H as highest bit
                                          in largest number in sequence
2_$#f+2fb            {2.$?+2base}%        Map sequence to bits, ensuring that
                                          each gives H bits by adding 2^H
z(,@@                zip(,@@              Transpose and pull off dummy row to use
                                          its length as the "width" in the header
:~~                  {~}/                 Flatten double array and dump on stack
]N*                  ]n*                  Separate everything with whitespace

```

Thanks to Optimizer for CJam 56 -\> 53.

# Answer
> 5 votes
# Pyth - 101 60 59

Outputs a `.pbm`. Can likely be golfed more.

```
Km.B/++24*dd**6%d2d48rvzQJCm+*\0-eSmlkKlddK"P1"lhJlJjbmjbdJ

```

Highly ungolfed because I will be translating to Pyth.

Explanation coming next. Right now look at the equivalent Python code.

It uses the OEIS algorithm to calculate the sequence and then it converts to binary, pads the numbers, does a matrix rotation, and formats it into a `pbm` image. Since I'm not using brute force, it is incredibly fast.

```
         K=
 m          rvzQ      Map from eval input to eval input
  .B                  Binary rep
   /      48          Divided by 48
    ++                Triple sum
     24               Of 24,
     *dd              Square of d
     **               Triple product
      6               6
      %d2             Modulo d%2
      d               Var d
J                     Set J=
 C                    Matrix rotation from columns of row to rows of columns
  m           K       Map K (This does padding)
   +                  String concat
    *                 String repeat
     \0               "0"
     -     ld         Subtract the length of the column from
      eS              The max
       mlkK           Of all the column lengths
    d                 The column
"P1"                  Print header "P1"
l                     Length of
 hJ                   First row
lJ                    Number of columns
jb                    Join by linebreaks
 m  J                 Map on to J
  jb                  Joined columns by linb
   d

```

Here is the `600,900` example:

Try it here online.

# Answer
> 4 votes
# R - ~~127~~ 125

I'm not sure if this complies with the rules totally. It doesn't output an image to a file, but it does create a raster and plot it to an output device.

I found the same formula as Martin, but here.

It uses an unnamed function.

```
require(raster);function(m,n)plot(raster(mapply(function(n)rev(as.integer(intToBits(round((n+n%%2*3)^2/48)))),m:n),0,n,0,32))

```

Run as follows

```
require(raster);(function(m,n)plot(raster(mapply(function(n)rev(as.integer(intToBits(round((n+n%%2*3)^2/48)))),m:n),0,n,0,32)))(0,600)

```

Produces the following plot

# Answer
> 3 votes
# Python 2 ~~\+ PIL~~, ~~255~~ 184

My first version used PIL in order to show an image :

```
i,R,B=input,range,lambda x:bin((x*x+6*x*(x%2)+24)/48)[2:]
def F(k,v):i.load()[k]=v
a,b=i(),i();h=len(B(b));from PIL import Image;i=Image.new('P',(b-a,h))
[F((x-a,y),int(B(x).zfill(h)[y])) for x in R(a,b) for y in R(h)]
i.putpalette([255]*3+[0]*3)
i.show()

```

The new version just produces a b&w PPM image on stdout :

```
i,R,B=input,range,lambda x:bin((x*x+6*x*(x%2)+24)/48)[2:]
def p(s):print s
a,b=i(),i();h=len(B(b));p('P1 %i %i'%(b-a,h))
[p(' '.join([B(x).zfill(h)[y] for x in R(a,b)])) for y in R(h)]

```

# Answer
> 2 votes
## JAVASCRIPT - 291

Code:

```
(function(a,b,c){c.width=b;t=c.getContext('2d');t.strokeStyle='black';for(i=a;i<=b;i++){g=(Math.floor(((i*i)+6*i*(i%2)+24)/48)>>>0).toString(2);l=g.length;for(j=0;j<l;j++){if(g[l-1-j]=='1'){t.rect(i-a,j,1,1);t.fill();}}}document.body.appendChild(c);})(0,300,document.createElement('canvas'))

```

Explanation:

```
(function (a, b, c) {
    //setting canvas width
    c.width = b;
    //get context 2d of canvas
    t = c.getContext('2d');
    //setting storke style.
    t.strokeStyle = 'black';
    //looping from a to b
    for (i = a; i <= b; i++) {
        //calculating A(i) and converting it to a binary string
        g = (Math.floor(((i * i) + 6 * i * (i % 2) + 24) / 48) >>> 0).toString(2);
        //looping through that string
        for (j = 0; j < g.length; j++) {
            //since canvas is upside down and the first digit is actually the last digit:
            if (g[g.length - 1 - j] == '1') {
                //we create the 1 by 1 rect
                t.rect(i - a, j, 1, 1);
                //we draw the rect
                t.fill();
            }
        }
    }
    //we append everything to the body
    document.body.appendChild(c);
    //parameters are put here
})(0, 300, document.createElement('canvas'))

```

Result:

Yes the result is upside down, but that's because `0,0` on a `js canvas` is top left. :3

Demo:

Demo on jsfiddle

# Answer
> 0 votes
# APL (Dyalog Extended), ~~26 25~~ 24 bytes

```
' ⎕'[⊤⌊12÷⍨6+×⍨⊥⊖0 2⊤…⎕]

```

Try it online!

Takes the inputs in reverse(-1 byte).

-1 byte from Bubbler(`.5+12÷⍨ → 12÷⍨6+`)

Generates the sequence in the same way as the existing J solution, except Bubbler shortened it with some math explained here.

Uses '⎕' as the display character. If '█' is required, then it becomes 27 bytes(does look nicer with it).

## Explanation

```
' ⎕'[⊤⌊12÷⍨6+×⍨⊥⊖0 2⊤…⎕]
                      ⎕  take the second and first inputs
                     …   create an inclusive range between them
                 0 2⊤    encode into parts of 0 & 2
                ⊖        reverse the columns
               ⊥         decode from base 2
                         (this calculates (n+3×(n%2))/2)
             ×⍨          square that
      ⌊12÷⍨6+            divide by 12, round to the nearest integer
     ⊤                   encode in base 2
                         (this gives a binary matrix witht the required graph)
' ⎕'[                  ] convert 0s to ' ' and 1s to '⎕'

```

---
Tags: code-golf, graphical-output, sequence, binary
---


title: Be there or be square!

text:
# Question
Title: Be there or be square!
Everybody has heard of the phrase "be there or be square". So I thought it was time for a challenge about it.

## Input

You will take a full absolute directory address as text as input via STDIN or equivalent.

## Output

If the directory address exists and is valid, your program will move itself to that folder on your computer. If not, it will output via STDOUT or equivalent the following square:

```
+-+
| |
+-+

```

## Requirements

* Standard loopholes are disallowed.
* You may output a single trailing newline if unavoidable.
* Your program must produce no output if it has been moved.
* Your program must be able to run again wherever it has been moved to.

## Assumptions

* You may assume that the input is never empty.
* You may assume the directory never has a filename appended to the end.
* You may assume that the input directory is never the current one.
* You may assume you have permissions to write and execute everywhere.

This is , so shortest answer in bytes wins.

# Answer
> 2 votes
# Bash + coreutils, ~~43~~ 42 bytes

```
mv -t $1 $0 2> >(:)||echo -n '+-+
| |
+-+'

```

This avoids printing the trailing newline via the -n flag to echo.

I'm not quite sure what the OP means by allowing a trailing newline if it's "unavoidable".

If it's acceptable to include a trailing newline, change

```
echo -n '+-+

```

to

```
echo '+-+

```

and save 3 bytes, for 39 bytes total.

# Answer
> 7 votes
# PowerShell, ~~59~~ ~~62~~ ~~61~~ 60 bytes

```
$z=ls($d=$args)-di;('"+-+
| |
+-+"','mv b.ps1 "$d"')[$?]|iex

```

Try it online!

## Explanation

PowerShell's `Move-Item` cmdlet (`mv`) renames a file as well, so giving it a directory that doesn't exist as the destination just renames the file to that last component instead (as long as the parent exists), so that was no good.

I could use `Test-Path` to determine that the destination exists and is a directory, but it's too long `Test-Path $d -PathT C`.

So instead I'm using `Get-ChildItem` (`ls`) with the (shortened) `-Directory` parameter, and checking `$?` to see if it was successful. The output if there is any is assigned to `$z` so that it isn't seen.

That's done in the form of an array with 2 elements, then indexing into the array with the boolean value of `$?`, which will get coalesced to `0` or `1`, so the first array element is chosen if the destination directory doesn't exist, and second if it does.

The first array element is a string containing the box (quoted); newlines are allowed in strings, even when they're not heredocs. The second element is a string containing the move command.

The result of that array selection gets piped into `Invoke-Expression` (`iex`) to be executed. This is necessary because of I just leave the actual move command in the array, it gets executed no matter what (to populate the array), which defeats the purpose.

# Answer
> 5 votes
# Octave, ~~60~~ ~~57~~ 52 bytes

*8 bytes saved thanks to @Stewie*

```
if~movefile('f.m',input(''))disp("+-+\n| |\n+-+")end

```

This is a script that lives within a file called `f.m`. When run, it will prompt the user for the folder to move the file to. If the folder does not exist and the move operation fails, then `movefile` returns `false` (or `0`) otherwise it returns `true` (or `1`). If it's `false`, we display the string `"+-+\n| |\n+-+"`.

# Answer
> 4 votes
## Batch, 80 bytes

```
@if not "%1"=="" move %0 %1\>nul 2>nul&&%1\%~nx0||(echo +-+&echo ^| ^|&echo +-+)

```

Batch doesn't like it if you move the batch file as it's running, so by invoking `%1\%~nx0` (which is the new name of the batch file) Batch stops looking for the old batch file.

# Answer
> 4 votes
## Bash + coreutils, 54 bytes

```
if [ -d $1 ];then mv $0 $1;else echo "+-+
| |
+-+";fi

```

Simple enough. It does a test to see if the first argument exists, if it exists the program moves itself into the argument, else prints the square.

Does not work on Windows, however it works on Bash on Ubuntu on Windows / WSL. Does not take a drive letter, however I think that has been clarified to be OK.

This account is owned by Mendeleev.

# Answer
> 1 votes
# Python 3, 71 bytes

```
from shutil import*
try:move('f',input())
except:print("+-+\n| |\n+-+")

```

It must be in a file named `f`

Fairly simple. It tries to move itself to whatever directory is given to it on STDIN, and if an error occurs it prints the box.

# Answer
> 0 votes
## C 137 bytes

```
#include<dirent.h> g(char *f,char *z){DIR* d=opendir(z);if(d){strcat(z,f);rename(f,z);}else{puts("+-+");puts("| |");puts("+-+");}}

```

Ungolfed version:

```
#include<dirent.h>
g(char *f,char *z)
{
  DIR* d=opendir(z);
  if(d)
  {
    strcat(z,f);
    rename(f,z);
  }
  else
  {
    puts("+-+");
    puts("| |");
    puts("+-+");
  }
}

```

`f` accepts the filename and `z` accepts the directory name. Destination string is a concatenation of `z` and `f`. `rename()` is used to move the file to the new location.

The `main()` would look like this:

```
int main(int argc, char *argv[])
{
    g(argv[0]+2,argv[1]); // 1st arg is the Destination string
    return 0;
},

```

Can definitely shortened somehow!

# Answer
> 0 votes
# Ruby, 58+12 = 70 bytes

Uses flags `-nrfileutils`. Input is piped in from a file w/o newlines into STDIN.

```
FileUtils.mv$0,File.exist?($_)&&$_ rescue$><<"+-+
| |
+-+"

```

# Answer
> 0 votes
# Minecraft ComputerCraft Lua, 74 bytes

```
if fs.isDir(...)then fs.move("f",... .."f")else print("+-+\n| |\n+-+")end

```

Filename is hard-coded as "f". This runs on an in-game computer and runs relative to that computer's directory structure. Uses CC Lua's builtin `fs` API.

Ungolfed:

```
local tArgs = { ... }      -- '...' is Lua's vararg syntax, similar to python's *args syntax
if fs.isDir(tArgs[1]) then -- Using '...' is like passing all args separately, extra args are usually ignored
    fs.move("file", tArgs[1] .. "file") -- '..' is Lua's string concatenation syntax
else
    print("+-+\n| |\n+-+") -- print the required output if the directory doesn't exist
end

```

# Answer
> 0 votes
# APL (Dyalog Unicode), 41 bytes

```
{⎕NEXISTS⍵:'f'⎕NMOVE⍨⍵,'f'⋄3 3⍴'+-+| |'}⎕

```

Try it online!

filename is hardcoded as `f`, in the current working directory.

---
Tags: code-golf, ascii-art, file-system
---


title: Bi-directional translator

text:
# Question
Title: Bi-directional translator
# Bi-directional translator

The challenge is to create a translator that can translate a `[a-zA-Z ]` string into another string according to the mappings below. The translator should also be able to translate translated text back into its normal form (hence *bi-directional*). Case doesn't have to be maintained and can be either lower/uppercase (or both lower and upper-cased) in the output, however your program should be able to handle either lower/uppercase strings.

Here is the specification of the mappings for this challenge:

```
-------------------
|Letter | Mapping |
-------------------
|   S   |    9    |
|   F   |    1    |
|   H   |    5    |
|   X   |    =    |
|   Z   |   {N}   |
|   M   |   --*   |
|   N   |   :)    |
|   G   |    ]    |
|   T   |    [    |
-------------------

```

Here are some example in/outputs: (*The " or ... or ..." obviously shouldn't be in your actual output, its just to demonstrate the possible outputs*)

```
> ABS
< AB9 or ab9 or Ab9 or aB9

> foo
< 1oo or 1OO or ...

> FIZZ BUZZ
> 1i{N}{N} bu{N}{N} or 1I{N}{N} BU{N}{N} or ...

> {n}[:)
< ztn or ZTN or ...

> bar
< bar or BAR or ...

```

The inputs will always be in `[a-zA-Z ]` or a "translated" string containing the mapped symbol, other symbols or characters outside wouldn't be inputted.

# Answer
# Retina 0.8.2, ~~70~~ ~~68~~ 57 bytes

```
.[}*]|\)

T`l`L
T`-{=519[]:NGTSF\HXZM`Ro
{
{N}
-
--*
:
:)

```

Try it online! Link includes test cases. Uppercases the result. Explanation:

```
.[}*]|\)

```

Remove the suffixes from `{N}`, `--*` and `:)` leaving their first character.

```
T`l`L

```

Uppercase everything.

```
T`-{=519[]:NGTSF\HXZM`Ro

```

Translate the first characters. The string is mapped to its reverse, so that `-` maps to `M` etc. and vice versa. The `H` is a special character and needs to be quoted. The `-` is normally a special character but placing it at the beginning avoids this.

```
{
{N}
-
--*
:
:)

```

Expand the `{`, `-` and `:` to the full strings again.
> 6 votes

# Answer
# JavaScript (ES6),  ~~118 113~~  109 bytes

```
s=>s.toUpperCase(A=[':)',...'NF1G]H5S9T[X=Z','{N}','M','--*']).replace(/[{-]..|:?./g,c=>A[A.indexOf(c)^1]||c)

```

Try it online!

### How?

Because the input is guaranteed to contain exclusively `[a-zA-Z]` and/or the special patterns, we can use the following minimal regular expression to match them all:

```
/[{-]..|:?./g
 [{-]..        // either "{" or "-" followed by 2 other characters
               // -> to match "{N}" or "--*"
        :?.    // or any character, preceded by an optional ":"
               // -> to match ":)" or any single character

```

Working on the uppercase version of the input, we look for the position of each matched pattern in the lookup array `A[]` and replace it with its counterpart, or leave it unchanged if it is not found (which may only happen for `ABCDEIJKLOPQRUVWY`).
> 6 votes

# Answer
# 05AB1E, 65 63 bytes

```
u"{N}"¬.:"--*"¬.:":)"¬.:"SFHXZMNGT[]:-{=519"Â‡"{-:N-)}*"3ιD€нs‡

```

Uses the same approach as Neil's answer. Probably not going to be too competitive among the golf answers, but there's definitely improvements to be made here (I'm still a novice with 05AB1E, especially with string manipulation).

Explanation:

```
u            uppercase the input

"{N}"        push '{N}'
     ¬       extract and push head ('{')
      .:     replace all {N} => {

"--*"        push '--*'
     ¬       extract and push head ('-')
      .:     replace all --* => -

":)"         push ':)'
    ¬        extract and push head (':')
     .:      replace all :) => :

"SFH...519"  push lookup string

Â            bifurcate (push a, reversed(a))
 ‡           transliterate input with lookup

             set up stack for reverse process
             to do { -> {N} ... etc

"{-:N-)}*"   push literal string
3ι           uninterleave by 3
  D          duplicate
   €         apply single function map
    н        extract first element
     s       swap
      ‡      transliterate

```

The bi-directional bit is achieved by transliterating with a bifurcated lookup string; each character that should be swapped is in the opposite position with the one it should be swapped with in the lookup string. The main problem (and potential savings) is that I repeat a lot of logic for the "{N}" -\> "{" ... part at the beginning as in the "{" -\> "N" ... part at the end. Originally, I thought transliterate could go both ways, so I was going to set up the stack carefully at the beginning, but I don't think transliterate likes it when there's a multi-character string in the list (it probably goes by character, rather than doing a replace all?).
> 6 votes

# Answer
# Perl 5 `-p`, ~~90~~, 88 bytes

```
$_=uc;s/.[}*]|://g;y/-{)SFHXGT915=][ZNM/MZN915=][SFHXGT{:-/;s/{/{N}/g;s/:/:)/g;s/-/--*/g

```

Try it online!

using the same algorithm as Neil's answer

saved 2 bytes removing the backslash before the opening brace, and removing the colon instead of closing parenthesis in `:)`
> 4 votes

# Answer
# Python 3, ~~189~~ ~~147~~ ~~127~~ 135 bytes

```
s=input().upper()
b=[*'915=][',':)','--*','{N}']
for k,v in zip(*['SFHXGTNMZ',b][::0>max(map(s.find,b))or-1]):s=s.replace(k,v)
print(s)

```

Try it online! If this were not codegolf the conditional should obviously be outside of the `for` rather than repeated at each iteration. What wouldn't we do for a few bytes...

* *saved 42 bytes by replacing the dict with two lists;*
* *saved 20 bytes thanks to ovs' `[::True or-1]` dark magic.*
* *added 8 bytes because of missing `.upper()`*
> 3 votes

# Answer
# Haskell, 186 bytes

```
import Data.Char
k="S 9 F 1 H 5 X = Z {N} M --* N :) G ] T [ "
v=words$k++map toLower k
w=v++reverse v
_!""=""
[]!(t:u)=t:w!u
(a:b:c)!s|n<-length a,take n s==a=b++w!drop n s|1<2=c!s
(w!)

```

Try it online!
> 2 votes

# Answer
# Python 3, <sup>~~226~~ ~~189~~</sup> 181 bytes

Saved a whopping 37 bytes thanks to ovs!!!
Saved 6 bytes thanks to Stef!!!

```
from re import*
def f(s,m="9 1 5 = --* :\) ] \[ {N}".split()):
 for t,r in zip(*(m,"SFHXMNGTZ")[::2*bool(search(f"({'|'.join(m)})",s,I))-1]):s=sub(t,r,s,0,I)
 return sub(r'\\','',s)

```

Try it online!

Will reverse the translation if any of the mappings are in the input.
> 0 votes

# Answer
# C (gcc), 333 bytes I'--\* e=ac\[ly 5al1 o1 9a\[a:) N

```
void f(char*i,char*o,int*a,int*e,char**c){int t=0;int s=0;char*p=0;while(i[0]){char x=e[(uint8_t)i[0]];if(x){int l;s=a[(s*23)+x-1];if((l=a[((s+1)*23)-1]))t=l;if(!p)p=i;if(s){i++;continue;}}s=0;if(t){if(t>9)o+=sprintf(o,c[t-10]);else o+=sprintf(o,c[t+8]);t=0;p=0;continue;}if(p){while(p<i){o[0]=p[0];o++;p++;}p=0;}o[0]=i[0];o++;i++;}}

```

Try it online!
> 0 votes

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


# Question
Title: Square root of a base 10 positive integer, digit by digit
It is possible (Wikipedia reference) to compute the square root of any number in a digit by digit fashion using a simple (I had learned it in primary school) algorithm.

**Challenge:**

* read a positive integer from the user, in base 10, no error check;
* compute the square root of that integer using a digit-by-digit algorithm (either Wikipedia's or any alternative you may devise);
* display the result, in base 10, with 30 digits after the decimal point (the result must be truncated at the last digit displayed).

**Restrictions:**

* no use of builtin or library *mathematical functions*;
* only arithmetic operations on integers (addition, subtraction, multiplication, division and module).

**Scores:**

the shortest correct implementation will be the winner.

---

My reference implementation (Python3, 781 bytes) follows:

```
from math import sqrt

num = input('Give me an integer, ')
n = '0'+num if len(num)%2 else num
couples = [int(''.join(digit for digit in tup))
               for tup in zip(*[iter(n)]*2)]

digits = []
n=0
rem = 0
for couple in couples:
    target = rem*100 + couple
    base = n*20
    for i in range(11):
        if (base+i)*i > target: break
    i = i-1
    digits.append(str(i))
    n = 10*n+i
    rem = target-(base+i)*i

digits.append('.')

for dec_digit in range(30):
    target = rem*100 + 0
    base = n*20
    for i in range(11):
        if (base+i)*i > target: break
    i = i-1
    digits.append(str(i))
    n = 10*n+i
    rem = target-(base+i)*i

print('From math.sqrt: sqrt(%s) = %r'%(num, sqrt(int(num))))
print('Digit by digit: sqrt(%s) = %s'%(num, ''.join(digits)))

```

---

Some test runs:

```
boffi@debian:~/.../tmp$ python3 sqrt.py
Give me an integer, 999901
From math.sqrt: sqrt(999901) = 999.9504987748144
Digit by digit: sqrt(999901) = 999.950498774814352559911780286530
boffi@debian:~/.../tmp$ python3 sqrt.py
Give me an integer, 4
From math.sqrt: sqrt(4) = 2.0
Digit by digit: sqrt(4) = 2.000000000000000000000000000000
boffi@debian:~/.../tmp$

```

# Answer
> 1 votes
# Python 3, 156 bytes

Uses the algorithm suggested by OP, since this is a golf of the reference implementation.

```
K=input()
n=len(K)%2*'0'+K+'0'*60
R=N=0
while n:
 a,b,*n=n;R=R*100+int(a+b);i=0;N*=20
 while~i*~N<=R:i+=1;N+=1
 print(i,end='.'[len(n)^60:]);R-=N*i;N=N+i>>1

```

Try it online!

---
Tags: code-golf, number, arithmetic
---


title: Fryer simulator

text:
# Question
Title: Fryer simulator
Your task is to model the effects of batter on pieces of food. Please add three layers of crust.

```
[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0], // in
 [0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
 [0,0,0,1,1,1,0,0,0,0,0,0,0,1,1,0,0,0],
 [0,0,0,0,1,0,0,0,0,0,0,0,1,1,0,1,0,0],
 [0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0],
 [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]
                   |
                   V
[[0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,2,1,2],
 [0,0,2,1,2,2,0,0,0,0,0,0,0,2,2,0,2,0],
 [0,0,2,1,1,1,2,0,0,0,0,0,2,1,1,2,0,0],
 [0,0,0,2,1,2,0,0,0,0,0,2,1,1,2,1,2,0],
 [0,0,0,0,2,0,0,0,0,0,0,0,2,1,1,1,2,0],
 [0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,0,0]]
                   |
                   V
[[0,0,3,2,3,3,0,0,0,0,0,0,0,3,3,2,1,2],
 [0,3,2,1,2,2,3,0,0,0,0,0,3,2,2,3,2,3],
 [0,3,2,1,1,1,2,3,0,0,0,3,2,1,1,2,3,0],
 [0,0,3,2,1,2,3,0,0,0,3,2,1,1,2,1,2,3],
 [0,0,0,3,2,3,0,0,0,0,0,3,2,1,1,1,2,3],
 [0,0,0,0,3,0,0,0,0,0,0,0,3,2,2,2,3,0]]
                   |
                   V
[[0,4,3,2,3,3,4,0,0,0,0,0,4,3,3,2,1,2], // out
 [4,3,2,1,2,2,3,4,0,0,0,4,3,2,2,3,2,3],
 [4,3,2,1,1,1,2,3,4,0,4,3,2,1,1,2,3,4],
 [0,4,3,2,1,2,3,4,0,4,3,2,1,1,2,1,2,3],
 [0,0,4,3,2,3,4,0,0,0,4,3,2,1,1,1,2,3],
 [0,0,0,4,3,4,0,0,0,0,0,4,3,2,2,2,3,4]]

```

A little visual aid:

```
body {
   background-color:#222;
   color:lightgray;
}
```

```
<pre>
[[<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>], // in
 [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>],
 [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>],
 [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>],
 [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>],
 [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>]]
                   |
                   V
[[<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:brown">2</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>],
 [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:gold">0</span>,<span style="color:brown">2</span>,<span style="color:gold">0</span>],
 [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>],
 [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:gold">0</span>],
 [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:brown">2</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:gold">0</span>],
 [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>]]
                   |
                   V
[[<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>],
 [<span style="color:gold">0</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>],
 [<span style="color:gold">0</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:gold">0</span>],
 [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>],
 [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>],
 [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:chocolate">3</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:gold">0</span>]]
                   |
                   V
[[<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>], // out
 [<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>],
 [<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>],
 [<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>],
 [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:red">1</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>],
 [<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:gold">0</span>,<span style="color:orange">4</span>,<span style="color:chocolate">3</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:brown">2</span>,<span style="color:chocolate">3</span>,<span style="color:orange">4</span>]]
</pre>
```

The input is a boolean matrix representing the fryer: 0 for the oil, 1 for the food. Your function or program should add the three layers as 2s, 3s, and 4s around the 1s, thus overwriting some of the 0s. Batter sticks horizontally and vertically (but not diagonally) to food of any shape or size, including donuts (food with holes) and crumbles (isolated food "pixels"), and is restricted to the boundaries of the fryer. Earlier layers of batter turn into crust and are not affected by later ones.

In other words, first you should replace all 0s that are in the von-Neumann neighbourhoods of 1s with 2s, then replace all 0s in the von-Neumann neighbourhoods of 2s with 3s, and finally replace all 0s in the von-Neumann neighbourhoods of 3s with 4s. Thus, the numbers 2,3,4 represent a quantity one greater than the Manhattan distance to the nearest 1-cell.

The fryer will be of size at least 3-by-3 and it will contain at least one piece of food. I/O is flexible - use a matrix format suitable for your language. Extra whitespace is allowed, shorter code desirable, loopholes forbidden.

More tests:

```
 [[0,0,1], // in
  [0,0,0],
  [0,1,0]]

 [[3,2,1], // out
  [3,2,2],
  [2,1,2]]

 -

 [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], // in
  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0,0,0,0],
  [1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0],
  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,1,1,0,0,1,0,0,0],
  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,1,0,0,1,0,0,0,0,0,0],
  [0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0],
  [0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0],
  [0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1],
  [0,0,1,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0],
  [0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
  [0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,1,0,0,0,0,0,0],
  [0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0]]

 [[3,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,3,3,4,3,3,3,4,4,4,3,2,1], // out
  [2,3,4,0,0,0,0,0,0,0,0,0,0,0,0,4,3,2,2,3,2,2,2,3,3,4,4,3,2],
  [1,2,3,4,0,0,0,0,0,0,0,0,0,0,4,3,2,1,1,2,1,1,1,2,2,3,4,4,3],
  [1,1,2,3,4,4,4,4,0,0,0,0,0,4,3,2,1,1,1,1,1,1,1,1,1,2,3,4,4],
  [2,2,3,4,4,3,3,3,4,0,0,0,4,3,2,1,1,2,1,1,1,1,1,2,2,1,2,3,4],
  [3,3,4,4,3,2,2,2,3,4,0,0,4,3,2,1,2,2,1,1,2,2,1,2,3,2,3,4,4],
  [4,4,4,3,2,1,1,1,2,3,4,0,4,3,2,1,1,2,1,2,3,3,2,2,2,3,4,3,3],
  [0,4,3,2,1,1,2,1,2,3,4,0,0,4,3,2,2,2,1,2,3,3,2,1,1,2,3,2,2],
  [4,3,2,1,1,2,2,1,2,3,4,0,0,0,4,3,3,3,2,3,4,4,3,2,2,3,2,1,1],
  [3,2,1,2,1,1,1,1,2,3,4,0,0,0,0,4,4,3,3,3,4,3,3,3,3,3,2,1,2],
  [4,3,2,1,2,2,1,2,3,4,0,0,0,0,0,4,3,2,2,2,3,2,2,3,4,4,3,2,3],
  [0,4,3,2,1,1,2,3,2,3,4,0,0,0,4,3,2,1,1,1,2,1,1,2,3,4,4,3,4],
  [0,0,4,3,2,2,3,2,1,2,3,4,0,0,0,4,3,2,2,2,3,2,2,3,4,4,3,2,3],
  [0,0,0,4,3,3,4,3,2,3,4,0,0,0,0,0,4,3,3,3,4,3,3,4,4,3,2,1,2],

```

A little visual aid:

```
body {
   background-color: #222;
   color:lightgray;
}
```

```

[[0,0,1], // in
  [0,0,0],
  [0,1,0]]

 [[3,2,1], // out
  [3,2,2],
  [2,1,2]]

 -

 [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], // in
  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0,0,0,0],
  [1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0],
  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,1,1,0,0,1,0,0,0],
  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,1,0,0,1,0,0,0,0,0,0],
  [0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0],
  [0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0],
  [0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1],
  [0,0,1,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0],
  [0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
  [0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,1,0,0,0,0,0,0],
  [0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0]]

 [[3,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,3,3,4,3,3,3,4,4,4,3,2,1], // out
  [2,3,4,0,0,0,0,0,0,0,0,0,0,0,0,4,3,2,2,3,2,2,2,3,3,4,4,3,2],
  [1,2,3,4,0,0,0,0,0,0,0,0,0,0,4,3,2,1,1,2,1,1,1,2,2,3,4,4,3],
  [1,1,2,3,4,4,4,4,0,0,0,0,0,4,3,2,1,1,1,1,1,1,1,1,1,2,3,4,4],
  [2,2,3,4,4,3,3,3,4,0,0,0,4,3,2,1,1,2,1,1,1,1,1,2,2,1,2,3,4],
  [3,3,4,4,3,2,2,2,3,4,0,0,4,3,2,1,2,2,1,1,2,2,1,2,3,2,3,4,4],
  [4,4,4,3,2,1,1,1,2,3,4,0,4,3,2,1,1,2,1,2,3,3,2,2,2,3,4,3,3],
  [0,4,3,2,1,1,2,1,2,3,4,0,0,4,3,2,2,2,1,2,3,3,2,1,1,2,3,2,2],
  [4,3,2,1,1,2,2,1,2,3,4,0,0,0,4,3,3,3,2,3,4,4,3,2,2,3,2,1,1],
  [3,2,1,2,1,1,1,1,2,3,4,0,0,0,0,4,4,3,3,3,4,3,3,3,3,3,2,1,2],
  [4,3,2,1,2,2,1,2,3,4,0,0,0,0,0,4,3,2,2,2,3,2,2,3,4,4,3,2,3],
  [0,4,3,2,1,1,2,3,2,3,4,0,0,0,4,3,2,1,1,1,2,1,1,2,3,4,4,3,4],
  [0,0,4,3,2,2,3,2,1,2,3,4,0,0,0,4,3,2,2,2,3,2,2,3,4,4,3,2,3],
  [0,0,0,4,3,3,4,3,2,3,4,0,0,0,0,0,4,3,3,3,4,3,3,4,4,3,2,1,2],

```

---

Thanks @Tschallacka for the visualizations.

# Answer
# Java 8, ~~271~~ ~~269~~ ~~247~~ ~~210~~ ~~202~~ ~~198~~ ~~193~~ ~~186~~ ~~179~~ ~~177~~ 176 bytes

```
a->{for(int l=a[0].length,i,t,I,J,n=0;++n<4;)for(i=a.length*l;i-->0;)for(t=4;a[I=i/l][J=i%l]==n&t-->0;)try{a[I-=t-t%3*t>>1][J-=t<2?1-2*t:0]-=a[I][J]<1?~n:0;}finally{continue;}}

```

Java and index-dependent matrices.. Not a good combination for an already verbose language to begin with..

Modifies the input-matrix instead of returning a new one.

-8 bytes thanks to *@ceilingcat*.

Try it online.

**Explanation:**

```
a->{                            // Method with integer-matrix parameter and no return-type
  for(int l=a[0].length,          //  Amount of columns
      i,t,I,J,                    //  Temp integers
      n=0;++n<4;)                 //  Loop `n` in range [1, 4):
    for(i=a.length*l;i-->0;)      //   Inner loop over the cells:
      for(t=4;a[I=i/l][J=i%l]     //    Set I,J to the current cell
                             ==n& //    If the value of the current cell is the current `n`:
              t-->0;)             //     Loop `t` downwards in the range (4, 0]:
        try{a                     //      Get the cell at a location relative to the current
             [I-=t-t%3*t>>1]      //       If `t` is 3:
                                  //        Take the cell above
                                  //       Else if `t` is 2:
                                  //        Take the cell below
             [J-=t<2?1-2*t:0]     //       Else if `t` is 0:
                                  //        Take the cell left
                                  //       Else if `t` is 1:
                                  //        Take the cell right
              -=a[I][J]<1?        //      And if this cell contains a 0:
                 ~n:0;            //       Fill it with `n+1`
        }finally{continue;}       //      catch and ignore ArrayIndexOutOfBoundsExceptions
                                  //      (saves bytes in comparison to manual checking)

```
> 11 votes

# Answer
# Stencil: 1 + 14 = 15 bytes

Command-line argument: `3`

Code: `s<×⌈/N:1+⌈/N⋄S`

Try it online!

`3` repeat the following transformation thrice:

`s` if whether the **s**elf is non-empty

`<` is less than

`×` the signum of

`⌈/N` the maximum of the von neuman**N** neighborhood

`:` then the new value becomes

`1+` one plus

`⌈/N` the maximum of the von neuman**N** neighborhood

else

`S` the value stays unmodified (**S**elf)
> 10 votes

# Answer
# Stencil *+CLA: `3`*, 11 bytes

```
s:S⋄+∘×⍨⌈/N

```

Try it online!

-1 thanks to Adám.
-2 thanks to a suggestion on another answer by ngn, which led me to convert this from **Stencil** to **Stencil *+CLA: `3`***.
> 8 votes

# Answer
# Python 3, 176 bytes

```
f=lambda a,i=-2,e=enumerate:a*i or f([[E or int((6*max(len(a)>i>-1<j<len(a[i])and a[i][j]for i,j in((r+1,c),(r-1,c),(r,c+1),(r,c-1))))**.5)for c,E in e(R)]for r,R in e(a)],i+1)

```

Try it online!

-18 bytes thanks to Mr. Xcoder
-20 bytes thanks to ovs
> 3 votes

# Answer
# Fortran 95, ~~309~~ ~~299~~ ~~294~~ ~~287~~ 269 bytes

```
subroutine f(a)
integer::a(:,:),s(2)
integer,allocatable::b(:,:)
s=shape(a)
allocate(b(0:s(1)+1,0:s(2)+1))
do1 k=0,3
do1 i=1,s(1)
do1 j=1,s(2)
b(i,j)=a(i,j)
if(any((/b(i+1,j)==k,b(i-1,j)==k,b(i,j+1)==k,b(i,j-1)==k/)).and.b(i,j)<1.and.k>0)b(i,j)=k+1
1 a(i,j)=b(i,j)
end

```

Fortran is not a golfing language.

* **Edit:** Saved 10 bytes by using weird old-fashioned do loops.
* **Edit 2:** Saved 5 bytes with `any()`
* **Edit 3:** Saved 7 bytes by removing an unnecessary `if`
* **Edit 4:** Saved 18 bytes by shrinking declaration of `s`
> 3 votes

# Answer
# JavaScript (ES6), ~~107~~ 105 bytes

```
f=(m,k=1)=>k<4?f(m.map((r,y)=>r.map((v,x)=>v|[-1,0,1,2].every(d=>(m[y+d%2]||0)[x+~-d%2]^k)?v:k+1)),k+1):m

```

### Test cases

```
f=(m,k=1)=>k<4?f(m.map((r,y)=>r.map((v,x)=>v|[-1,0,1,2].every(d=>(m[y+d%2]||0)[x+~-d%2]^k)?v:k+1)),k+1):m

draw = a => O.innerText += a.map(r => r.join(',')).join('\n')+'\n\n'

draw(f(
 [[0,0,1],
  [0,0,0],
  [0,1,0]]
))

draw(f(
 [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0,0,0,0],
  [1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0],
  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,1,1,0,0,1,0,0,0],
  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,1,0,0,1,0,0,0,0,0,0],
  [0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0],
  [0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0],
  [0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1],
  [0,0,1,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0],
  [0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
  [0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,1,0,0,0,0,0,0],
  [0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0]]
))
```

```

```

### Commented

```
f = (m, k = 1) =>                  // given the input matrix m[] and starting with k = 1
  k < 4 ?                          // if this is not the 4th iteration:
    f(                             //   do a recursive call:
      m.map((r, y) =>              //     for each row r[] at position y in m[]:
        r.map((v, x) =>            //       for each cell v at position x in r[]:
          v |                      //         if v is non-zero
          [-1, 0, 1, 2].every(d => //         or each neighbor cell at (x+dx, y+dy), with:
            (m[y + d % 2] || 0)    //           dy = d % 2 --> [-1, 0, 1, 0]
            [x + ~-d % 2]          //           dx = (d - 1) % 2 --> [0, -1, 0, 1]
            ^ k                    //           is different from k
          ) ?                      //         then:
            v                      //           let the cell unchanged
          :                        //         else:
            k + 1                  //           set the cell to k + 1
        )                          //       end of inner map()
      ),                           //     end of outer map()
      k + 1                        //     increment k for the next iteration
    )                              //   end of recursive call
  :                                // else:
    m                              //   stop recursion and return m[]

```
> 3 votes

# Answer
# Python 2, ~~146~~ 143 bytes

```
e=enumerate;l=input()
for y,f in e(l):
 for g,h in e(f):x=1+min(abs(y-a)+abs(g-c)for a,b in e(l)for c,d in e(b)if d==1);l[y][g]=x*(x<5)
print l

```

Try it online!
> 3 votes

# Answer
# Wolfram Language (Mathematica), 70 bytes

```
Mod[-MorphologicalTransform[#,#[[;;,2]]~Max~#[[2]]&,i]~Sum~{i,0,3},5]&

```

Try it online!
> 2 votes

# Answer
# APL (Dyalog Unicode), ~~34~~ ~~30~~ 23 bytes (abrudz/SBCS)

```
5|{5⊃,⍵+×⌊.⌊⍨⍵}⌺3 3⍣3∘-

```

Try it online!

-4 thanks to ngn.
> 2 votes

# Answer
# Retina, ~~93~~ ~~87~~ 84 bytes

```
1
4
3{m`(?<=^(.)*)0(?=4|.*¶(?>(?<-1>.)*)4|(?<=40|^(?(1)_)(?<-1>.)*4.*¶.*))
5
T`1-5`d

```

Try it online! Based on my answer to Kill it With Fire. Edit: Saved ~~6~~ 9 bytes thanks to @MartinEnder. Explanation:

```
1
4

```

Turn all the 1s into 4s.

```
3{

```

Repeat the rest of the program (at most) 3 times.

```
m`(?<=^(.)*)0(?=4|.*¶(?>(?<-1>.)*)4|(?<=40|^(?(1)_)(?<-1>.)*4.*¶.*))
5

```

Change all 0s adjacent to 4s into 5s.

```
T`1-5`d

```

Decrement all digits.

# Retina 0.8.2, ~~100~~ 94 bytes

```
1
3
{m`(?<=^(.)*)0(?=3|.*¶(?>(?<-1>.)*)3|(?<=30|^(?(1)_)(?<-1>.)*3.*¶.*))
4
T`1-4`d`^[^1]+$

```

Try it online! Explanation:

```
1
3

```

Turn all the 1s into 3s.

```
{

```

Repeat until the output does not change.

```
m`(?<=^(.)*)0(?=3|.*¶(?>(?<-1>.)*)3|(?<=30|^(?(1)_)(?<-1>.)*3.*¶.*))
4

```

Change all 0s adjacent to 3s into 4s.

```
T`1-4`d`^[^1]+$

```

If there are no 1s, decrement all digits.
> 1 votes

# Answer
# Clean, 157 bytes

```
import StdEnv,StdLib
t=transpose
z=zipWith
?n=n+sign n
f[0,h:l]=[?h:f[h:l]]
f[h,0:l]=[h,?h:f l]
f[h:l]=[h:f l]
f l=l
$l=z(z max)(t(map f(t l)))(map f l)

```

#

```
$o$o$

```

Try it online!

As a function literal.
> 1 votes

# Answer
# Perl, 63 bytes

Includes +3 for `0ap`

```
perl -0ape 's/0(?=$a|.{@{-}}$a)/$a+1/seg,$_=reverse while($a+=$|-=/
/)<4'

```

Give the input matrix as a block of digits **without** final newline., e.g.

```
001
000
010

```

for the 3x3 example. The output format is the same, a block of digits without final newline.

You can use a small script like

```
perl -i -0pe 's/\n*$//' <file>

```

to conveniently remove the final newlines from a file if that is hard to do in your favorite editor
> 1 votes

# Answer
# Ruby, ~~183~~ ~~158~~ 146 bytes

```
->a{3.times{|n|a.size.times{|i|r=a[i];r.size.times{|j|(r[j]<1&&[i>0?a[i-1][j]:0,a[i+1]&.at(j),j>0?r[j-1]:0,r[j+1]].include?(n+1))?r[j]=n+2:0}}};a}

```

Try it online!

Uses the obvious three-loop algorithm. ~~The fact that Ruby allows negative indexing into arrays means that there is no way (that I can see) around making the bounds checks.~~ Reaching beyond the boundary of an array returns `nil`, so only the negative bound checks are necessary. The check for `a[i+1][j]` just needs to use the safe access operator.

I also shaved off a few bytes by using a variable for `a[0]`.

-12 more bytes: Use `.times` instead of `(0...x).map` (in three places).

```
->a{
  3.times{|n|                    # For n from 0 to 2
    a.size.times{|i|             # For each row
      r=a[i];
      r.size.times{|j|           # For each column
        (r[j]<1 && [             # If the current cell is 0, and any of
            i>0 ? a[i-1][j] : 0, #     the cell to the north,
            a[i+1]&.at(j),       #     the cell to the south,
            j>0 ? r[j-1] : 0,    #     the cell to the west,
            r[j+1]               #     or the cell to the east
          ].include?(n+1)        #   are set to the previous value,
        ) ? r[j]=n+2 : 0         # Set this cell to the next value (or 0)
      }
    }
  };
  a                              # Return the modified array
}

```
> 1 votes

# Answer
# Python 3, 125 bytes

```
f=lambda a,n=2,e=enumerate:n//5*a or f([[r[j]or n*any([0,*r][j:j+3]+[0,*c][i:i+3])for j,c in e(zip(*a))]for i,r in e(a)],n+1)

```

Try it online!

Adaptation of my answer to Calculate COVID spread
> 1 votes

# Answer
# C (gcc), 217 bytes

```
for(w=2;w<=4;w++)for(y=0;y<H;y++)for(x=0;x<W;x++){if(o[y][x].v[w%2])continue;if(o[y][x].v[!(w%2)]){o[y][x].v[w%2]=o[y][x].v[!(w%2)];continue;}for(z=0;z<8;z++)if(o[y][x].a[z]&&o[y][x].a[z]->v[!(w%2)])o[y][x].v[w%2]=w;}

```

Try it online!
> 1 votes

---
Tags: code-golf, matrix
---


title: Output an Animated Trigonometry Circle

text:
# Question
Title: Output an Animated Trigonometry Circle
I want you to write a program that outputs a trigonometry circle like the one below. I also want you to animate this circle, having the sine line move along the circumference with the other lines move around it. **The minimum number of *unique* frames is 5. Any lower and your entry will not be counted.**

The lines you will need are:

* Sine (Both)
* Cosine (Both)
* Secant
* Cosecant
* Tangent
* Cotangent
* OA (on diagram)

## Edit: No longer a limit

This is a code golf challenge, but I want you to get your code to **below** my code which is written in BBC BASIC.

*Note:* I will remove this requirement if the challenge is too hard.

### My code: BBC BASIC - 185 bytes, 232 characters (Thanks Steve)

```
a=0:REPEAT:CLS:a+=0.005:CIRCLE600,500,300:s=300*SIN(a)+500:c=300*COS(a)+600:sc=300*1/COS(a)+600:cs=300*1/SIN(a)+500:MOVE600,500:DRAWc,s:DRAWc,500:DRAW600,500:DRAWsc,500:DRAWc,s:MOVE600,500:DRAW600,cs:DRAWc,s:DRAW600,s:WAIT 1:UNTIL0

```

# Answer
## Mathematica, 142 bytes

```
Graphics[{Circle[],Line/@{{{c=Cos@t,0},{c,s=Sin@t},{0,s}},{{0,0},{1/c,0},{0,1/s},{0,0},{c,s}}},},PlotRange->{r={-2,2},r}]~Animate~{t,0.01,2Pi}

```

I'm plotting for angles between `0.01` and  which conveniently skips any angles where one of the lines would become actually infinite. You can make a GIF from it by replacing `Animate` with `Table`, adding a step width of `0.1` say and then using `Export` on the result:

So I got a bit bored and thought I'd give the full-blown thing a go (with all lines and colours). I omitted the labels, because they are really annoying to position and just clutter everything up.

```
Animate[
  c = Cos@t;
  s = Sin@t;
  h = Sign@c;
  v = Sign@s;
  i = .1 h;
  j = .1 v;
  Graphics[{
    Thick,
    Circle[],
    Line /@ {{{c, -s}, {0, 0}, {c, s}}, {{-i, 0}, {-i, j}, {0,
        j}}, {{-i + c, 0}, {-i + c, j}, {c, j}}, {{c - .1 s,
        s + .1 c}, {1.1 c - .1 s, 1.1 s + .1 c}, 1.1 {c, s}}},
    Circle[{0, 0}, 0.1, {t, Round[t, Pi]}],
    Blue,
    Line /@ {{{0, 0}, {c, 0}}, {{0, s}, {c, s}}},
    Red,
    Line /@ {{{0, 0}, {0, s}}, {{c, 0}, {c, s}}},
    Darker@Green,
    Line[{{c, 0}, {h, 0}}],
    Cyan,
    Line[{{0, s}, {0, v}}],
    Lighter@Lighter@Magenta,
    Line[{{h, 0}, {1/c, 0}}],
    Darker@Darker@Green,
    Line[{{0, v}, {0, 1/s}}],
    Orange,
    Line[{{0, 1/s}, {c, s}}],
    Lighter@Brown,
    Line[{{1/c, 0}, {c, s}}],
    Gray,
    Line[{{c, 0}, {c, -s}}],
    Lighter@Gray,
    Line[{{c, s}, {h, 0}}],
    Lighter@Pink,
    Line /@ {{{-.45 h, 0}, {-.55 h, 0}}, {{-.45 h, 1/s}, {-.55 h,
        1/s}}},
    Arrowheads[{-.05, .05}],
    Arrow[{{-.5 h, 0}, {-.5 h, 1/s}}],
    Darker@Cyan,
    Line /@ {{{0, -.45 v}, {0, -.55 v}}, {{1/c, -.45 v}, {1/
         c, -.55 v}}},
    Arrow[{{0, -.5 v}, {1/c, -.5 v}}],
    Dashed,
    Black,
    Line[{{c, s}, 1.3 {c, s}}],
    Lighter@Pink,
    Line /@ {{{0, 0}, {-.5 h, 0}}, {{0, 1/s}, {-.5 h, 1/s}}},
    Darker@Cyan,
    Line /@ {{{0, 0}, {0, -.5 v}}, {{1/c, 0}, {1/c, -.5 v}}}
    }, PlotRange -> {r = {-2, 2}, r}],
  {t, 0.01, 2 Pi}
  ];

```

Enjoy!

And because this is still a code-golf question I golfed this down as well, to see how short I could get it. Currently, **719 bytes**:

```
Graphics[{Thick,Arrowheads@{-.05,.05},(z=Circle)[],(n=Line)/@{{p={c=Cos@t,s=Sin@t},o={0,0},{c,-s}},{-{i=.1(h=Sign@c),0},{-i,j=.1(v=Sign@s)},{0,j}},{{-i+c,0},{-i+c,j},{c,j}},{p+(q={-.1s,.1c}),1.1p+q,1.1p}},z[o,0.1,{t,Round[t,Pi]}],{e=Dashed,n[{p,1.3p}]},Blue,n/@{{o,a={c,0}},{b={0,s},p}},Red,n/@{{o,b},{a,p}},g=(d=Darker)@Green,n@{a,{h,0}},y=Cyan,n@{b,{0,v}},(l=Lighter)@l@Magenta,n@{{h,0},f={1/c,0}},d@g,n@{{0,v},u={0,1/s}},Orange,n@{u,p},l@Brown,n@{f,p},r=Gray,n@{a,{c,-s}},l@r,n@{p,{h,0}},l@Pink,n/@{q={{-.45h,0},{-.55h,0}},{u,u}+q},Arrow@{q={-.5h,0},u+q},{e,n/@{{o,q},{u,u+q}}},d@y,n/@{q={{0,-.45v},{0,-.55v}},{f,f}+q},Arrow@{q={0,-.5v},f+q},{e,n/@{{o,q},{f,f+q}}}},PlotRange->{r={-2,2},r}]~Animate~{t,0.01,2Pi,0.05}

```
> 16 votes

# Answer
# APL (dzaima/APL), 125 bytes

```
P5.size←2⌿300
t←0
g←P5.G
z←0 0
P5.draw←{g.bg¯1
g.circle 3⌿90
g.ln a←90×1+z,2 1○t
g.rect a
g.ln 90×1+z,(÷2○t),z,z,⍨÷1○t
t+←.1}

```

Try it online!

Displays it at the top left corner:

## Explanation

`P5.size←2⌿300` make a 300x300 canvas

`t←0` set angle \\$\theta=0.\\$

`g←P5.G` shorten drawing namespace

`z←0 0` save \[0,0\] in `z`

`P5.draw←{` Do the following repeatedly:

`g.bg¯1` Draw a white background

`g.circle 3⌿90` draw a circle of radius 90 at \\$(90, 90)\\$

`g.ln a←90×1+z,2 1○t` Line from \\$(90,90)\\$ to \\$(90cos\theta, 90sin\theta)\\$ for angle

`g.rect a` rectangle using the same coordinates

`g.ln 90×1+z,(÷2○t),z,z,⍨÷1○t` triangle with the points \\$(90, 90),(90,90/cos\theta),(90/sin\theta,90)\\$

`t+←.1` increment angle \\$\theta\\$
> 0 votes

---
Tags: code-golf, graphical-output, animation, trigonometry
---


title: Find the optimal pattern

text:
# Question
Title: Find the optimal pattern
Given a string **s** composed of lowercase letters, such as

```
aabaaababbbbaaba

```

and a positive integer **n**, such as `4`, output a length-**n** string **t** such that when **t** is repeated to the length of **s**, they have as many chars in common as possible. For the given example, the optimal output would be `aaba`, because it has thirteen chars in common with the target string:

```
s: aabaaababbbbaaba
t: aabaaabaaabaaaba (aaba)
   ^^^^^^^^  ^ ^^^^

```

and no possible **t** has more. However, for `aaaaaab`, there are two possible outputs: `aaaa` and `aaba`, which each have 6 chars in common with the target string:

```
s: aaaaaab
t: aaaaaaaa (aaaa)
   ^^^^^^

s: aaaaaab
t: aabaaaba (aaba)
   ^^ ^^^^

```

Either `aaaa` or `aaba` can be outputted, or both if you'd like. Note that **s** is not ever repeated; the trailing `a` in both repeated values of **t** is simply ignored.

## Test cases

```
Inputs -> Valid outputs
1 a -> a
1 aa -> a
2 aa -> aa
1 ab -> a b
2 ab -> ab
1 abb -> b
2 abb -> ab bb
2 ababa -> ab
2 abcba -> ab
2 aabbbbb -> bb  (ab is not a valid output here)
3 aababba -> aab abb
3 aababbaa -> aab
3 asdasfadf -> asf
3 asdasfadfsdf -> asf adf
2 abcdefghijklmnopqrstuvwxyzyx -> yx
2 supercalifragilisticexpialidocious -> ic ii
3 supercalifragilisticexpialidocious -> iri ili ioi
4 supercalifragilisticexpialidocious -> scii
5 supercalifragilisticexpialidocious -> iapic
2 eeeebaadbaecaebbbbbebbbbeecacebdccaecadbbbaceebedbbbddadebeddedbcedeaadcabdeccceccaeaadbbaecbbcbcbea -> bb be
10 bbbbacacbcedecdbbbdebdaedcecdabcebddbdcecebbeeaacdebdbebaebcecddadeeedbbdbbaeaaeebbedbeeaeedadeecbcd -> ebbbdbeece ebdbdbeece
20 aabbbaaabaaabaaaabbbbabbbbabbbabbbbbabbaaaababbbaababbbaababaaaabbaaabbaabbbabaaabbabbaaabbaaaaaaaba -> aabbbbaaabbabbbaabba

```

## Rules

* You may assume the input will only ever be a non-empty string of lowercase letters and a positive integer no greater than the length of the string.
* You may take the inputs in any standard format and in either order.
* You may output a single string, or more than one in the form of an array, separated by newlines or spaces, etc.
* Your code must finish for each test-case in less than 1 minute on any fairly modern computer.
* This is , so make your code as short as possible.

# Answer
# Jelly, 11 bytes

```
sZµṢŒrUṀṪµ€

```

Try it online!

Wasn't expecting to beat Dennis on this one, so tried to FGITW it (after trying several possibilities; there's more than one way to make 11). I came in shorter, much to my surprise.

Takes the string then the count as command-line arguments. Outputs on stdout.

## Explanation

```
sZµṢŒrUṀṪµ€
s            Split {the first input} into {the second input}-sized groups
 Z           Transpose
  µ      µ€  On each of the transposed groups:
   Ṣ           Sort it;
    Œr         Run-length encode it;
      U        Rearrange it to the form {count, letter};
       Ṁ       Take the largest element (i.e. largest count)
        Ṫ      Take the second element of the pair (i.e. just the letter)

```

This uses the insight that the letter in each position of the pattern must be the most common letter corresponding to that position. We can find the letters corresponding to a particular pattern via splitting into pattern-sized groups, and transposing. The main reason this solution is so long is that Jelly doesn't seem to have a short way to find the mode of a list (I made several attempts, but they're all at least six bytes long).

# Jelly, 10 bytes, based on @Dennis' solution

```
⁸ċ$ÞṪ
sZÇ€

```

Try it online!

This is a combination of @Dennis' solution and my own; there was a five-byte mode in that solution, which I stole for this solution. (I already had solutions based on `⁸ċ`, but couldn't get below six bytes with it; I hadn't thought of using `Þ`.)

## Explanation

`µ…µ€` and `Ç€` (with the  on the previous line) are both three bytes long (the latter needs a newline), and equivalent. Normally I use the former, but the latter's more flexible, as it allows you to use  to mention the argument.

This makes it possible to sort (`Þ`) by the number of occurrences in  (`⁸ċ`), then take the last element (), to find the mode in just five characters.
> 11 votes

# Answer
## Mathematica, 51 bytes

```
#&@@@Commonest/@(PadRight@Partition[#2,UpTo@#])&

```

Input and output are lists of characters.

Also based on the modes of the lines of the transpose. I believe they called the built-in for the mode of a list `Commonest` *solely* to spite code golfers.
> 10 votes

# Answer
# Python 3, ~~99, 73~~ 61 bytes

-12, thx to @Rod

```
lambda s,n:''.join(max(s,key=s[i::n].count)for i in range(n))

```

Same idea, but rewrote it to eliminate the import statement.

```
lambda s,n:''.join(max(s,key=lambda c:s[i::n].count(c))for i in range(n))

```

Original

```
from collections import*
lambda s,n:''.join(Counter(s[i::n]).most_common(1)[0][0]for i in range(n))

```

Explanation:

```
s[i::n]                  a slice of every nth character of s, starting at position i

Counter(s[i::n])         counts the characters in the slice
  .most_common()         returns a list of (character, count) pairs, sorted by decreasing count
    [0][0]               grabs the letter from the first pair (i.e., the most common letter
      for i in range(n)  repeat for all starting positions

''.join                  combines the most common letters into a single string

```
> 7 votes

# Answer
## Python 2, 106

Now it's a different answer! I was thinking about one(almost)-liner from the beggining. Now even shorter, based on zip usage by @Rod.

Thanks to @L3viathan and @Rod for clarification about using lambdas as answer

Try it online

```
lambda S,N:max(combinations(S,N),key=lambda s:sum(x==y for x,y in zip(S,s*len(S))))
from itertools import*

```

Explanation:

`combinations(S,N)` creates all combinations length N from characters of S

`max()` have argument `key` which takes as input function to use to compare elements

`lambda s:sum(x==y for x,y in zip(S,s*len(S)))` passed as such function

This lambda counts number of matching characters in list of tuples, produces by `zip(S,s*len(S))`

`s` \- one of combinations and it's multipled by `len(S)` which creates string that is guaranteed longer than S

`zip` creates tuples of characters of each string `S` and `s*len(S)` and ignores all characters that can't be matched (in case of one string longer than another)

So `max` chooses combination, that produce maximum sum
> 5 votes

# Answer
## JavaScript (ES6), ~~104~~ ~~101~~ 94 bytes

```
(n,s)=>s.replace(/./g,(_,i)=>[...s].map((c,j,a)=>j%n-i||(a[c]=-~a[c])>m&&(m++,r=c),m=r=``)&&r)

```

Saved 3 bytes twice thanks to @Arnauld. 97-byte solution that works with all non-newline characters:

```
(n,s)=>s.replace(/./g,(_,i)=>[...s].map((c,j)=>j%n-i||(o[c]=-~o[c])>m&&(m++,r=c),m=r=``,o={})&&r)

```

The previous 104-byte solution works with newline characters too:

```
(n,s)=>[...Array(n)].map((_,i)=>[...s].map((c,j)=>j%n-i||(o[c]=-~o[c])>m&&(m++,r=c),m=0,o={})&&r).join``

```
> 5 votes

# Answer
# Jelly, ~~12~~ 11 bytes

```
s@ZċþZMḢ$€ị

```

Try it online!

### How it works

```
s@ZċþZMḢ$€ị  Main link. Arguments: n (integer), s (string)

s@           Split swapped; split s into chunks of length n.
  Z          Zip/transpose, grouping characters that correspond to repetitions.
   ċþ        Count table; for each slice in the previous result, and each character
             in s, count the occurrences of the character in the group.
             This groups by character.
     Z       Zip/transpose to group by slice.
        $€   Map the two-link chain to the left over the groups.
      M        Find all maximal indices.
       Ḣ       Head; pick the first.
          ị  Index into s to retrieve the corresponding characters.

```
> 4 votes

# Answer
# Pyth, 11 bytes

```
meo/dNd.TcF

```

Takes input as `s,n` and outputs as a list of characters.

### Explanation

```
meo/dNd.TcF
         cFQ   Split s into chunks of length n.
       .T      Transpose.
m o/dNd        Sort characters in each string by frequency.
 e             Take the most common.

```
> 2 votes

# Answer
# Japt, ~~16~~ 15 bytes

*Saved 1 byte thanks to @obarakon*

```
Ç=VëUZ)¬ñ!èZ o

```

14 bytes of code + 1 byte for the `-P` flag. Try it online!

### Ungolfed and explanation

```
 Ç   =VëUZ)¬ ñ!èZ o
UoZ{Z=VëUZ)q ñ!èZ o}
                          Implicit: U = input number, V = input string
Uo                        Create the range [0...U).
  Z{               }      Map each item Z by this function:
      VëUZ                  Take every U'th char of V, starting at index Z.
    Z=    )                 Call the result Z.
           q                Split the result into chars.
             ñ!èZ           Sort each char X by the number of occurrences of X in Z.
                  o         Pop; grab the last item (the most common char).
                      -P  Join the results (array of most common chars) into a string.

```
> 2 votes

# Answer
# Python 2, 132 bytes

```
from itertools import*
p,k=input()
b=l=len(p)
for i in combinations(p,k):
 x=sum(x!=y for x,y in zip(p,i*l))
 if x<b:b,o=x,i
print o

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 17 bytes

```
Iôð«øvy{.¡é®èÙJðÜ

```

Try it online!

**Explanation**

```
Iô                 # split 2nd input in chunks of 1st input size
  ð«               # append a space to each
    ø              # zip
     vy            # for each y in the zipped list
       {           # sort the string
        .¡         # group into chunks of consecutive equal elements
          é        # sort by length
           ®è      # pop the last element (the longest)
             Ù     # remove duplicate characters from the string
              J    # join the stack into one string
               ðÜ  # remove any trailing spaces

```
> 1 votes

# Answer
# PHP, 245 Bytes

```
function p($c,$s,$r=""){global$a;if(($c-strlen($r)))foreach(str_split(count_chars($s,3))as$l)p($c,$s,$r.$l);else{for($v=str_pad("",$w=strlen($s),$r);$z<$w;)$t+=$v[$z]==$s[$z++];$a[$t][]=$r;}}p($argv[1],$argv[2]);ksort($a);echo join(" ",end($a));

```

Online Version

## Breakdown

```
function p($c,$s,$r=""){
    global$a;
    if(($c-strlen($r)))  # make permutation
        foreach(str_split(count_chars($s,3))as$l)
            p($c,$s,$r.$l); #recursive
    else{
        for($v=str_pad("",$w=strlen($s),$r);$z<$w;)
        $t+=$v[$z]==$s[$z++]; #compare strings
        $a[$t][]=$r; # insert value in array
    }
}
p($argv[1],$argv[2]); #start function with the input parameter
ksort($a); # sort result array
echo join(" ",end($a)); #Output

```
> 1 votes

# Answer
## Haskell, 84 bytes

```
import Data.Lists
f n=map(argmax=<<(length.).flip(filter.(==))).transpose.chunksOf n

```

Usage example:

```
f 10 "bbbbacacbcedecdbbbdebdaedcecdabcebddbdcecebbeeaacdebdbebaebcecddadeeedbbdbbaeaaeebbedbeeaeedadeecbcd"
"ebbbdbeece"

```

Split input string into chunks of length `n`, transpose and ffind for each sublist the most frequent element.
> 1 votes

# Answer
# Röda, 68 bytes

```
f s,n{seq 0,n-1|{|i|sort s/"",key={|c|x=s[i::n]x~=c,"";[#x]}|head}_}

```

Try it online!

It's a function that prints the output without trailing newline.

This was inspired by this answer.
> 1 votes

# Answer
# Husk, 9 bytes

```
►ȯΣz=¹¢Ṗ²

```

Try it online!

Zgarb-quality questions need a Zgarb language answer.

## Explanation

```
►ȯΣz=¹¢Ṗ²
     ¹ Ṗ² length n powerset of string
►ȯ        max by:
      ¢   repeating each subsequence infinitely
   z=¹    and check equality with the input
  Σ       sum the results
          this will return the most optimal pattern.

```
> 1 votes

# Answer
# Japt `-P`, 11 bytes

```
òV ÕËü ñÊ¬Ì

```

Try it

```
òV ÕËü ñÊ¬Ì     :Implcit input of string U & integer V
òV              :Partitions of U of length V
   Õ            :Transpose
    Ë           :Map
     ü          :  Group & sort
       ñ        :  Sort by
        Ê       :    Length
         ¬      :  Join
          Ì     :  Last character
                :Implicitly join & output

```
> 0 votes

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


title: Perimeter of Conway hexagon

text:
# Question
Title: Perimeter of Conway hexagon
## Background

Given a triangle \\$ABC\\$, extend its three sides by the opposite side length, as shown in the figure below. Then the six points surprisingly lie on a circle called the **Conway circle**, whose center coincides with the incenter (the center of incircle, the circle that is tangent to the three sides from the inside).

## Task

Given three side lengths \\$a,b,c\\$ of the triangle \\$ABC\\$, calculate the perimeter of the hexagon \\$A\_b B\_a B\_c C\_b C\_a A\_c\\$ (formed by the six points on the Conway circle).

The answer must be within `1e-6` relative error from the expected. You can assume the side lengths form a valid non-degenerate triangle.

The shortest code in bytes wins.

## Test cases

```
a   b   c         ans
---------------------
1   1   1    9.000000
2   2   3   20.399495
3   4   5   35.293155
6   7   12  65.799785
2.3 4.5 6.7 31.449770

```

# Answer
> 18 votes
# Python 3, ~~89 87 69~~ 68 bytes

*Thanks @xnor for finding a shorter expression, saving 1 byte!*

```
f=lambda a,b,c,n=3:n and(a+b+c)*(c*c/a/b-a/b-b/a+2)**.5+f(b,c,a,n-1)

```

Try it online!

A recursive function, takes in 3 sides of the triangle as input.

Recursion is used to repeats the function 3 times, each time with the positions of `a,b,c` swapped in order to calculate each of the 3 summands in the formula below.

### How

We can see that each side of the hexagon is the base of an isosceles triangle, whose vertex angle is an angle of the original triangle. For example:

* \\$C\_aC\_b\\$ is the base of \\$CC\_aC\_b\\$ \- an isosceles triangle with leg \\$c\\$ and vertex angle \\$\widehat{C}\\$.
* \\$A\_bB\_a\\$ is the base of \\$CA\_bB\_a\\$ \- an isosceles triangle with leg \\$a+b\\$ and vertex angle \\$\widehat{C}\\$.

Given the leg \\$l\\$ and vertex angle \\$\theta\\$ of an isosleces triangle, the base is calculated as: $$l\sqrt{2-2\cos{\theta}}$$ Consider 2 opposites side of the hexagon, says \\$C\_aC\_b\\$ and \\$A\_bB\_a\\$. Since their corresponding triangles have the same vertex angle, their total length is: $$c\sqrt{2-2\cos{\widehat{C}}}+(a+b)\sqrt{2-2\cos{\widehat{C}}}$$$$=(a+b+c)\sqrt{2-2\cos{\widehat{C}}}$$ Then the perimeter of the hexagon is the sum of 3 opposite pairs: $$(a+b+c)\left(\sqrt{2-2\cos{\widehat{A}}}+\sqrt{2-2\cos{\widehat{B}}}+\sqrt{2-2\cos{\widehat{C}}}\right)$$ The cosine of an angle can be calculated from the sides of the triangle: $$2-2\cos{\widehat{C}}=\frac{c^2-(a-b)^2}{ab}$$ Thus, the final formula for the hexagon's perimeter is: $$(a+b+c)\left(\sqrt{\frac{a^2-(b-c)^2}{bc}}+\sqrt{\frac{b^2-(a-c)^2}{ac}}+\sqrt{\frac{c^2-(a-b)^2}{ab}}\right)$$

# Answer
> 12 votes
# Python 3, 64 bytes

```
lambda*t:eval("+((-(%s-%s)**2+%s**2)/%s/%s)**.5"*3%(t*5))*sum(t)

```

Try it online!

Uses an adaptation of a formula by Surculose Sputum, written so that the variables `a,b,c` repeat in a cycle when the formula is read left to right.

```
+((-(a-b)**2+c**2)/a/b)**.5+((-(c-a)**2+b**2)/c/a)**.5+((-(b-c)**2+a**2)/b/c)**.5

```

This lets us insert the input values into the formula as literals by string interpolation on the tuple `(a,b,c)` repeated 5 times, and then call `eval` to evaluate the resulting expression.

---

# Python 3, 76 bytes

```
lambda a,b,c:sum((2-(a*a+b*b+c*c-2*x*x)*x/a/b/c)**.5*(a+b+c)for x in[a,b,c])

```

Try it online!

I took Surculose Sputum's formula and solution and wrote the three summands in a closer-to-symmetric form like:

$$(a+b+c)\sqrt{2-\frac{a^2+b^2-c^2}{ab}}$$

The idea is that we want the summand to be as symmetric in \\$a,b,c\\$ as possible so that we can iterate a single variable \\$x\\$ over \\$a,b,c\\$ to produce each summand.

To this end, we write the core term $$\frac{a^2+b^2-c^2}{ab}$$ as the somewhat clunky

$$\frac{a^2+b^2+c^2-2c^2}{abc}\cdot c$$

so that we can write it in this symmetric form:

$$\frac{a^2+b^2+c^2-2x^2}{abc}\cdot x$$

Substituting \\$x=a\\$, \\$x=b\\$, and \\$x=c\\$ gives the three respective summands.

Perhaps there's a better way to put this fraction into a near-symmetric form than doing so for the numerator and denominator individually. We can split it up as $$a/b+b/a-c^2/(ab)$$ but I don't see where to go from there.

# Answer
> 5 votes
# dc, 68 bytes

```
9k?scsbsa[lad*lblc-d*-lblc*/v]dsFxlalbsasblFxlalcsasclFx++lalblc++*p

```

Try it online!

Or check out all the test cases.

This is a direct implementation of Surculose Sputum's answer (the original iterative one), which is the type of formula that dc ("desk calculator") can be pretty good for!

**Explanation:**

```
9k     Set precision to 9 decimal places.
?      Read input line (push a, b, and c on the stack).
scsbsa Save the input numbers in registers a, b, and c.
[      Start a macro.
       This macro takes the values in registers a, b, and c,
       and computes the first square root in the formula,
       leaving that result on the stack, as follows:
  lad*   Push a^2.
  lblc-  Push b-c.
  d*     Replace b-c at the top of the stack with (b-c)^2.
  -      Replace the top 2 items on the stack with a^2-(b-c)^2.
  lblc*  Push b*c.
  /      Divide to compute the formula under the radical sign.
  v      Compute the square root.
]      End of macro.
dsFx       Save macro for later use under the name F, and also run it now.
lalbsasb   Swap registers a and b.
lFx        Call macro F to compute the second square root.
lalcsasc   Swap registers a and c.
lFx        Call macro F to compute the third square root.
++         Add the three square roots.
lalblc++   Compute a+b+c.
*          Multiply a+b+c by the sum of the square roots.
p          Print the result.

```

# Answer
> 5 votes
# Desmos, 1455 bytes

Try it online! Link is Desmos. Interactive! Click and drag triangle points.

Obviously this answer is not going for shortest, I just wanted to show off an interactive demo. The bytes score was calculated by taking the length of concatenating all of the LaTeX from each formula in the calculator used to compute the perimeter (formulas used for interactive components were not counted).

# Answer
> 2 votes
# 05AB1E, 15 bytes

*Port of Surculose Seputum's Python solution*

```
œεnÆy¦P/}ÌtO*O;

```

Try it online!

# Answer
> 2 votes
# Io, 104 bytes

Port of Surculose Sputum's answer.

```
f :=method(a,b,c,n,if(n!=0,(a+b+c)*(c*c/a/b-a/b-b/a+2)**.5+f(b,c,a,n-1),n))
g :=method(a,b,c,f(a,b,c,3))

```

Try it online!

# Answer
> 2 votes
# Wolfram Mathematica, 99 bytes

```
(#1+#2+#3)(Sqrt[(#1^2-(#2-#3)^2)/#2/#3]+Sqrt[(#2^2-(#1-#3)^2)/#1/#3]+Sqrt[(#3^2-(#1-#2)^2)/#1/#2])&

```

Try it online!

I am pretty sure that this code can be improved. But I wasn't able to wrap my head around it. So I just post this in the hope of learning something new from more experienced users.

# Answer
> 2 votes
# APL (Dyalog Extended), <sup>~~45~~</sup> 44 bytes

```
+/×{+/{a b c←⍵⋄√(a×a÷b×c)+2-(⊢+÷)b÷c}⌽∘⍵¨⍳3}

```

Try it online!

Bubbler has a 27 byte solution with a complete train, but I think it deserves it's own answer.

This is a port of Surculose Suptum's formula, simplified by Kevin Cruijssen.

-1 byte from dzaima.

# Answer
> 1 votes
# Java 8, 104 bytes

```
(a,b,c)->{double r=0,t,n=3;for(;n-->0;t=a,a=b,b=c,c=t)r+=(a+b+c)*Math.sqrt(c*c/a/b-a/b-b/a+2);return r;}

```

Iterative port of *@SurculoseSputum*'s Python answer, so make sure to upvote him!

Try it online.

**Explanation:**

```
(a,b,c)->{                  // Method with double as all three parameters and return-type
  double r=0,               // Result-sum, starting at 0
         t,                 // Temp-double
  n=3;for(;n-->0            // Loop 3 times:
          ;                 //   After every iteration:
           t=a,a=b,b=c,c=t) //    Rotate `a,b,c` to `b,c,a` respectively
    r+=                     //  Increase the result-sum by:
      (a+b+c)               //   The sum of `a,b,c`
      *Math.sqrt(           //   Multiplied by the square-root of:
         c*c                //    `c` squared
            /a/b            //    Divided by both `a` and `b`
         -a/b               //    Minus `a` divided by `b`
         -b/a               //    as well as `b` divided by `a`
         +2);               //    Plus 2
  return r;}                //  After the loop, return the result-sum

```

Or as a single formula:

$$p = (a+b+c)\sqrt{c^2\div a\div b-\frac{a}{b}-\frac{b}{a}+2}$$ $$+(a+b+c)\sqrt{a^2\div b\div c-\frac{b}{c}-\frac{c}{b}+2}$$ $$+(a+b+c)\sqrt{b^2\div c\div a-\frac{c}{a}-\frac{a}{c}+2}$$

# Answer
> 1 votes
# Charcoal, 24 bytes

```
Ｉ×ΣθΣＥθ₂⁻²∕×ι⁻ΣＸθ²⊗×ιιΠθ

```

Try it online! Link is to verbose version of code. Port of @xnor's formula. Explanation:

```
     Ｅθ                     Map over sides
              ΣＸθ²          Sum of sides squared
             ⁻              Subtract
                   ×ιι      Square of current side
                  ⊗         Doubled
           ×ι               Multiply by current side
          ∕           Πθ    Divide by product of sides
        ⁻²                  Subtract from 2
       ₂                    Square root
    Σ                       Take the sum
 ×                          Multiplied by
  Σθ                        Sum of sides
Ｉ                           Cast to string for implicit print

```

Unfortunately `SquareRoot` doesn't seem to vectorise so I have to do that inside the `Map` which makes it marginally less efficient.

# Answer
> 1 votes
# JavaScript (ES7), 62 bytes

Now a port of Surculose Sputum's answer.

```
f=(a,b,c,n)=>n^3&&(a+b+c)*(c*c/a/b-a/b-b/a+2)**.5+f(b,c,a,-~n)

```

Try it online!

---
Tags: code-golf, geometry, trigonometry
---