title: Visualizing Words

text:
# Question
Title: Visualizing Words
Given a word consisting of lowercase letters only, do the following:

1. For each letter, get the prime factorization of its position in the alphabet.
2. For each prime factor, *p*, draw a diamond of side length *p* and stick the letter in the middle of the diamond.
3. The biggest diamond is in the middle, subsequent smaller diamonds (from biggest to smallest) alternate between going to the bottom or top.

**Note:** For the letter **a** use a side-length of 1.

Example: **cat**

* **c**: 3 = 3
* **a**: 1 = 1
* **t**: 20 = 5\*2\*2

The diagram:

```
                 .
                . .
               . t .
                . .
                 .
                 .
                . .
   .           .   .
  . .         .     .
 .   .   .   .       .
.  c  . .a. .    t    .
 .   .   .   .       .
  . .         .     .
   .           .   .
                . .
                 .
                 .
                . .
               . t .
                . .
                 .

```

Example: **dog**

* **d**: 4 = 2\*2
* **o**: 15 = 5\*3
* **g**: 7 = 7

Diagram:

```
                         .
                        . .
           .           .   .
          . .         .     .
         .   .       .       .
  .     .     .     .         .
 . .   .       .   .           .
. d . .    o    . .      g      .
 . .   .       .   .           .
  .     .     .     .         .
  .      .   .       .       .
 . .      . .         .     .
. d .      .           .   .
 . .       .            . .
  .       . .            .
         .   .
        .  o  .
         .   .
          . .
           .

```

**-20% bonus** if your program outputs to a text file called "\[your-word\].txt". Then input a real word (or phrase, made lowercase with no spaces) that is at least **20 letters** long and no one else has chosen yet, and paste the output between a `<pre>` and a `</pre>` in your answer.

# Answer
# Matlab, ~~466~~ 393 - 20% = 314.4 bytes

Golfed: (Could save some more bytes, also because of @AndreasDeak's help!)

```
function q(W);function z=g(l,c);[x,y]=ndgrid(abs(-l:l));z=0*y;z(~x&~y)=c;z(x+y==l)=46;end;w=W-96;n=numel(w);R=n*26;C=1;A=zeros(2*R);for k=1:n;f=sort(factor(w(k)));C=C+max(f)+1;d=-1;r=R;for F=fliplr(f);v=-F:F;while norm(A(r+v,v+C));r=r+d;end;A(r+v,v+C)=g(F,W(k));d=-d;end;C=C+max(f);end;A=A(find(sum(A,2)),find(sum(A)));f=fopen([W,'.txt'],'w');for k=1:size(A,1);fprintf(f,[A(k,:),'\n']);end;end

```

It should work in Octave (opensource) too, but only with a lot of warnings. Use this version if you want to try it in octave (output to console, instead of file):

```
function q(W);function z=g(l,c);[x,y]=ndgrid(abs(-l:l));z=0*y;z(~x&~y)=c;z(x+y==l)=46;end;w=W-96;n=numel(w);R=n*26;C=1;A=zeros(2*R);for k=1:n;f=sort(factor(w(k)));C=C+max(f)+1;d=-1;r=R;for F=fliplr(f);v=-F:F;while norm(A(r+v,v+C));r=r+d;end;A(r+v,v+C)=g(F,W(k));d=-d;end;C=C+max(f);end;A=A(find(sum(A,2)),find(sum(A)));disp([A,'']);end

```

Ungolfed and explained:

```
function q(W)
function z=g(l,c) %get a square matrix for one prime factor
[x,y]=ndgrid(abs(-l:l));
z=0*y;
z(~x&~y)=c;    %character in the middle
z(x+y==l)=46;  %dots
end;
w=W-96;                %convert word to the corresponding indices
n=numel(w);
R=n*26;                %keeps track of the main row
C=1;                   %keeps track of the current column
A=zeros(2*R);          %make a 'canvas' matrix that is way to big
for k=1:n;
    f=sort(factor(w(k)));          %get all the factors of current character
    C=C+max(f)+1;                  %update current column
    d=-1;                          %search direction
    r=R;
    for F=fliplr(f);
        v=-F:F;
        while norm(A(r+v,v+C));    %go up or down until there is enough space to write the prime factor
            r=r+d;
        end;
        A(r+v,v+C)=g(F,W(k));     %insert all the prime factors
        d=-d;
    end;
    C=C+max(f);
end;
A=A(find(sum(A,2)),find(sum(A))); %truncate all the unneccessary padding
f=fopen([W,'.txt'],'w');     %write to file
for k=1:size(A,1);
    fprintf(f,[A(k,:),'\n']);
end;

end

```

The requested word: (And here as a file: (zoom out a lot): supercalifragilisticexpialidocious.txt)

```
                       .                                                                                .                                                                                .
                      . .                                                                                . .                                                                                . .
                     .   .                                                                                .   .                                                                                .   .
                    .     .                                                                                .     .                                                                                .     .
                   .       .                                                                                .       .                                                                                .       .
                  .         .                                                                                .         .                                                                                .         .
                 .           .                                                                                .           .                                                                                .           .
                .             .                                                                                .             .                                                                                .             .
               .               .                                                                                .               .                                                                                .               .
              .                 .                                                                                .                 .               .                                                                                .                 .
             .                   .                                                                                .                   .             . .                                                                                .                   .
            .                     .                                          .                .                    .                               .                  .                     .           . t .                               .                     .                                                                          .                     .
           .                       .              .         .               . .              . .                  . .            .                . .                .                       .           . .                               . .    .              . .                                                         .              .                       .
          .                         .            . .       . .             . r .            . l .                . r .          . .              . l .              .                         .           .                               . x .  . .            . l .                                                       . .            .                         .
         .                           .          .   .     . p .     .       . .              . .                  . .          .   .              . .              .                           .          .                        .       . .  . p .            . .                   .                        .          .   .          .                           .
        .                             .        .     .     . .     . .       .                .                    .          .     .              .              .                             .        . .                      . .       .    . .              .                   . .                      . .        .     .        .                             .
       .                               .      .       .     .     .   .      .      .         .      .      .      .         .       .      .      .      .      .                               .      .   .      .      .      .   .      .     .     .         .      .           .   .      .      .      .   .      .       .      .                               .
      .                                 .    .         .    .    .     .    . .    . .       . .    . .    . .    . .       .         .    . .    . .    . .    .                                 .    .     .    . .    . .    .     .    . .    .    . .       . .    . .    .    .     .    . .    . .    .     .    .         .    .                                 .
     .                                   .  .           .  . .  .       .  .   .  .   .  .  .   .  .   .  .   .  .   .  .  .           .  .   .  .   .  .   .  .                                   .  .       .  .   .  .   .  .       .  .   .  . .  .   .  .  .   .  .   .  . .  .       .  .   .  .   .  .       .  .           .  .                                   .
    .                  s                  ..      u      .. p ..    e    ..  r  ..  c  ..a..  l  ..  i  ..  f  ..  r  ..a..      g      ..  i  ..  l  ..  i  ..                  s                  ..    t    ..  i  ..  c  ..    e    ..  x  .. p ..  i  ..a..  l  ..  i  .. d ..    o    ..  c  ..  i  ..    o    ..      u      ..                  s                  .
     .                                   .  .           .  . .  .       .  .   .  .   .  .  .   .  .   .  .   .  .   .  .  .           .  .   .  .   .  .   .  .                                   .  .       .  .   .  .   .  .       .  .   .  . .  .   .  .  .   .  .   .  . .  .       .  .   .  .   .  .       .  .           .  .                                   .
      .                                 .    .         .    .    .     .    . .    . .       . .    . .    . .    . .       .         .    . .    . .    . .    .                                 .    .     .    . .    . .    .     .    . .    .    . .       . .    . .    .    .     .    . .    . .    .     .    .         .    .                                 .
       .                               .      .       .     .     .   .      .      .         .      .      .      .         .       .      .      .      .      .                               .      .   .      .      .      .   .      .     .     .         .      .     .     .   .      .      .      .   .      .       .      .                               .
        .                             .        .     .     . .     . .       .                .      .      .      .          .     .       .      .      .       .                             .        . .       .              . .       .    . .    .         .      .    . .     . .              .       . .        .     .        .                             .
         .                           .          .   .     . p .     .       . .              . .    . .    . .    . .          .   .       . .    . .    . .       .                           .          .       . .              .       . .  . p .  . .       . .    . .  . d .     .              . .       .          .   .          .                           .
          .                         .            . .       . .             .   .            . l .  .   .  . f .  .   .          . .       .   .  . l .  .   .       .                         .           .      .   .                    . x .  . .  .   .     . l .  .   .  . .      .             .   .      .           . .            .                         .
           .                       .              .         .             .  r  .            . .  .  i  .  . .  .  r  .          .       .  i  .  . .  .  i  .       .                       .           . .    .  i  .                    . .    .  .  i  .     . .  .  i  .  .      . .           .  i  .    . .           .              .                       .
            .                     .               .         .              .   .              .    .   .    .    .   .                    .   .    .    .   .         .                     .           . t .    .   .                      .     .   .   .       .    .   .         .   .           .   .    .   .          .               .                     .
             .                   .               . .       . .              . .                     . .           . .                      . .           . .           .                   .             . .      . .                       .    . .   . .              . .         .  o  .           . .    .  o  .        . .               .                   .
              .                 .               .   .     . p .              .                       .             .                        .             .             .                 .               .        .                       . .  . p .   .                .           .   .             .      .   .        .   .               .                 .
               .               .               .  u  .     . .                                                                                .               .                                                . x .  . .                                  . .                      . .        .  u  .               .               .
                .             .                 .   .       .                                                                                .             .                                                  . .    .                                    .                        .          .   .                 .             .
                 .           .                   . .                                                                                .           .                                                    .                                                                               . .                   .           .
                  .         .                     .                                                                                .         .                                                                                .                     .         .
                   .       .                                                                                .       .                                                                                .       .
                    .     .                                                                                .     .                                                                                .     .
                     .   .                                                                                .   .                                                                                .   .
                      . .                                                                                . .                                                                                . .
                       .                                                                                .                                                                                .

```
> 9 votes

# Answer
# Funciton, non-competitive, 29199 bytes

I enjoyed this challenge because it highlighted the sore lack of some very useful library functions. I will include all of those functions here (and in the byte count) because I wrote them after this challenge was posted.

**Full source in a single file**

# Explanation

As always, get a better rendering by executing `javascript:(function(){$('pre,code').css({lineHeight:5/4});})()` in your browser console.

## `ɹ`  Reverse

As you may or may not know, Funciton comes with a library full of functions for *lists*, which are values encoded in a single humongous integer, as well as a separate library for *lazy-evaluated sequences*, which use lambda expressions (anonymous functions) in order to be lazy. Of course there’s also a library for string handling functions.

For this challenge, I needed a function to reverse a string, and a function to reverse a lazy-evaluated sequence. Surprisingly, I only had one for lists — exactly the one I didn’t need. So here are the reverse functions for lazy sequences (`ɹ`) and for strings ():

```
              ╓───╖             ╔════╗ ┌────╖        ╓───╖
              ║ ɹ ║             ║ 21 ╟─┤ >> ╟──┐     ║ ⇄ ║
              ╙─┬─╜             ╚════╝ ╘═╤══╝  │     ╙─┬─╜      ┌──┐
          ┌─────┴─────┐                ┌─┴─╖   ├───────┴────────┤  │
        ┌─┴─╖ ┌───╖   │                │ ⇄ ║   │   ╔════╗ ┌───╖ │  │
      ┌─┤   ╟─┤ ɹ ╟─┐ │                ╘═╤═╝   │   ║ −1 ╟─┤ ≠ ╟─┴┐ │
      │ └─┬─╜ ╘═══╝ │ │                ┌─┴─╖ ┌─┴─╖ ╚════╝ ╘═╤═╝  │ │
      │   │   ┌───╖ │ │                │ ‼ ╟─┤ ? ╟──────────┤    │ │
      │   └───┤ ʬ ╟─┘ │                ╘═╤═╝ ╘═╤═╝  ╔═══╗ ┌─┴─╖  │ │
      │       ╘═╤═╝   │                ┌─┴─╖ ╔═══╗  ║ 0 ╟─┤ ≠ ╟──┘ │
      │ ╔═══╗ ┌─┴─╖   │              ┌─┤ ʃ ╟─╢ 1 ║  ╚═╤═╝ ╘═══╝    │
      └─╢ 0 ╟─┤ ? ╟───┘              │ ╘═╤═╝ ╚═══╝    │            │
        ╚═══╝ ╘═╤═╝                  │   └────────────┘            │
                │                    └─────────────────────────────┘

```

The lazy-sequences one uses `ʬ`, which is “append an element to the end of a lazy sequence”. The string one uses `ʃ` (substring) and  (string concatenate).

## Primes

Although I could have done prime factorization by just trying to divide *n* by all factors in order, I decided I wanted a library function that generates prime numbers. The following function takes an integer *n* and implements the Sieve of Eratosthenes to generate all prime numbers up to *n*. It does this as a lazy sequence, so it’ll generate only as many primes as you actually evaluate.

```
                                       ╓───╖
                                       ║ Ṗ ║
                                 ╔═══╗ ╙─┬─╜
                                 ║ 0 ║ ┌─┴─╖
                                 ╚═╤═╝ │ ♭ ║
                          ╔═══╗ ┌──┴─╖ ╘═╤═╝
                          ║ 2 ╟─┤ Ṗp ╟───┘
                          ╚═══╝ ╘══╤═╝
    ┌──────────────┐               │
    │              ├─────────────────────────────────────────┐
    │            ┌─┴─╖                                       │
    │          ┌─┤ · ╟────────────────────────────┐   ╓┬───╖ │
    │          │ ╘═╤═╝                            ├───╫┘Ṗp ╟─┤
    │          │   │           ╔═══╗ ┌────╖     ┌─┴─╖ ╙─┬──╜ │
    │          │   │           ║ 1 ╟─┤ >> ╟─────┤ · ╟───┴─┐  │
    │          │   │  ┌───╖    ╚═══╝ ╘══╤═╝     ╘═╤═╝     │  │
    │          │ ┌─┴──┤ ♯ ╟─────┐    ┌──┴─╖ ┌───╖ │       │  │
    │          │ │    ╘═══╝ ┌─┐ │ ┌──┤ Ṗp ╟─┤ ♭ ╟─┴─┐     │  │
    │          │ │          ├─┘ └─┤  ╘══╤═╝ ╘═══╝ ┌─┘     │  │
    │          │ │        ╔═╧═╕ ┌─┴─╖ ┌─┴─╖     ┌─┴─╖     │  │
    │          │ └────────╢   ├─┤ · ╟─┤ ? ╟─────┤ · ╟─┐   │  │
    │          │ ┌───╖    ╚═╤═╛ ╘═╤═╝ ╘═╤═╝     ╘═╤═╝ │   │  │
    │        ┌─┴─┤ ♭ ╟─┐ ┌──┴─╖   │   ┌─┴─╖       │   │   │  │
    │        │   ╘═══╝ └─┤ Ṗp ╟───┘ ┌─┤ ? ╟───────┘   │   │  │
    │ ┌───╖  │  ╔════╗   ╘══╤═╝     │ ╘═╤═╝           │   │  │
  ┌─┴─┤ ÷ ╟──┘  ║ −1 ║   ┌──┴─╖   ╔═╧═╗ │            ┌┴┐  │  │
  │   ╘═╤═╝     ╚══╤═╝ ┌─┤ >> ╟─┐ ║ 0 ║              └┬┘  │  │
  │   ┌─┴─╖ ┌────╖ │   │ ╘════╝ │ ╚═══╝               │   │  │
  │   │ × ╟─┤ << ╟─┘ ┌─┴─┐    ╔═╧═╗                   │   │  │
  │   ╘═╤═╝ ╘══╤═╝  ┌┴┐ ┌┴┐   ║ 1 ╟───────────────────┴─┐ │  │
  └─────┘     ┌┴┐   └┬┘ └┬┘   ╚═══╝                     ├─┘  │
              └┬┘    │   └──────────────────────────────┘    │
             ┌─┴─╖ ┌─┴──╖                                    │
             │ ÷ ╟─┤ << ╟─┐                                  │
             ╘═╤═╝ ╘════╝ ├──────────────────────────────────┘
              ┌┴┐         │
              └┬┘         │
      ╔════╗ ┌─┴──╖       │
      ║ −1 ╟─┤ << ╟───────┘
      ╚════╝ ╘════╝

```

The helper function, `Ṗp`, takes:

* A running counter which just keeps decrementing until it reaches 0.
* The sieve, which has a bit set for each number that is already known to be not-prime. Initially, the least significant bit represents the number 2, but we shift this right with each iteration.
* A number *n* which indicates what number is represented by the sieve’s lowest bit; this is incremented with every iteration.

At each iteration, if the sieve’s lowest bit is 0, we’ve found a prime *n*. We then use the formula I already described in Fill the rows, columns, and diagonals of an NxN grid to set every *n*-th bit in the sieve before moving to the next iteration.

## Prime factorization

```
                             ╓───╖
                             ║ Ḟ ║
                             ╙─┬─╜
                       ┌───────┴──────┐
                       │ ┌───╖ ┌────╖ │
                       └─┤ Ṗ ╟─┤ Ḟp ╟─┘
                         ╘═══╝ ╘═╤══╝
                                 │
               ┌────────────────────────────────────────────┐
               │                                     ╓┬───╖ │
       ┌───────┴─┐     ┌───────────────────────┐   ┌─╫┘Ḟp ╟─┘
       │ ╔═══╗ ┌─┴─╖ ┌─┴─╖ ┌───┐ ┌────╖      ┌─┴─╖ │ ╙────╜
       │ ║ 0 ╟─┤   ╟─┤ · ╟─┘┌┐ └─┤ Ḟp ╟──┐ ┌─┤ · ╟─┴──┐
       │ ╚═══╝ └─┬─╜ ╘═╤═╝  └┤   ╘═╤══╝  ├─┘ ╘═╤═╝    │
       │       ┌─┴─┐ ┌─┴─╖ ╔═╧═╕ ┌─┴─╖ ┌─┴─╖ ┌─┴──╖ ┌─┴─╖
       │       │   └─┤ · ╟─╢   ├─┤ ? ╟─┤ · ╟─┤ ÷% ╟─┤ · ╟─┐
       │       │     ╘═╤═╝ ╚═╤═╛ ╘═╤═╝ ╘═╤═╝ ╘═╤══╝ ╘═╤═╝ │
       │       │    ┌──┴─╖   │   ┌─┴─╖ ┌─┴─╖   └──────┘   │
       │       │    │ Ḟp ╟───┘ ┌─┤ ? ╟─┤ ≤ ║              │
       │     ┌─┴─╖  ╘══╤═╝     │ ╘═╤═╝ ╘═╤═╝              │
       └─────┤ · ╟─────┘     ╔═╧═╗ │   ╔═╧═╗              │
             ╘═╤═╝           ║ 0 ║     ║ 2 ║              │
               │             ╚═══╝     ╚═══╝              │
               └──────────────────────────────────────────┘

```

This is fairly straight-forward. Just iterate through the primes up to *n* and see which ones divide *n*. If one does divide *n*, remember to carry on with the *same* prime so that we return it multiple times if it divides *n* multiple times. This returns the empty sequence for any number less than 2.

## Generate a diamond

This function generates a single diamond given a character and a radius. It only uses the character to place it in the center of the diamond.

```
                                   ┌───╖
             ┌─────────────────────┤ ♯ ╟───────────┬─────────┐
             │ ┌───╖ ╔═══╗   ┌───┐ ╘═══╝           │         │
             └─┤ ♫ ╟─╢ 0 ║   │ ┌─┴─╖               │         │
               ╘═╤═╝ ╚═══╝   │ │ ʭ ╟───┐           │         │
               ┌─┴─╖   ┌─────┘ ╘═╤═╝   │           │         │
               │ ɱ ╟───┤ ┌───╖ ┌─┴─╖ ╔═══╗   ╓───╖ │         │
               ╘═╤═╝   └─┤ ɹ ╟─┤ ʓ ╟─╢ 1 ║ ┌─╢ ◇ ╟─┤         │
                 │ ╔═══╗ ╘═══╝ ╘═══╝ ╚═══╝ │ ╙───╜ │         │
                 │ ║ 0 ║                   │     ┌─┴─╖       │
                 │ ╚═╤═╝                   │     │ ♭ ║       │
               ╔═╧═╕ │   ╔════╗            │     ╘═╤═╝       │
           ┌───╢   ├─┘ ┌─╢ 21 ║          ┌─┴─╖   ┌─┴─╖     ┌─┴─┐
           │   ╚═╤═╛   │ ╚════╝ ┌────────┤ · ╟───┤ · ╟─┐ ┌─┴─╖ │
           │   ┌─┴─╖ ┌─┴──╖ ┌───┘        ╘═╤═╝   ╘═╤═╝ ├─┤ = ║ │
           │ ┌─┤ ‼ ╟─┤ >> ║ │              │     ┌─┴─╖ │ ╘═╤═╝ │
           │ │ ╘═══╝ ╘═╤══╝ │              │   ┌─┤ ? ╟─┘   │   │
           │ │   ┌───╖ │ ┌──┘              │   │ ╘═╤═╝     │   │
           │ └─┬─┤ ⇄ ╟─┘ │     ┌─────┐     │   │ ┌─┴─╖     │   │
           │   │ ╘═══╝ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ └─┤ · ╟──┬──┘   │
           │   └───────┤ · ╟─┤ ? ╟─┤ · ╟─┤ ‼ ║   ╘═╤═╝  │      │
           │           ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝   ┌─┴─╖  │      │
           │             └─────┘     └─┬───┘ ┌───┤ … ║  │      │
           │               ┌─────┐     │     │   ╘═╤═╝  │      │
           │            ╔══╧═╗ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ ╔═╧══╗ │      │
           │            ║ 32 ║ │ … ╟─┤ ‼ ╟─┤ ‼ ║ ║ 32 ║ │      │
           │            ╚════╝ ╘═╤═╝ ╘═══╝ ╘═╤═╝ ╚════╝ │      │
           │                   ┌─┴─╖       ╔═╧══╗       │      │
           │               ┌───┤ − ╟───┬─┐ ║ 46 ║       │      │
           │             ┌─┴─╖ ╘═══╝   │ │ ╚════╝       │      │
           └─────────────┤ · ╟─────────┘ └──────────────┘      │
                         ╘═╤═╝                                 │
                           └───────────────────────────────────┘

```

This makes heavy use of lazy sequences. Here’s how it works:

* Generate the sequence of integers from 0 to *r* (inclusive).
* For each such integer *α*, generate a string consisting of (*r**α*) spaces (), followed by a dot, followed by *α* spaces — unless *α* = *r*, in which case generate one fewer space and append the letter. We now have the top-left quarter of the diamond.
* To each of these strings, append another copy of the same string, but with the characters reversed () and then the first character removed (`>> 21`). We now have the top half of the diamond.
* Take this sequence and append to it the same sequence, but reversed (`ɹ`) and with the first element removed (`ʓ`). We now have the whole diamond.

Now we have the strings that make up the diamond, but we need a little more information. We need to know where the vertical middle of the diamond is. Initially this is of course *r*, but once we’ve appended other diamonds to the top and bottom of this, we will need to keep track of the position of the “middle” diamond so that we can vertically align the other stacks of diamonds correctly. The same goes for the horizontal extent of the diamond (need that when appending diamonds to the top and bottom). I also decided to keep track of the letter; I need that because otherwise the function  (which we get to in the next section) would have to have four parameters, but Funciton allows only three.

```
                             ┌─────────────────┐
                             │  ╓───╖          │
                             ├──╢ ◆ ╟──┐       │
                             │  ╙───╜  │       │
                             │   ┌─────┴───┐   │
                           ┌─┴─╖ │ ┌───╖ ┌─┴─╖ │
                         ┌─┤ · ╟─┴─┤ › ╟─┤ › ║ │
                         │ ╘═╤═╝   ╘═╤═╝ ╘═╤═╝ │
                         │ ┌─┴─╖     │   ┌─┴─╖ │
                         │ │ ◇ ╟─────────┤ › ╟─┘
                         │ ╘═╤═╝         ╘═══╝
                         └───┘

```

We use the list API ( adds elements to the front of a list) to create a structure containing \[*x*, *y*, *c*, *q*\], where *x* is the x-coordinate of the horizontal center of the diamond, *y* is the y-coordinate of the baseline, *c* is the letter and *q* is the lazy sequence of strings. This structure will be used to contain all of the intermediate stages from now on.

## Append diamonds vertically

This function takes an existing diamond stack, a radius, and a boolean indicating whether to add the new diamond to the top (true) or bottom (false).

```
                 ┌─────────────────────────────────────────────────┐
               ┌─┴─╖         ┌───────────────────────────┐ ┌───╖ ┌─┴─╖
           ┌───┤ · ╟─────────┘ ╔═══╗ ┌───────────────┐   ├─┤ ‹ ╟─┤ ‹ ║
           │   ╘═╤═╝           ║ 1 ║ │ ╓───╖         │   │ ╘═╤═╝ ╘═╤═╝
           │     │             ╚═╤═╝ └─╢ ⬗ ╟─┐       │ ┌─┴─╖ │   ┌─┴─╖
           │     │ ┌───╖ ┌───╖ ┌─┴──╖  ╙─┬─╜ │       └─┤ · ╟─┘ ┌─┤ ‹ ╟─┐
           │   ┌─┴─┤ + ╟─┤ ♯ ╟─┤ << ║    │   │         ╘═╤═╝   │ ╘═══╝ │
           │   │   ╘═╤═╝ ╘═══╝ ╘═╤══╝    │ ┌─┴─╖         │     │       │
           │   │   ┌─┴─╖         └───────┴─┤ · ╟───┐   ┌─┴─╖   │       │
           │   └───┤ ? ╟─┐                 ╘═╤═╝ ┌─┴───┤ · ╟─┐ │       │
           │       ╘═╤═╝ ├───────────────────┘   │     ╘═╤═╝ │ │       │
           │ ┌───╖ ┌─┴─╖ │               ┌─────┐ │ ┌───╖ │   │ │       │
           └─┤ › ╟─┤ › ║ │       ┌───╖ ┌─┴─╖   │ └─┤ − ╟─┘   │ │       │
             ╘═╤═╝ ╘═╤═╝ │     ┌─┤ ‼ ╟─┤ ‼ ║   │   ╘═╤═╝     │ │       │
               │   ┌─┴─╖ │     │ ╘═╤═╝ ╘═╤═╝ ┌─┴─╖ ┌─┴─╖     │ │       │
               ┌───┤ · ╟─┘     │ ┌─┴─╖   ├───┤ · ╟─┤ … ║     │ │       │
     ┌───┐     │   ╘═╤═╝       └─┤ · ╟───┘   ╘═╤═╝ ╘═╤═╝     │ │       │
     │ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖         ╘═╤═╝         │  ╔══╧═╗     │ │       │
     │ │ ʭ ╟─┤ ? ╟─┤ › ╟─┐ ╔═══╗ ╔═╧═╕         │  ║ 32 ║     │ │       │
     │ ╘═╤═╝ ╘═╤═╝ ╘═══╝ │ ║ 0 ╟─╢   ├─────────┘  ╚════╝     │ │       │
     │ ┌─┘   ┌─┴─╖       │ ╚═══╝ ╚═╤═╛                       │ │       │
     │ └─┬───┤ ʭ ╟─┐   ┌─┴─╖     ┌─┴─╖                       │ │       │
     │ ┌─┴─╖ ╘═══╝ ├───┤ · ╟─────┤ ɱ ║                       │ │       │
     └─┤ · ╟───────┘   ╘═╤═╝     ╘═╤═╝                       │ │       │
       ╘═╤═╝             │       ┌─┴─╖                       │ │       │
         │               └─────┬─┤ ◇ ╟───────────────────────┘ │       │
         │                     │ ╘═══╝                       ┌─┴─╖     │
         │                     └─────────────────────────────┤ · ╟─────┘
         │                                                   ╘═╤═╝
         └─────────────────────────────────────────────────────┘

```

This is fairly straight-forward too; use  to unpack the structure; use  to generate the new diamond; use `ɱ` (map) to add spaces to the beginning and end of each string in the new diamond so that it all has the same width; append (`ʭ`) the new strings onto the old (if bottom) or the old onto the new (if top); and finally use  to construct the structure containing all the new values. In particular, if we are appending to the bottom, *y* doesn’t change, but if we are appending to the top, *y* must increase by `♯(r << 1)` (*r* is the radius of the new diamond).

## Concatenate stacks horizontally

This is the biggest function of them all. I won’t deny that it was fairly fiddly to get this right. It takes two stacks and concatenates them horizontally while respecting the correct vertical alignment.

```
                           ┌──────────────────────────────────┬───────────────────────┐
                           │     ┌──────────────────┐       ┌─┴─╖                   ┌─┴─╖
                           │     │    ┌───────────┐ └───────┤ · ╟───┬───────────────┤ · ╟─────────────┐
                           │     │  ┌─┴─╖         │         ╘═╤═╝   │               ╘═╤═╝             │
                           │     │  │ ‹ ╟───┐     │         ┌─┴─╖ ┌─┴─╖               │               │
                           │     │  ╘═╤═╝ ┌─┴─╖   └─────────┤ · ╟─┤ · ╟─────────┐     │               │
                           │     │    ├─┐ │ ‹ ╟───┐         ╘═╤═╝ ╘═╤═╝         │     │               │
                           │     │    └─┘ ╘═╤═╝ ┌─┴─╖ ╓───╖ ┌─┴─╖   │           │     │               │
                           │     │          │   │ ‹ ╟─╢ ❖ ╟─┤ ‹ ║   │           │     │               │
                           │     │          │   ╘═╤═╝ ╙───╜ ╘═╤═╝ ┌─┴─╖ ┌─┐     │     │               │
                           │     │          │     │           └───┤ ‹ ║ └─┤     │     │               │
                           │     │          │     │               ╘═╤═╝ ┌─┴─╖   │     │               │
                           │     │          │     │                 └───┤ ‹ ║   │     │               │
                           │     │          │     └─────────────────┐   ╘═╤═╝   │     │               │
                           │     │          │                     ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖             │
                           │     │          │      ┌──────────────┤ · ╟─┤ · ╟─┤ · ╟─┤ · ╟──────┐      │
                           │     │          └──────┤              ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝      │      │
                           │   ┌─┴─╖             ┌─┴─╖            ┌─┴─╖   │     │     │        │      │
                           │ ┌─┤ · ╟─────────────┤ · ╟────────────┤ · ╟───┘     │     │        │      │
                           │ │ ╘═╤═╝             ╘═╤═╝            ╘═╤═╝         │     │        │      │
                           │ │   │                 │         ┌────╖ │         ┌─┴─╖   │        │      │
       ╔═══╗ ┌────╖        │ │   │                 │       ┌─┤ << ╟─┴─────────┤ · ╟─┐ │        │      │
       ║ 1 ╟─┤ << ╟────────┘ │   │                 │       │ ╘═╤══╝           ╘═╤═╝ │ │        │      │
       ╚═══╝ ╘═╤══╝ ╔════╗   │   │               ┌─┴─╖     │ ┌─┴─╖              │   │ │     ┌──┴──┐   │
             ┌─┴─╖  ║ 32 ╟─┐ │   │ ┌─────────────┤ · ╟───┐ │ │ ♯ ║              │   │ │   ┌─┴─╖ ┌─┴─╖ │
             │ ♯ ║  ╚════╝ │ │   └─┤ ┌───╖       ╘═╤═╝   │ │ ╘═╤═╝ ┌───╖ ╔════╗ │   │ │ ┌─┤ ? ╟─┤ < ║ │
             ╘═╤═╝   ┌───╖ │ │     └─┤ − ╟─────────┴─┐   │ │   └───┤ … ╟─╢ 32 ║ │   │ │ │ ╘═╤═╝ ╘═╤═╝ │
               └─────┤ … ╟─┘ │       ╘═╤═╝         ┌─┴─╖ │ └───┐   ╘═╤═╝ ╚════╝ │   │ │ │ ┌─┴─╖   ├───┘
                     ╘═╤═╝   │ ┌───╖ ┌─┴─╖ ┌───────┤ · ╟─┴─┐ ╔═╧═╗ ┌─┴─╖ ┌──────┘   │ │ └─┤ · ╟───┘
                       │   ┌─┴─┤ ʭ ╟─┤ ȶ ║ │ ┌───╖ ╘═╤═╝   │ ║ 1 ║ │ ⁞ ║ │ ┌────────┘ │   ╘═╤═╝
                     ┌─┴─╖ │   ╘═╤═╝ ╘═╤═╝ └─┤ > ╟───┴─┐   │ ╚═══╝ ╘═╤═╝ │ │   ┌──────┘     └────┐
                     │ ⁞ ║ │   ┌─┴─╖ ┌─┴─╖   ╘═╤═╝     │ ┌─┴─╖ ┌───╖ │   │ │ ┌─┴─╖ ┌───╖ ┌───╖ ┌─┴─╖
                     ╘═╤═╝ └───┤ ? ╟─┤ · ╟─────┴─┐     │ │ − ╟─┤ ȶ ╟─┴─┐ │ │ │ + ╟─┤ ♯ ╟─┤ › ╟─┤ › ║
                     ┌─┴─╖     ╘═╤═╝ ╘═╤═╝       │     │ ╘═╤═╝ ╘═╤═╝   │ │ │ ╘═╤═╝ ╘═══╝ ╘═╤═╝ ╘═╤═╝
┌────────────────────┤ · ╟───────┴───┐ └─┐     ┌─┴─╖   └───┘   ┌─┴─╖   │ │ └───┘           │     │
│                    ╘═╤═╝         ┌─┴─╖ │   ┌─┤ · ╟───────────┤ · ╟───┘ │                       │
│ ┌────────────────┐   │   ┌───────┤ · ╟─┘   │ ╘═╤═╝           ╘═╤═╝     │                       │
│ │ ╔════╗ ┌───╖ ┌─┴─╖ └───┤ ┌───╖ ╘═╤═╝     │   │               │     ┌─┴───┐                   │
│ │ ║ 32 ╟─┤ ‼ ╟─┤ · ╟───┐ └─┤ ʭ ╟───┘       │   │             ┌─┴─╖ ┌─┴─╖ ┌─┴─╖                 │
│ │ ╚════╝ ╘═╤═╝ ╘═╤═╝   │   ╘═╤═╝     ┌─────┘   │             │ ʭ ╟─┤ · ╟─┤ ? ╟─┐               │
│ │        ┌─┴─╖ ╔═╧═╕ ╔═╧═╕ ┌─┴─╖   ┌─┴─╖       │             ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ │               │
│ │        │ ‼ ╟─╢   ├─╢   ├─┤ ʑ ╟───┤ ʭ ║     ┌─┴─╖             └─────┘     │   │               │
│ │        ╘═╤═╝ ╚═╤═╛ ╚═╤═╛ ╘═╤═╝   ╘═╤═╝ ┌───┤ · ╟─────────────────────────┘   │               │
│ └──────────┘     │   ╔═╧═╗   │       ├───┘   ╘═╤═╝                             │               │
│                  └───╢ 0 ║ ┌─┴─╖   ┌─┴─╖       └───────────────────────────────┘             ┌─┴─╖ ╔═══╗
│                      ╚═══╝ │ ȶ ╟───┤ · ╟─────────────────────────────────────────────────────┤ › ╟─╢ 0 ║
│                            ╘═╤═╝   ╘═╤═╝                                                     ╘═══╝ ╚═══╝
│                            ┌─┴─╖   ┌─┴─╖
│                      ┌─────┤ ? ╟─┐ │ ɕ ║
│                    ┌─┴─╖   ╘═╤═╝ │ ╘═╤═╝
│            ┌───╖ ┌─┤ < ╟───┬─┘   │   │
└────────────┤ ɕ ╟─┤ ╘═══╝ ┌─┴─╖   │   │
             ╘═══╝ └───────┤ · ╟───┘   │
                           ╘═╤═╝       │
                             └─────────┘

```

Here’s how it works.

* First, for each stack, generate an infinite sequence () of strings, each of which contains spaces () according to that stack’s width.
* The *y* values of the stacks tell us which one needs to “move down” and by how much. Prepend the appropriate space sequence, truncated (`ȶ`) to the right length (*y1**y2* or *y2**y1* as appropriate).
* Now determine the length of each of the string sequences (`ɕ`), which tells us their height. Find out which one is taller.
* Append the infinite space sequences to both stacks.
* Use zip (`ʑ`) to put them together. For each pair of strings, concatenate them () along with an extra space in between.
* *Then* use `ȶ` to truncate the result of that to the tallest height. By doing this late, we don’t have to care which one of them needs the padding.

Finally, generate the structure again. At this point, we no longer need the character in the diamonds, so we set that to 0. The *x* value is just summed and incremented (so that the width of the stack can still be calculated as `♯(x << 1)`). The *y* value is set to the higher one of the two.

## Iterate over characters in a string

This is another useful function which I will add to the library. Given a string, it gives you a lazy sequence containing each character code.

```
                                        ╓───╖
                                        ║ ↯ ║
                                        ╙─┬─╜
                           ┌──────────────┴────────────────┐
                           │      ┌─┐          ╔═══╗ ┌───╖ │
                           │      └─┤     ┌────╢ 0 ╟─┤ ≠ ╟─┴─┐
                    ┌──────┴─┐ ┌┐ ╔═╧═╕ ┌─┴─╖  ╚═══╝ ╘═╤═╝   │
                    │        ├─┤├─╢   ├─┤ ? ╟──────────┤     │
                    │        │ └┘ ╚═╤═╛ ╘═╤═╝ ╔════╗ ┌─┴─╖   │
                    │ ╔══════╧══╗ ┌─┴─╖   │   ║ −1 ╟─┤ ≠ ╟───┘
                    │ ║ 2097151 ║ │ ↯ ║       ╚════╝ ╘═══╝
                    │ ╚═════════╝ ╘═╤═╝
                    │             ┌─┴──╖ ╔════╗
                    └─────────────┤ >> ╟─╢ 21 ║
                                  ╘════╝ ╚════╝

```

`and`ing a string with 2097151 returns the first character. `>>`ing it by 21 removes it. We check for both 0 and −1 for a reason explained in the esolangs page; this is not relevant to this challenge, but I want the library function to be correct.

## Convert character to diamond stack

This function takes a single character and returns the structure for the vertical stack representing that one character.

```
                                   ╔════╗
                                   ║ 96 ║  ╓───╖
                                   ╚══╤═╝  ║ ⬖ ║
                        ┌───╖ ┌───╖ ┌─┴─╖  ╙─┬─╜
                    ┌───┤ ɗ ╟─┤ Ḟ ╟─┤ − ║    │
                    │   ╘═╤═╝ ╘═══╝ ╘═╤═╝    │
                    │   ┌─┴─╖         ├──────┘  ┌──┐
                    │   │ ɹ ║         │     ┌───┤  │
                    │   ╘═╤═╝   ┌─────┘     │   │  │
                  ╔═╧═╗ ┌─┴─╖ ┌─┴─╖         │  ┌┴┐ │
                  ║ 1 ╟─┤   ╟─┤ · ╟─────┐ ╔═╧═╕└┬┘ │
                  ╚═══╝ └─┬─╜ ╘═╤═╝   ┌─┴─╢   ├─┘ ┌┴┐
            ┌───────────┐ │     └─┐   │   ╚═╤═╛   └┬┘
          ┌─┴─╖         │ │ ┌───╖ │   └─┐ ╔═╧═╕ ┌──┴─╖ ╔═══╗
    ┌─────┤ · ╟───┐     │ └─┤ ◆ ╟─┘   ┌─┴─╢   ├─┤ << ╟─╢ 1 ║
 ┌──┴─┐   ╘═╤═╝   │     │   ╘═╤═╝     │   ╚═╤═╛ ╘════╝ ╚═╤═╝
 │ ┌──┴─╖ ┌─┴─╖ ╔═╧═╕ ╔═╧═╕ ┌─┴─╖   ┌─┴─╖ ┌─┴─╖        ┌─┴─╖
 │ │ >> ╟─┤ ⬗ ╟─╢   ├─╢   ├─┤ ʩ ╟───┤ · ╟─┤ ʑ ╟────────┤ ⸗ ║
 │ ╘══╤═╝ ╘═╤═╝ ╚═╤═╛ ╚═╤═╛ ╘═╤═╝   ╘═╤═╝ ╘═╤═╝        ╘═╤═╝
 │  ╔═╧═╗  ┌┴┐    │   ╔═╧═╗   │       └─────┘          ╔═╧═╗
 │  ║ 1 ╟─┐└┬┘    └───╢ 0 ║                            ║ 0 ║
 │  ╚═══╝ ├─┘         ╚═══╝                            ╚═══╝
 └────────┘

```

This function is interesting because we needed the diamonds to be appended *alternatingly* to the bottom and top. Here’s how I did it:

* First, subtract 96 (so `'a'` becomes 1), get prime factors ( above), use `ɗ` to add the element 1 if the sequence is empty, and then reverse (`ɹ`) the order.
* Take the first element off and call  to jumpstart the stack.
* Now, use  to generate a lazy sequence that just alternates the numbers 0 and 1 indefinitely.
* Use `ʑ` (zip) on that and the remaining prime factors. For each prime factor, shift it left by 1 and `or` the 0/1 onto it. We now have a sequence that encodes the prime numbers *and* the top/bottom information.
* Finally, use `ʩ` (fold left/aggregate). The initial value is the stack we generated from the first element above. For each value *ν*, call  (append a new diamond) with the previous stack, the prime (`ν >> 1`) and whether top or bottom (`ν & 1`).

## ⑨ Main program

Here we do the main work.

```
                       ┌─────┐
                       │   ┌─┴─╖
                       │   │ ⬖ ║
               ╔═══╗ ╔═╧═╕ ╘═╤═╝
               ║ 0 ╟─╢   ├───┘
               ╚═╤═╝ ╚═╤═╛ ┌───╖ ┌───╖ ╔═══╗
                 └─┐   └───┤ ɱ ╟─┤ ↯ ╟─╢   ║
       ┌─────────┐ └─────┐ ╘═╤═╝ ╘═══╝ ╚═══╝
       │       ┌─┴─╖     │ ┌─┴─╖
       │   ┌───┤ · ╟───┐ └─┤   ╟─┐
       │   │   ╘═╤═╝   │   └─┬─╜ │
       │ ┌─┴─╖ ╔═╧═╕ ╔═╧═╕ ┌─┴─╖ │
       │ │ ❖ ╟─╢   ├─╢   ├─┤ ʩ ╟─┘
       │ ╘═╤═╝ ╚═╤═╛ ╚═╤═╛ ╘═╤═╝
       └───┘   ╔═╧═╗   │   ┌─┴─╖ ┌─┐
               ║ 0 ╟───┘ ┌─┤ ‹ ╟─┴─┘
               ╚═══╝     │ ╘═══╝
                       ┌─┴─╖ ┌─┐
                     ┌─┤ ‹ ╟─┴─┘
                     │ ╘═══╝
      ╔════╗ ┌───╖ ┌─┴─╖ ┌─┐
      ║ 10 ╟─┤ ʝ ╟─┤ ‹ ╟─┴─┘
      ╚════╝ ╘═╤═╝ ╘═══╝
               │

```

First, map (`ɱ`) over the characters in the input string () and turn each into a diamond stack using . Take the first element off that, and fold (`ʩ`) over the rest to concatenate them all (). Finally, unpack the structure using  to get to the sequence of strings and join them all (`ʝ`) using 10 (the newline) as the separator.

## Example output

**Input:**

```
crusaders

```

**Output** (took 9 seconds to compute; cannot post here because size limit).
> 11 votes

# Answer
# 05AB1E, 84 bytes

```
εUAyk>ÐV≠iÒDg;Y18Q-._}εXs<ú'.ìηy>j.º».∊}».c.B€SøJ•ΓXÇôнÒ¤Å¨ Â<’|Ë•24вYèú»}».B€SøJćÛ»

```

**Try it online.**

No 20% bonus, although I might try that later on. 05AB1E isn't able to write files to disk itself, but it can evaluate Python code, so I might be able to write a file to disk using Python code. It definitely won't save enough bytes to be worth the 20% bonus, though.

**Explanation:**

```
ε                     # Map over each letter of the (implicit) input-string
 U                    #  Pop and store the letter in variable `X`
   k                  #  Get the 0-based index
  y                   #  of the letter
 A                    #  in the lowercase alphabet
    >                 #  And increase it by 1 to make it a 1-based index
     Ð                #  Triplicate it
      V               #  Pop and store one in variable `Y`
       ≠i           } #  If it's NOT equal to 1 (so not 'a'):
         Ò            #   Get all prime factors including duplicates
          Dg          #   Get the amount of prime factors (without popping by duplicating first)
            ;         #   Halve that amount
             Y18Q     #   Check if `Y` is 18 (1 if truthy; 0 if falsey)
                 -    #   Subtract that from halve the amount of prime factors
                  ._  #   And rotate the list of prime factors that many times towards the left
                      #   (which only uses the integer portion and ignores the decimal values)
                      #   (the `Dg;Y18Q-._` is to put the prime factors in the correct order,
                      #    according to the third rule of the challenge description)
 ε                    #  Then map over each prime factor `y`:
  X                   #   Push the letter `X`
   s                  #   Swap so the prime factor is at the top again
    <                 #   Decrease it by 1
     ú                #   Pad the letter with that many leading spaces
      '.ì            '#   And prepend a "."
         η            #   Then take the prefixes of this string
          y>          #   Push the prime factor, and increase it by 1
            j         #   Make all prefixes of equal length by padding with spaces,
                      #   up to a length of the prime factor + 1
                      #   (we now have the top-left portion of a diamond)
  .º                  #   Mirror each line horizontally with overlap
    »                 #   Join them by newlines
     .∊               #   And also mirror everything vertically with overlap
                      #   (we now have the entire diamond)
 }                    #  After the inner map:
  »                   #  join all diamonds of the current letter with newline delimiter
   .c                 #  Centralize all lines (which pads leading spaces)
     .B               #  Split each line on newlines as box (also adds trailing spaces)
       €S             #  Convert each line to a list of characters
         ø            #  Zip/transpose; swapping rows/columns
          J           #  Join all transposed inner character-lists to a string again
  •ΓXÇôнÒ¤Å¨ Â<’|Ë•   #  Push compressed integer 384055587443514148837383584634491347
   24в                #  Convert it to base-24 as list:
                      #   [11,23,22,21,22,19,21,17,17,21,19,13,16,11,17,19,17,7,16,5,14,17,13,1,16,19]
      Yè              #  Index value `Y` into this list
        ú             #  Pad each line with that many leading spaces
         »            #  And join them with a newline delimiter again
}                     # After the outer map:
 »                    # join all diamond-towers together with newline delimiter
  .B                  # Split each line on newlines as box (also adds trailing spaces)
    €S                # Convert each line to a list of characters
      ø               # Zip/transpose; swapping rows/columns
       J              # Join all transposed inner character-lists to a string again
        ć             # Extract head; pop and push remainder-list of lines and the first line
                      # (this first line is always a line consisting of only spaces,
                      #  since the padding list was incremented by 1 for each letter)
         Û            # Trim all leading lines consisting of only spaces
          »           # And join all remaining lines with newline delimiter
                      # (after which it is output implicitly as result)

```

See this 05AB1E tip of mine (section *How to compress large integers?* and *How to compress integer lists?*) to understand why `•ΓXÇôнÒ¤Å¨ Â<’|Ë•` is `384055587443514148837383584634491347` and `•ΓXÇôнÒ¤Å¨ Â<’|Ë•24в` is `[11,23,22,21,22,19,21,17,17,21,19,13,16,11,17,19,17,7,16,5,14,17,13,1,16,19]`.
> 1 votes

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


# Question
Title: Find the min and max number of substitutions
The Levenshtein distance between two strings is the minimum number of single character insertions, deletions and substitutions needed to transform one string into the other. Let us call insertions, deletions and substitutions "edit operations". We will say that any sequence of \\$k\\$ edit operations that transforms one string into another one is optimal if \\$k\\$ is also the Levenshtein distance between the two strings.

For example, take the strings \\$ab\\$ and \\$ba\\$. The optimal sequence of edit operations "insert \\$b\\$ at index 0", "delete the final character" transforms \\$ab\\$ into \\$ba\\$. However a different optimal sequence "substitute the first character for a \\$b\\$", "substitute the second character for an \\$a\\$" also transforms \\$ab\\$ into \\$ba\\$. In general there may be many different optimal sequences of edit operations for a given pair of strings.

For an optimal sequence of edit operations we are interested in counting the number of substitutions in the sequence. In particular, for a given pair of strings, we want to count the smallest possible number of substitutions in an optimal sequence of edit operations and also the largest possible. We will assume that both strings have the same length.

# Example

```
0000 0000 . In this case every optimal sequence has length 0 and so min = max = 0.
0010 1001 . Levenshtein distance 2 by one insertion and one deletion. min = max = 0.
1100 1110 . Levenshtein distance 1. min = max = 1. There is no optimal sequence with an insertion or deletion.
1010 1100 . Levenshtein distance 2. min = 0. max = 2.
1010 0111 . Levenshtein distance 3. min = 1. max = 3.
0011 1100 . Levenshtein distance 4. min = 0. max = 4.
10000011 11110100. Levenshtein distance 6. min = 2. max = 6.
000111101110 100100111010. Levenshtein distance 5. min = 1. max = 5.
0011011111001111 1010010101111110. Levenshtein distance 7. min = 3.  max = 7.
0010100001111111 0010010001001000. Levenshtein distance 7.  min = 5. max = 7.
10100011010010110101011100111011 01101001000000000111101100000000. Levenshtein distance 15. min = max = 9.
11011110011010110101101011110100 00100010101010111010000000001110. min = 8. max = 12.
32123323033013011333111032331323 13100313103110123321321211233032. min = 6. max = 14.
17305657112546416613111655660524 23146332512152524313021536474017. min = 11. max = 21.

```

# Task

For a given pair of strings of the same length, output the minimum and maximum number of substitutions in an optimal sequence of edit operations for those two strings.

You can assume the input is given in any convenient form you choose and may similarly provide the output in any way that is convenient for you.

# Answer
> 5 votes
# JavaScript (ES10),  ~~169 168~~  161 bytes

*Saved 7 bytes thanks to @KevinCruijssen*

Takes the strings as `(s)(t)`. Returns `[min, max]`.

```
s=>t=>[[...Array(d=(g=(k,m=s.length,n=m,c)=>m*n?1+Math.min(g(k,m,n-1),g(k,--m,n),g(k-=c=s[m]!=t[--n],m,n)-!c):k?1/0:m-~n)())].flatMap((_,i)=>g(i)-d?[]:j=i)[0],j]

```

Try it online! (fast test cases)

Try it online! (a longer test case which may time out if TIO is overloaded)

## Commented

### Helper function \\$g\\$

\\$g\\$ is a function that computes the standard Levenshtein distance when it's called with \\$k\\$ undefined, or the edit distance with exactly \\$k\\$ substitutions when it's called with \\$k\ge0\\$. An additional offset of \\$+1\\$ is added to the result in both cases.

NB: It is presented separately for readability but must be defined within the scope of the main function so that the source string \\$s\\$ and the target string \\$t\\$ are defined.

```
g = (                         // g is a recursive function taking:
  k,                          //   k = allowed number of substitutions, or undefined
  m = s.length,               //   m = 1st pointer, initialized to the length of s
  n = m,                      //   n = 2nd pointer, initialized to the length of s
  c                           //   c = substitution cost
) =>                          //       (needs to be defined in the local scope)
  m * n ?                     // if both m and n are greater than 0:
    1 +                       //   add 1 to the final result
    Math.min(                 //   add the minimum of:
      g(k, m, n - 1),         //     recursive call for insertion with (m, n - 1)
      g(k, --m, n),           //     recursive call for deletion with (m - 1, n)
      g(                      //     recursive call for substitution:
        k -=                  //       set c if s[m - 1] is not equal to t[n - 1]
          c = s[m] != t[--n], //       and decrement k if c is set
        m, n                  //       use (m - 1, n - 1)
      ) - !c                  //     subtract 1 from the result if c is not set
    )                         //   end of Math.min()
  :                           // else (leaf node):
    k ?                       //   if k is not equal to 0 or NaN:
      1 / 0                   //     return +Infinity
                              //     (to make sure that this branch is not chosen)
    :                         //   else:
      m - ~n                  //     return m + n + 1

```

### Main function

```
s => t =>                     // s = source string, t = target string
  [                           // the final result is a pair:
    [                         //   build an array containing:
      ...Array(d = g()),      //     d entries, where d = Levenshtein distance (+1)
    ]                         //
    .flatMap((_, i) =>        //   for each entry at position i in there:
      g(i)                    //     if the edit distance (+1) with i substitutions
      - d ?                   //     is not equal to d:
        []                    //       reject this entry
      :                       //     else:
        j = i                 //       append it to the array and copy i to j
    )[0],                     //   end of flatMap(); return the 1st entry (minimum)
    j                         //   followed by the last entry (maximum)
  ]                           // end of result

```

---
Tags: code-golf, edit-distance
---


title: Starbucks to English

text:
# Question
Title: Starbucks to English
In the classic days of Starbucks before these newfangled sticker-printers and wireless drivethrough headset palmtop scanner dealies, in the heady days of 2000-ish, Starbucks had a concise system for describing beverages with a strict syntax and accompanying encoded form.

Vertically on the cup there are a series of labelled boxes which may contain certain values.:

```
Decaf
[   ]     -blank-  X  1/2  1/3  2/3
Shots
[   ]     -blank-  0 1 2 3 ... 20    followed by    S T G V
Syrup
[   ]     -blank-  V M C H
Milk
[   ]     -blank-  Wh % N B
Custom
[    ]    -blank- ((-|x)?(F|WC|M|CR) )+
Drink
[   ]     E EM ECP A L C CM

```

But we will use a horizontal form for easier manipulation. These are the names of the 6 fields of the input which may be any convenient form. Examples here are simple CSV. The Custom field and Syrup fields each may be a concatenation of several values. You may use any convenient subdelimiter. Examples here use space. The Shots field is also a concatenation of a (possible) number and a designation of the cup size (which is implicit in the physical cup but naturally fits in this place in the encoding).

The Decaf field values are translated into words like this

```
-blank-   -nothing-
X         "decaf"
1/2       "half-caf"
1/3       "one-third-caf"
2/3       "two-thirds-caf"

```

Logically, the fractional values are only permissible when the number of shots is divisible by the denominator; but for this challenge it is not necessary to detect or diagnose this error.

The Shots field should be broken into its numerical component (if present) and the size identifier. The number should be displayed in latin tuple form: single, double, triple, quadruple, quintuple, *beyond 5 just print the number and the suffix "-tuple" ie. `7-tuple`, `16-tuple`*. The size designations are:

```
S  short
T  tall
G  grande
V  venti

```

Eg.

```
2T  double tall
3G  triple grande

```

The Syrup field may contain one or more of several optional-number/lettercode tokens. The maximum number of a syrup is 20. Even that is too much. LOL.

```
V  vanilla
C  caramel
M  mocha
H  hazelnut

```

Eg.

```
2V 2C     two vanilla two caramel
H         hazelnut
M H 1V    mocha hazelnut one vanilla

```

The Milk field may contain **one** of the following.

```
Wh  whole-milk
%   two-percent
N   skim
B   breve

```

The Custom field may contain one or more of several modifiers with optional `x` or `-` sign.

```
x  extra     F   foam
-  no        WC  whip
             M   mocha drizzle
             CR  caramel drizzle

```

The Drink field contains one drink id.

```
E    espresso
EM   espresso macchiato
ECP  espresso con panna
A    americano
L    latte
C    cappuccino
CM   caramel macchiato

```

Any field may be blank except for the size designation and the drink id.

Examples.

```
,3G,V,Wh,,L    =>   triple grande vanilla whole-milk latte
X,2T,,N,,L     =>   decaf double tall skim latte
1/2,V,,,,CM    =>   half-caf venti caramel macchiato
2/3,3V,3V,B,WC,L  => two-thirds-caf triple venti three vanilla breve whip latte
,G,,,xCR,CM    =>   grande extra caramel drizzle caramel macchiato
X,4T,2M 2C,B,xWC -F xM,C  =>
  decaf quadruple tall two mocha two caramel breve extra whip no foam extra mocha drizzle cappuccino

```

There is no need to diagnose erroneous or illogical concoctions such as a "no foam ... cappuccino\*.

## Additional Complication

For only the drinks with the word `espresso`, the number `single` should be replaced by `solo` and `double` should be replaced by `doppio`. And the size may be unspecified and omitted. Also, just for the bare `espresso` drink itself, if the only other specification is one of these two specially-replaced numbers-of-shots, then the word `espresso` itself should be omitted.

```
,2,1V,B,,EM   =>  doppio one vanilla breve espresso macchiato
,1,,,,E       =>  solo
,2,,,,E       =>  doppio
,3,,,,E       =>  triple espresso

```

## Additional observations on 'reading a cup'

This part is not a requirement for this challenge but may be a useful refinement in applying this sort of verbalized system in other domains.

I mentioned *syntax* at the very beginning, and by applying the schema to incoming streams of words, orders could be transmitted verbally by several order takers to the barista making beverages. The rough framework `SIZE .... DRINK` provides demarcation between several orders spoken at once. There is thus a tendency to make all the interior attributes as adjectival phrases so the order also has a valid English noun-phrase structure. So `whip` is often spoken `with whip` or `whipped` and `foam` is often spoken `foamy` or `with foam`.

Thus, for some old-time baristas, they're not "correcting you" when they repeat the order in the proper format (*well,... sometimes*). They're simply organizing the information for the purpose of remembering all the details exactly. By schematizing the information, an entire beverage order becomes a single unit for the purpose of applying the magic number 7 plus or minus 2. So a barista with this skill can *hold 5-9 orders in their head* provided other distractions do not consume too much head room. :)

# Answer
> 3 votes
# Retina 0.8.2, 640 bytes

Performs a series of substitutions to transform the input into the expected output.

```
-
no
x
extra
Wh
whole-milk
%
2-percent
N
skim
B
breve
X
deJ
1/2
half-J
1/3
1Q-J
2/3
2Qs-J
Q
-third
J
caf
^,
 ,
 ,1(?=\D.*E)
,soloZ
 ,2(?=\D.*E)
,doppioZ
Z,,,,E$
Z
 ,(\d+)
,$1UleZ
,1U
,sing
,2U
,doub
,3U
,trip
\d+(?!\d*U)
$&Y
U
-tup
,4-.
,quadr
,5-
,quin
 ,
Z
S
short
T
tall
G
grande
ZV
 venti
M(?=[^,]*,\w*$)
MR
E
espresso
M$
 macchiato
CP
 con panna
A
americano
L
latte
C$
cappuccino
F
foam
WC
whip
R
 drizzle
4Y
fourY
6Y
sixY
7Y
sevenY
9Y
nineY
10Y
ten
11Y
eleven
12Y
twelve
13Y
thirK
15Y
fifK
18Y
eighK
20Y
twenty
1Y
one
2Y
two
3Y
three
5Y
five
8Y
eight
1(\w*)Y
$1K
K
teen
V
vanilla
C
caramel
M
mocha
H
hazelnut
 -
-
Z,*| ?,+

^ |Y

```

Try it online!

Most of it is pretty straightforward replacements. A few interesting parts are:

```
 ,1(?=\D.*E)
,soloZ
 ,2(?=\D.*E)
,doppioZ

```

Handles the special cases for drinks containing the word "espresso". It transforms the 1 and 2 into "solo" and "doppio" before we get to the stage where we transform those numbers into latin tuple form.

```
Z,,,,E$
Z

```

Removes the word "espresso" if "solo" or "doppio" is the only other modifier.

```
M(?=[^,]*,\w*$)
MR

```

Appends an `R` to any `M` with only one comma between it and the end of the string. This allows us to transform all `R`s into "drizzle" later on.

```
1(\w*)Y
$1K
K
teen

```

Allows us to transform 14,16,17, and 19 into their word forms all at once, since we replace 4,6,7, and 9 beforehand.

# Answer
> 6 votes
# Javascript ES6, ~~902~~ 900 bytes

```
s=>(R=(l,r)=>(l.split`.`.map((e,i,l)=>!(i%2)&&(r=r.split(e).join(l[i+1]+" "))),r),R("-.no.!.-tuple.1/2.half-caf.1/3.one-third-caf.2/3.two-thirds-caf.ECP.Econ panna.CM.RY.CR.RZ.EM.EY.WC.whip.Wh.whole-milk.A.americano.B.breve.C.cappuccino.D.extra.E.espresso.F.foam.G.grande.H.hazelnut.I.venti.L.latte.M.OZ.N.skim.O.mocha.R.caramel.S.short.T.tall.V.vanilla.X.decaf.Y.macchiato.Z.drizzle.%.two-percent",R(",1,,,,E.solo.,2,,,,E.doppio",s).split`,`.map((e,i)=>(`1VI.2MO.2CR.4xD`.split`.`.map(k=>k[0]==i&&(e=e.split(k[1]).join(k[2]))),i==1?(e=R("1!.single.2!.double.3!.triple.4!.quadruple.5!.quintuple",e.replace(/(\d+)/,"$1!"))):i==2?(e=R("10.ten.20.twenty.11.eleven.12.twelve.13.thir0.14.four0.15.fif0.16.six0.17.seven0.18.eigh0.19.nine0.0.teen.1.one.2.two.3.three.4.four.5.five.6.six.7.seven.8.eight.9.nine",e)):s.includes`E`&&(e=R("single.solo.double.doppio",e)),e)).join` `).replace(/\s+/g," ").trim())

```

"Ungolfed":

```
s=>(
  R=(l,r)=>(l.split`.`.map((e,i,l)=>!(i%2)&&(r=r.split(e).join(l[i+1]+" "))),r),                                   // consecutive string replacement function
  R("-.no.!.-tuple.1/2.half-caf.1/3.one-third-caf.2/3.two-thirds-caf.ECP.Econ panna.CM.RY.CR.RZ.EM.EY.WC.whip.     // replace all symbols with appropriate values
     Wh.whole-milk.A.americano.B.breve.C.cappuccino.D.extra.E.espresso.F.foam.G.grande.H.hazelnut.I.venti.L.latte.
     M.OZ.N.skim.O.mocha.R.caramel.S.short.T.tall.V.vanilla.X.decaf.Y.macchiato.Z.drizzle.%.two-percent",
    R(",1,,,,E.solo.,2,,,,E.doppio",s)                                                                             // if special espresso cases, directly replace entire string
    .split`,`.map((e,i)=>(                                                                                // split input at commas
      `1VI.2MO.2CR.4xD`.split`.`.map(k=>k[0]==i&&(e=e.split(k[1]).join(k[2]))),                                    // substitute duplicate symbols with unique symbols
      i==1?(e=R("1!.single.2!.double.3!.triple.4!.quadruple.5!.quintuple",e.replace(/(\d+)/,"$1!"))):              // if in shots section, expand all numbers
      i==2?(e=R("10.ten.20.twenty.11.eleven.12.twelve.13.thir0.14.four0.15.fif0.16.six0.17.seven0.18.eigh0.        // if in syrup section, expand all numbers
                  19.nine0.0.teen.1.one.2.two.3.three.4.four.5.five.6.six.7.seven.8.eight.9.nine",e)):
      s.includes`E`&&(e=R("single.solo.double.doppio",e)),                                                         // replace single,double with solo,doppio if espresso is in the string
    e)).join` `).replace(/\s+/g," ").trim())                                                                       // join sections, cleanup whitespaces

```

Example runs:

```
f(",3G,V,Wh,,L")              -> triple grande vanilla whole-milk latte
f("X,2T,,N,,L")               -> decaf double tall skim latte
f("1/2,V,,,,CM")              -> half-caf venti caramel macchiato
f("2/3,3V,3V,B,WC,L")         -> two-thirds-caf triple venti three vanilla breve whip latte
f(",G,,,xCR,CM")              -> grande extra caramel drizzle caramel macchiato
f("X,4T,2M 2C,B,xWC -F xM,C") -> decaf quadruple tall two mocha two caramel breve extra whip no foam extra mocha drizzle cappuccino
f(",2,1V,B,,EM")              -> doppio one vanilla breve espresso macchiato
f(",1,,,,E")                  -> solo
f(",2,,,,E")                  -> doppio
f(",3,,,,E")                  -> triple espresso

```

# Answer
> 4 votes
# Python, ~~824~~ ~~815~~ ~~807~~ 805 bytes

```
f=lambda s,a=0:a==0and" ".join(" ".join(f(" "+s.split(",")[i],(["X,deC,1/2,half-C,1/3,oneT-C,2/3,twoTs-C,C,caf,T,-third","".join(" %i"%i+f(",%i-tupL,"%i,["1","x","2","y"])for i in range(6,21))+"1,solo,2,doppio,"*('E'in s)+"1,singL,2,doubL, 3,tripL, 4,quadrupL, 5,quintupL,x,1,y,2,S,short,T,tall,G,grande,V,Vnti","V, vanilla,H, hazelnut,10,ten,11,eleVn,12,twelV,13,thirT,14,4T,15,fifT,16,6T,17,7T,18,8een,19,9T,20,twenty,1,one,2,two,3,three,4,four,5,fiV,6,six,7,seVn,8,eight,9,nine,T,teen","Wh,whole-milk,%,two-percent,N,skim,B,breV","x,extra ,-,no ,F,foam,WC,whip,M,MR,R, drizzL","CM,xM,E,espresso,M, macchiato,CP, con panna,A,americano,L,latte,C,cappuccino,x,C"][i]+",C, caramel,M, mocha,L,le ,V,ve").split(","))for i in range(6-(s in",1,,,,E,2,,,,E"))).split())or a and f(s.replace(a[0],a[1]),a[2:])or s

```

Slightly more readable:

```
def f(s,a=0):
 if a==0:
  a=["X,deC,1/2,half-C,1/3,oneT-C,2/3,twoTs-C,C,caf,T,-third"]
  a+=["".join(" %i"%i+f(",%i-tupL,"%i,["1","x","2","y"])for i in range(6,21))+"1,solo,2,doppio,"*('E'in s)+"1,singL,2,doubL, 3,tripL, 4,quadrupL, 5,quintupL,x,1,y,2,S,short,T,tall,G,grande,V,Vnti"]
  a+=["V, vanilla,H, hazelnut,10,ten,11,eleVn,12,twelV,13,thirT,14,4T,15,fifT,16,6T,17,7T,18,8een,19,9T,20,twenty,1,one,2,two,3,three,4,four,5,fiV,6,six,7,seVn,8,eight,9,nine,T,teen"]
  a+=["Wh,whole-milk,%,two-percent,N,skim,B,breV"]
  a+=["x,extra ,-,no ,F,foam,WC,whip,M,MR,R, drizzL"]
  a+=["CM,xM,E,espresso,M, macchiato,CP, con panna,A,americano,L,latte,C,cappuccino,x,C"]
  return" ".join(" ".join(f(" "+s.split(",")[i],(a[i]+",C, caramel,M, mocha,L,le ,V,ve").split(","))for i in range(6-(s in",1,,,,E,2,,,,E"))).split())
 elif a:
  return f(s.replace(a[0],a[1]),a[2:])
 else:
  return s

```

Demo at https://repl.it/C8Hz/3

# Answer
> 3 votes
# Ruby `-plaF,`, ~~975~~ 870 bytes

I got a random upvote on my old, almost-four-year-old answer to this question, and because of my comments on how horribly it went (you can check the post history if you want to see what I wrote before) I was inspired to make it better (aka: rewrite most of it from the ground up) and managed to golf over a hundred bytes off it. Still longer than the Python answer, but I'm much happier with how things turned out now.

About 20 bytes were saved by switching from trying to run regex patterns to affect specific parts of the comma structure to using the `-aF,` flag to autosplit a line of input on commas and save it to `$F`, allowing me to modify some elements before stitching it back together and finally modifying the output variable with the last few `sub`/`gsub` commands.

Honestly, the number of regex replacements made here means most of this could be a Retina program, but I don't know Retina well enough for that.

```
g=->n,c{n.grep(/^ ?#{c}/i)[0]}
n=%w"0 one two three four five six seven eight nine ten eleven twelve thir four fif";n+=n[6,4]<<'twenty'
$F[1].sub!(/(\d*)(\w)?/){i=eval$1;"#{i&&(%w"0 sing doub trip quadrup quintup"[i]||$1+"-tup")+"le"} #{g[%w"short tall grande venti",$2]if$2}"}
$F[2].gsub!(/(\d*)(\w)/){i=eval$1;"#{i&&n[i]}#{'teen'if(13..19)===i} #{g[%w"vanilla caramel mocha hazelnut",$2]}"}
$F[3].sub!(/.+/){%w"skim whole-milk breve two-percent"[$&.sum%26%4]}
$F[4].gsub!(/(x|-)?(\w+)/){"#{%w"extra no"[$1.ord%2]if$1} #{g[%w"caramelD mochaD whip foam",$2[0]].sub ?D,' drizzle'}"}
$_=$F*' '
sub(/^\S+/){%w"de - half- one-third- two-thirds-"[$&.sum%8]+"caf"}
sub'CP',' con pana'
sub'CM','caramel'+m=' macchiato'
e='espresso'
gsub(/[A-Z]/){g[%w"americano latte cappuccino"+[m,e],$&]}
gsub(/ +/,' ')
$_.strip!
sub(/[sd]...le/){g[%w"doppio solo",$&[0]]}if$_[e]
sub'o '+e,?o

```

Try it online!

---
Tags: code-golf
---


title: Do the circles overlap?

text:
# Question
Title: Do the circles overlap?
Given the coordinates of the centres and the radii of 2 circles, output a truthy value of whether they do or do not overlap.

## Input

* Input may be taken via STDIN or equivalent, function arguments, but not as a variable. You can take them as a single variable (list, string etc) or as multiple inputs / arguments, in whatever order you want.
* The input will be six floats. These floats will be up to 3 decimal places. The coordinates can be positive or negative. The radii will be positive.

## Output

* Output can be via STDOUT or function return.
* The program must have exactly 2 distinct outputs - one for a True value (the circles do overlap) and one for a False output (they don't overlap).

### Test cases

(Input is given as list of tuples `[(x1, y1, r1), (x2, y2, r2)]` for the test cases; you can take input in any format)

### True

```
[(5.86, 3.92, 1.670), (11.8, 2.98, 4.571)]
[(8.26, -2.72, 2.488), (4.59, -2.97, 1.345)]
[(9.32, -7.77, 2.8), (6.21, -8.51, 0.4)]

```

### False

```
[(4.59, -2.97, 1.345), (11.8, 2.98, 4.571)]
[(9.32, -7.77, 2.8), (4.59, -2.97, 1.345)]
[(5.86, 3.92, 1.670), (6.21, -8.51, 0.4)]

```

---

This is Code Golf, shortest answer in bytes wins.

# Answer
> 18 votes
# Jelly, 5 bytes

```
IA<S}

```

Takes two complex numbers (centers) as first argument, and two real numbers (radii) as second argument.

Try it online!

### How it works

```
IA<S}  Main link.
       Left argument:  [x1 + iy1, x2 + iy2]
       Right argument: [r1, r2]

I      Increments; yield (x2 - x1) + i(y2 - y1).
 A     Absolute value; yield √((x2 - x1)² + (y2 - y1)²).
   S}  Take the sum of the right argument, yielding r1 + r2.
  <    Compare the results.

```

# Answer
> 11 votes
## JavaScript (ES6), 38 bytes

Takes input as 6 distinct variables ***x1***, ***y1***, ***r1***, ***x2***, ***y2***, ***r2***.

```
(x,y,r,X,Y,R)=>Math.hypot(x-X,y-Y)<r+R

```

### Test cases

```
let f =

(x,y,r,X,Y,R)=>Math.hypot(x-X,y-Y)<r+R

// True
console.log(f(5.86, 3.92, 1.670, 11.8, 2.98, 4.571))
console.log(f(8.26, -2.72, 2.488, 4.59, -2.97, 1.345))
console.log(f(9.32, -7.77, 2.8, 6.21, -8.51, 0.4))

// False
console.log(f(4.59, -2.97, 1.345, 11.8, 2.98, 4.571))
console.log(f(9.32, -7.77, 2.8, 4.59, -2.97, 1.345))
console.log(f(5.86, 3.92, 1.670, 6.21, -8.51, 0.4))
```

# Answer
> 7 votes
# Pyth, 5 bytes

```
gsE.a

```

Input format:

```
[x1, y1], [x2, y2]
r1, r2

```

Try it online

### How it works

```
     Q   autoinitialized to eval(input())
   .a    L2 norm of vector difference of Q[0] and Q[1]
gsE      sum(eval(input()) >= that

```

# Answer
> 7 votes
# MATL, 5 bytes

```
ZPis<

```

Input format is:

```
[x1, y1]
[x2, y2]
[r1, r2]

```

Try it online! Or verify all test cases.

### How it works

```
ZP   % Take two vectors as input. Push their Euclidean distance
i    % Input the vector of radii
s    % Sum of vector
<    % Less than?

```

# Answer
> 6 votes
# , 39 bytes

```
function(k,r)dist(matrix(k,2,2))<sum(r)

```

takes input `k=c(x1,x2,y1,y2)` and `r=c(r1,r2)`; returns `FALSE` for tangent circles.

Try it online!

### 27 bytes:

```
function(m,r)dist(m)<sum(r)

```

Takes input as a matrix with the circle centers given as rows and a vector of radii.

Try it online!

# Answer
> 6 votes
# Python, 40 bytes

```
lambda x,y,r,X,Y,R:abs(x-X+(y-Y)*1j)<r+R

```

Try it online!

Uses Python's complex arithmetic to compute the distance between the two centers. I'm assuming we can't take the input points directly as complex numbers, so the code expresses them like `x+y*1j`.

# Answer
> 5 votes
# Python 3, 45 bytes

```
lambda a,b,c,d,e,f:(a-d)**2+(b-e)**2<(c+f)**2

```

Try it online!

-8 bytes thanks to Neil/Step Hen

# Answer
> 5 votes
# Python 3, 45 bytes

```
lambda X,Y,R,x,y,r:(X-x)**2+(Y-y)**2<(R+r)**2

```

Try it online!

# Answer
> 5 votes
# 05AB1E, 6 bytes

```
αs--0›

```

Try it online!

-1 byte by using `a - b > 0` rather than `(reverse) b - a < 0`

# Answer
> 4 votes
# APL (Dyalog), 10 bytes

Prompts for circle centers as list of two complex numbers, then for radii as list of two numbers

```
(+/⎕)>|-/⎕

```

Try it online!

`(+/⎕)` \[is\] the sum of the radii

`>` greater than

`|` the magnitude of

`-/⎕` the difference in centers

# Answer
> 3 votes
# Jelly, 12 bytes

```
I²+⁴I²¤<⁵S²¤

```

Try it online!

-2 bytes thanks to Dennis

# Answer
> 3 votes
# Haskell, ~~37~~ 36 bytes

```
(u#v)r x y s=(u-x)^2+(v-y)^2<(r+s)^2

```

Try it online!

Thanks @AndersKaseorg for `-1` byte!

# Answer
> 3 votes
# Mathematica, 16 bytes

```
Norm[#-#2]<+##3&

```

Input: `[{x1, y1}, {x2, y2}, r1, r2]`

---

Mathematica has a `RegionIntersection` builtin, but that alone is 18 bytes long...

Built-in version:

```
RegionIntersection@##==EmptyRegion@2&

```

Takes 2 `Disk` objects. `[Disk[{x1, y1}, r1], Disk[{x2, y2}, r2]]`.

# Answer
> 3 votes
# Java (OpenJDK 8), 38 bytes

```
(a,b,c,x,y,z)->Math.hypot(a-x,b-y)<c+z

```

Try it online!

# Answer
> 3 votes
# Java 8, ~~41~~ 38 bytes

```
(x,y,r,X,Y,R)->Math.hypot(x-X,y-Y)<r+R

```

Try it here.

Apparently, Java also has `Math.hypot`, which is 3 bytes shorter.

EDIT: Just realized this answer is now exactly the same as *@OlivierGrégoire*'s Java 8 answer, so please upvote him instead of me if you like the 38-byte answer.

**Old answer (41 bytes)**:

```
(x,y,r,X,Y,R)->(x-=X)*x+(y-=Y)*y<(r+=R)*r

```

Try it here.

# Answer
> 2 votes
# Pyth, 15 bytes

```
<sm^-EE2 2^+EE2

```

Takes input in the order x1,x2,y1,y2,r1,r2

Test suite!

# Answer
> 2 votes
# Perl 6, 13 bytes

```
*+*>(*-*).abs

```

Try it online!

The first two arguments are the radii, in either order. The third and fourth arguments are the coordinates of the centers, as complex numbers, in either order.

# Answer
> 2 votes
# C#, ~~50~~ 41 bytes

```
(x,y,r,X,Y,R)=>(x-=X)*x+(y-=Y)*y<(r+=R)*r

```

*Saved 9 bytes thanks to @KevinCruijssen.*

# Answer
> 2 votes
# Taxi, 1582 bytes

```
Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Pickup a passenger going to Tom's Trims.Pickup a passenger going to Tom's Trims.Go to Tom's Trims:n.[a]Go to Post Office:s.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to What's The Difference.Pickup a passenger going to What's The Difference.Go to What's The Difference:n 5 l.Pickup a passenger going to Cyclone.Go to Cyclone:e 1 r.Pickup a passenger going to Multiplication Station.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:s 1 l 2 r 4 l.Pickup a passenger going to Addition Alley.Go to Tom's Trims:s 1 r 3 r.Pickup a passenger going to The Babelfishery.Switch to plan "b" if no one is waiting.Switch to plan "a".[b]Go to Addition Alley:n 1 r 1 l 3 l 1 l.Pickup a passenger going to Magic Eight.Go to Post Office:n 1 r 1 r 3 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Addition Alley.Pickup a passenger going to Addition Alley.Go to Addition Alley:n 5 l 1 l.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 1 l.Pickup a passenger going to Multiplication Station.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:s 1 l 2 r 4 l.Pickup a passenger going to Magic Eight.Go to Magic Eight:s 1 r.Switch to plan "c" if no one is waiting.'1' is waiting at Writer's Depot.[c]'0' is waiting at Writer's Depot.Go to Writer's Depot:w 1 l 2 l.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l.

```

Try it online!

Outputs `1` for overlapping circles.
Outputs `0` for non-overlapping circles (including tangential circles).

Ungolfed / formatted:

```
Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to The Babelfishery.
Pickup a passenger going to Tom's Trims.
Pickup a passenger going to Tom's Trims.
Go to Tom's Trims: north.
[a]
Go to Post Office: south.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 1st right.
Pickup a passenger going to What's The Difference.
Pickup a passenger going to What's The Difference.
Go to What's The Difference: north 5th left.
Pickup a passenger going to Cyclone.
Go to Cyclone: east 1st right.
Pickup a passenger going to Multiplication Station.
Pickup a passenger going to Multiplication Station.
Go to Multiplication Station: south 1st left 2nd right 4th left.
Pickup a passenger going to Addition Alley.
Go to Tom's Trims: south 1st right 3rd right.
Pickup a passenger going to The Babelfishery.
Switch to plan "b" if no one is waiting.
Switch to plan "a".
[b]
Go to Addition Alley: north 1st right 1st left 3rd left 1st left.
Pickup a passenger going to Magic Eight.
Go to Post Office: north 1st right 1st right 3rd right 1st left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 1st right.
Pickup a passenger going to Addition Alley.
Pickup a passenger going to Addition Alley.
Go to Addition Alley: north 5th left 1st left.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 1st left 1st left.
Pickup a passenger going to Multiplication Station.
Pickup a passenger going to Multiplication Station.
Go to Multiplication Station: south 1st left 2nd right 4th left.
Pickup a passenger going to Magic Eight.
Go to Magic Eight: south 1st right.
Switch to plan "c" if no one is waiting.
'1' is waiting at Writer's Depot.
[c]
'0' is waiting at Writer's Depot.
Go to Writer's Depot: west 1st left 2nd left.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st right 2nd right 1st left.

```

# Answer
> 1 votes
## Java, ~~50~~ 38 bytes

```
(x,y,r,X,Y,R)->Math.hypot(x-X,y-Y)<r+R

```

# Answer
> 1 votes
# Scala, 23 bytes

Thanks @Arnauld for his *almost polyglot* answer.

```
math.hypot(a-x,b-y)<r+q

```

Try it online!

# Answer
> 1 votes
# PostgreSQL, 41 characters

```
prepare f(circle,circle)as select $1&&$2;

```

Prepared statement, takes input as 2 parameters in any `circle` notation.

Sample run:

```
Tuples only is on.
Output format is unaligned.
psql (9.6.3, server 9.4.8)
Type "help" for help.

psql=# prepare f(circle,circle)as select $1&&$2;
PREPARE

psql=# execute f('5.86, 3.92, 1.670', '11.8, 2.98, 4.571');
t

psql=# execute f('8.26, -2.72, 2.488', '4.59, -2.97, 1.345');
t

psql=# execute f('9.32, -7.77, 2.8', '6.21, -8.51, 0.4');
t

psql=# execute f('4.59, -2.97, 1.345', '11.8, 2.98, 4.571');
f

psql=# execute f('9.32, -7.77, 2.8', '4.59, -2.97, 1.345');
f

psql=# execute f('5.86, 3.92, 1.670', '6.21, -8.51, 0.4');
f

```

# Answer
> 1 votes
# x86 Machine Code (with SSE2), 36 bytes

```
; bool CirclesOverlap(double x1, double y1, double r1,
;                     double x2, double y2, double r2);
F2 0F 5C C3        subsd   xmm0, xmm3      ; x1 - x2
F2 0F 5C CC        subsd   xmm1, xmm4      ; y1 - y2
F2 0F 58 D5        addsd   xmm2, xmm5      ; r1 + r2
F2 0F 59 C0        mulsd   xmm0, xmm0      ; (x1 - x2)^2
F2 0F 59 C9        mulsd   xmm1, xmm1      ; (y1 - y2)^2
F2 0F 59 D2        mulsd   xmm2, xmm2      ; (r1 + r2)^2
F2 0F 58 C1        addsd   xmm0, xmm1      ; (x1 - x2)^2 + (y1 - y2)^2
66 0F 2F D0        comisd  xmm2, xmm0
0F 97 C0           seta    al              ; ((r1 + r2)^2) > ((x1 - x2)^2 + (y1 - y2)^2)
C3                 ret

```

The above function accepts descriptions of two circles (x- and y-coordinates of center point and a radius), and returns a Boolean value indicating whether or not they intersect.

It uses a vector calling convention, where the parameters are passed in SIMD registers. On x86-32 and 64-bit Windows, this is the `__vectorcall` calling convention. On 64-bit Unix/Linux/Gnu, this is the standard System V AMD64 calling convention.

The return value is left in the low byte of `EAX`, as is standard with all x86 calling conventions.

This code works equally well on 32-bit and 64-bit x86 processors, as long as they support the SSE2 instruction set (which would be Intel Pentium 4 and later, or AMD Athlon 64 and later).

### AVX version, still 36 bytes

If you were targeting AVX, you would probably want to add a VEX prefix to the instructions. This does not change the byte count; just the actual bytes used to encode the instructions:

```
; bool CirclesOverlap(double x1, double y1, double r1,
;                     double x2, double y2, double r2);
C5 FB 5C C3      vsubsd   xmm0, xmm0, xmm3   ; x1 - x2
C5 F3 5C CC      vsubsd   xmm1, xmm1, xmm4   ; y1 - y2
C5 EB 58 D5      vaddsd   xmm2, xmm2, xmm5   ; r1 + r2
C5 FB 59 C0      vmulsd   xmm0, xmm0, xmm0   ; (x1 - x2)^2
C5 F3 59 C9      vmulsd   xmm1, xmm1, xmm1   ; (y1 - y2)^2
C5 EB 59 D2      vmulsd   xmm2, xmm2, xmm2   ; (r1 + r2)^2
C5 FB 58 C1      vaddsd   xmm0, xmm0, xmm1   ; (x1 - x2)^2 + (y1 - y2)^2
C5 F9 2F D0      vcomisd  xmm2, xmm0
0F 97 C0         seta     al                 ; ((r1 + r2)^2) > ((x1 - x2)^2 + (y1 - y2)^2)
C3               ret

```

AVX instructions have the advantage of taking *three* operands, allowing you to do non-destructive operations, but that doesn't really help us to compact the code any here. However, mixing instructions with and without VEX prefixes can result in sub-optimal code, so you generally want to stick with *all* AVX instructions if you're targeting AVX, and in this case, it doesn't even hurt your byte count.

# Answer
> 1 votes
# 05AB1E, 10 bytes

```
-¨nOt²¹+θ‹

```

Try it online!

# Answer
> 1 votes
# PHP, 66 bytes

```
<?php $i=$argv;echo hypot($i[1]-$i[4],$i[2]-$i[5])<$i[3]+$i[6]?:0;

```

Try it online!

Runs from the command line, taking input as 6 command-line parameter arguments, and prints 1 if the circles overlap, else 0.

# Answer
> 1 votes
# dc, 22 bytes

```
9k?+_5R-d*_3R-d*+v-vzp

```

Try it online!

Or try the test suite!

Input is read from stdin in the format `x1 x2 y1 y2 r1 r2`. Note that negative numbers are written in dc with an underscore `_` instead of a minus sign `-`.

Output is on stdout: 1 for truthy, 0 for falsey. If the two circles are tangent to one another or if they're identical, they're considered to be overlapping.

---

This requires a recent version of GNU dc which supports the `R` operation (rotate).

On versions of dc which don't support `R`, you can instead use

`9k?-d*sY-d*lY+vsD+lD-vzp`

(24 bytes long), with input presented on stdin in the order `r1 r2 x1 x2 y1 y2`. Here's a test suite for the 24-byte program, for older versions of dc

---

**Explanation**

```
9k   Set precision to 9 decimal places.
?    Read the input and push all 6 numbers on the stack (r2 is at the top of the stack since it's entered last).
+    Add r1 and r2
_5R  Rotate the stack so that r1+r2 is now at the bottom.
-d*  Compute (y1-y2)^2.
_3R  Rotate the stack so that it's now: r1+r2 (y1-y2)^2 x1 x2 (top on the right)
-d*  Compute (x1-x2)^2.
+    Compute (x1-x2)^2 + (y1-y2)^2.
v    Take the square root to compute the distance between the centers.
-    Subtract the distance between the centers from r1-r2.
v    Pop one number from the stack. If it's non-negative, then compute its square root and push that back on the stack.
z    Push the size of the stack onto the stack. (This is 0 if the difference was negative, and it's 1 if the difference was positive.)
p    Print the item at the top of the stack.

```

# Answer
> 0 votes
## Julia 0.6.0 (46 bytes)

```
a->((a[1]-a[2])^2+(a[3]-a[4])^2<(a[5]+a[6])^2)

```

# Answer
> 0 votes
# Clojure, 68 bytes

```
#(<(+(*(- %4 %)(- %4 %))(*(- %5 %2)(- %5 %2)))(*(+ %6 %3)(+ %6 %3)))

```

Takes six arguments: x1, y1, r1, x2, y2, r2. Returns true or false.

Sadly, Clojure does not have a `pow` function of some sorts. Costs a lot of bytes.

# Answer
> 0 votes
# Actually, 8 bytes

```
-)-(h@+>

```

Try it online!

Explanation:

```
-)-(h@+>  (implicit input: [y1, y2, x1, x2, r1, r2])
-         y2-y1 ([y2-y1, x1, x2, r1, r2])
 )-       move to bottom, x1-x2 ([x1-x2, r1, r2, y2-y1])
   (h     move from bottom, Euclidean norm ([sqrt((y2-y1)**2+(x2-x1)**2), r1, r2])
     @+   r1+r2 ([r1+r2, norm])
       >  is r1+r2 greater than norm?

```

# Answer
> 0 votes
# R (+pryr), 31 bytes

```
pryr::f(sum((x-y)^2)^.5<sum(r))

```

Which evaluates to the function

```
function (x, y, z)
sum((x - y)^2)^0.5 < sum(z)

```

Where `x` are the coordinates of circle 1, `y` are the coordinates of circle 2 and `z` the radii.

Calculates the distance between the two centers using Pythagoras and tests if that distance is smaller than the sum of the radii.

Makes use of R's vectorisation to simultaneously calculate `(x1-x2)^2` and `(y1-y2)^2`. These are then summed and squarely rooted.

# Answer
> 0 votes
# Go, 93 bytes

```
package q
import c "math/cmplx"
func o(a,b complex128,r,R float64)bool{return c.Abs(b-a)<r+R}

```

Fairly simple algorithm, same as several other answers, except it uses the built-in `complex` type and calls math/cmplx.Abs().

Taking the radii as complex numbers doesn't help, because the cast to float64 adds more bytes than the variable declaration saves (can't do `float64 < complex128`).

Try it online! Includes the test cases, and uses package main instead of a library.

# Answer
> 0 votes
# Javascript, 38 chars

```
(x,y,r,X,Y,R)=>Math.hypot(X-x,Y-y)<R+r

```

Test:

```
f=(x,y,r,X,Y,R)=>Math.hypot(X-x,Y-y)<R+r

console.log(
  f(5.86, 3.92, 1.670, 11.8, 2.98, 4.571),
  f(8.26, -2.72, 2.488, 4.59, -2.97, 1.345),
  f(9.32, -7.77, 2.8, 6.21, -8.51, 0.4)
);

console.log(
  f(4.59, -2.97, 1.345, 11.8, 2.98, 4.571),
  f(9.32, -7.77, 2.8, 4.59, -2.97, 1.345),
  f(5.86, 3.92, 1.670, 6.21, -8.51, 0.4)
);
```

# Answer
> 0 votes
# QBIC, 30 bytes

```
?abs(:-:)^2+abs(:-:)^2<(:+:)^2

```

Basically does `a²+b²=c²`. Takes parameters in the order of `x1, x2, y1, y2, r1, r2`.

```
                 The code builds a triangle y doing a²+b²=c²
?abs(:-:)^2      Takes the size of our triangle along the x-axis
+abs(:-:)^2      Takes the size of our triangle along the y-axis
 (:+:)^2         Takes the length of both radii
<                And compares them. The circles overlap (-1) if their combined
                 radii is bigger than the c-side of the triangle

```

# Answer
> 0 votes
# Swift, 47 Bytes

```
($0-$3)*($0-$3)+($1-$4)*($1-$4)<($2+$5)*($2+$5)

```

`$0, $1, ...` are *implicit closure parameters*. To use, assign to a variable with a type annotation:

```
let f: (
    _ x1: Double, // $0 ----+
    _ y1: Double, // $1 ----|----+
    _ r1: Double, // $2 ----|----|----+
    _ x2: Double, // $3 ----+    |    |
    _ y2: Double, // $4 ---------+    |
    _ r2: Double  // $5 --------------+
    ) -> Bool = {
     ($0-$3)*($0-$3)+($1-$4)*($1-$4)<($2+$5)*($2+$5)
}

```

# Answer
> 0 votes
# Perl 5, 54 bytes

```
$_=$F[2]+$F[5]>sqrt(($F[0]-$F[3])**2+($F[1]-$F[4])**2)

```

Try it online!

Input format:

*x1 y1 r1 x2 y2 r2*

---
Tags: code-golf, decision-problem
---


title: This Question Has _____ Views

text:
# Question
Title: This Question Has _____ Views
Inspired by this Youtube Video from Tom Scott.

Write a program or function that prints the current amount of views this question has.

That's it.

Your program may only access the stack exchange api, any other websites are disallowed.

## Output

An integer with the exact amount of views this question has at the moment. Outputs with the `k` for thousand are disallowed.

# Answer
> 5 votes
# 05AB1E, ~~46~~ ~~42~~ 36 bytes

**Reading from the question-URL: 36 bytes**

```
’ƒËŠˆ.Â‚‹º.ŒŒ/q/’žYì•3X&•«.w'Ž‡¡1èþ¨

```

-6 bytes thanks to *@CommandMaster*, by reading from this question's URL instead of the API

No direct TIO, since the `.w` builtin (to access a website) is disabled on TIO. But:

```
’ƒËŠˆ.Â‚‹º.ŒŒ/q/’žYì•3X&•«

```

Try this part online to see the generation of the URL.

```
'Ž‡¡1èþ¨

```

Try this part online to see the extraction of the amount of views from the HTML content. (Input doesn't contain the entire HTML content, because the TIO URL would extend 65k+ characters and be too big to post, haha.. xD)

**Reading from the API: ~~46~~ 42 bytes**

```
•3X&•’¸¸.Â‚‹º.ŒŒ/…é/ÿ?€¼=ƒËŠˆ’žYì.w'š‹¡Åsþ

```

No direct TIO, since the `.w` builtin (to access a website) is disabled on TIO. But:

```
•3X&•’¸¸.Â‚‹º.ŒŒ/…é/ÿ?€¼=ƒËŠˆ’žYì

```

Try this part online to see the generation of the API-URL.

```
'š‹¡Åsþ

```

Try this part online to see the extraction of the amount of views from the JSON.

**Explanation:**

```
’ƒËŠˆ.Â‚‹º.ŒŒ/q/’
              # Push dictionary string "codegolf.stackexchange.com/q/"
 žY           # Push builtin "https://"
   ì          # And prepend it in front of the url
    •3X&•     # Push compressed integer 203590 (the id of this question)
         «    # Append it to the url
          .w  # Access this URL and read its contents
'Ž‡          '# Push dictionary string "wed"
   ¡          # Split the HTML on this word
    1è        # Get the second item (at index 1)
              #  (i.e. ` 119 times">\n                    <span class="fc-light mr2">Vie`)
      þ       # Only leave the digits (i.e. 1992)
       ¨      # And remove the last digit (2), that was part of the class
              # (after which it is output implicitly as result)

•3X&•         # Push compressed integer 203590 (the id of this question)
 ’¸¸.Â‚‹º.ŒŒ/…é/ÿ?€¼=ƒËŠˆ’
              # Push dictionary string "api.stackexchange.com/questions/ÿ?site=codegolf",
              # where the `ÿ` is automatically filled with this integer
  žY          # Push builtin "https://"
    ì         # And prepend it in front of the url
     .w       # Access this URL and read its contents
'š‹          '# Push dictionary string "count"
   ¡          # Split the JSON on this word:
              #  (i.e. `...,"view_count":14,"answer_count":2,...` will be split to
              #   [`...,"view_`, `":14,"answer_`, `":2,...`])
    Ås        # Pop and only leave the middle item (i.e. `":14,"answer_`)
      þ       # Pop and only leave its digits (i.e. 14)
              # (after which it is output implicitly as result)

```

See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress large integers?*) to understand why `’ƒËŠˆ.Â‚‹º.ŒŒ/q/’` is `"codegolf.stackexchange.com/q/"`; `•3X&•` is `203590`; `'Ž‡` is `"wed"`; `’¸¸.Â‚‹º.ŒŒ/…é/ÿ?€¼=ƒËŠˆ’` is `"api.stackexchange.com/questions/ÿ?site=codegolf"`; and `'š‹` is `"count"`.

# Answer
> 2 votes
# JavaScript (browser), ~~129~~ ~~121~~ ~~129~~ 117 bytes

-12 bytes thanks to Kevin Cruijssen, Command Master!

```
await fetch`//api.stackexchange.com/questions/203590?site=codegolf`.then(x=>x.json()).then(x=>x.items[0].view_count)

```

## Another version, not using await (~~136~~ ~~128~~ 136 bytes):

```
fetch('https://api.stackexchange.com/2.2/questions/203590?site=codegolf').then(x=>x.json()).then(x=>console.log(x.items[0].view_count))

```

# Answer
> 2 votes
# Google Sheets, ~~99~~ 95 bytes

```
=Mid(Index(ImportData("https://api.stackexchange.com/questions/203590?site=codegolf"),10),12,99

```

Sheets will add the trailing parentheses automatically.

`ImportData` will treat the result as a CSV and split the text into columns.
`Index(~,10)` pulls the 10th entry from that split result.
`Mid(~,12,99)` starts at the 12th character and pulls up to the next 99.

So long as the view count doesn't get to 10^99, this will work fine.

Here's a screenshot showing the three steps:

# Answer
> 1 votes
# Python 2, ~~125~~ 117 bytes

*-6 bytes thanks to Kaddath*

Using only the standard library, unlike the other python answer.

```
from urllib import*
x=urlopen("http://codegolf.stackexchange.com/q/203590").read()
print x[x.find("wed"):].split()[1]

```

# Python 3, ~~149~~ 142 bytes

*-6 bytes thanks to Kaddath*

```
from urllib.request import*
x=urlopen("http://codegolf.stackexchange.com/q/203590").read().decode("utf-8")
print(x[x.find("wed"):].split()[1])

```

# Answer
> 1 votes
## sh, 96 bytes

```
wget -qO- http://codegolf.stackexchange.com/questions/203590|sed -n 's/.*\(V.*mes\).*/\1/p;540q'

```

This assumes the presence of `wget` and `sed`. We can save 5 bytes (the `;540q` part) if we can assume there's no more match of `V.*mes` on the page -- as of this writing, there isn't, but that may not be true after more submissions. This also assumes the first part of the page is fairly static, and the `Viewed XXX times` sentence appears uniquely before line 540 (which it currently does).

## sh, 101 bytes

```
wget -qO- http://codegolf.stackexchange.com/questions/203590|sed -n 's/.*\(V.*mes\).*/\1/p;/V.*mes/q

```

Similar to the above, but this variation does not depend on which line the `Viewed XXX times` appears -- it terminates after the finding the first one.

# Answer
> 0 votes
# Python 2 with `requests`, 113 bytes

```
from requests import*
t=get('http://codegolf.stackexchange.com/q/203590').text
print t[t.find('wed'):].split()[1]

```

A pair of `()` is needed for Python 3 (114 bytes).

# Answer
> 0 votes
# PHP, ~~96~~ 89 bytes

```
<?=split(' ',strstr(join(file('http://codegolf.stackexchange.com/q/203590')),'wed '))[1];

```

Inspired by @newbie's answer. I think I can do better, still a first try. I strangely only got malformed characters from the JSON api :/

EDIT gained 7 bytes using `split` and `strstr` instead of `preg_match`

# Answer
> 0 votes
# Bash + common tools, 67

```
lynx -dump codegolf.stackexchange.com/q/203590|grep -Po 'wed \K\d+'

```

# Answer
> 0 votes
# T-SQL, 43 bytes

T-SQL executed directly against the Stack Exchange Data Explorer:

```
SELECT ViewCount FROM Posts WHERE Id=203590

```

Based on my answer to this similar question.

---
Tags: code-golf, stack-exchange-api
---