title: ASCII-art to numbers

text:
# Question
Title: ASCII-art to numbers
Inspired by Digits in their lanes

## Input:

An ASCII-art of width ≤ 11, consisting of spaces and `#`. (You can choose any two distinct characters instead.) Example:

```
     #
    ###
     #
     #
    # #
   #   #
  #     #
 #  ###  #
#   ###   #
###########
#         #
#         #
#   ###   #
#   ###   #
#   ###   #
###########

```

## Output:

A list of integers, with one element for each line of the input. If you put a hash in each decimal digit's lane, including the minus sign, in the order `-0123456789`. Duplicated digits are allowed, but ignored. The order of the digits in the output is not important. Possible outputs for the above input include:

```
[ 4, 345, 4, 4, 35, 26, 17, 34580, -3459, -9876543210, -9, -9, -3459, -3459, -3459, -1234567890 ]
[ 4444444, 5345354354, 4, 44, 535, 2666, 71, 85430, -3495939495, -93678132645160234, -99, -99999, -934539, -935439, -9534, -9876543210 ]

```

Note that you have to distinguish between 0 and -0. If your output format doesn't support that, you can say there is a special value for -0 (e.g. `None`).

### Leading zeros

If a number is 0 (or -0), the zero is always counted.

Else, you have to move the zero after the first digit (not necessarily next to it): For example, -09 stands for `-` and `9`, so you have to output -90 instead. So, even if you output the string `"-09"` where `-`, `0` and `9` are `#`, that is not right.

* In your output, leading zeroes are not counted (that is, the output is the same as if those leading zeroes are removed). This does also include zeroes directly after the minus signs.

+ Here are some examples for clarification:

    ```
    -0123456789    OK           not OK
    ##          -> -0
    ###         -> -10          -01
    ##        # -> -90          -09
     ##         -> 10           01
      #         -> 01           10

    ```
* **This does also apply when you output a string!**

## General rules

* You can assume that in every line, at least one of 0-9 is a `#` (not empty or only `-`)
* You can submit a program or function
* Choose any reasonable input/output format (eg. list of lines, list of characters, etc.)

## Scoring

* Your score is the number of bytes in your code.
* Lowest score wins.

## Loopholes

## Examples

Note that there is an infinite number of correct outputs for every input, here, only one is mentioned. If you need to verify an output, you can usually use an answer to Digits in their lanes and input your output. Then compare it's output with the original input.

```
     #         4
    ###        345
     #         4
     #         4
    # #        35
   #   #       26
  #     #      17
 #  ###  #     83450
#   ###   # -> -9534
###########    -9876543210
#         #    -9
#         #    -9
#   ###   #    -3459
#   ###   #    -3459
#   ###   #    -3459
###########    -1234567890

 #########     123456780
#         #    -9
#  ##  ## #    -23679
# #   #   #    -159
# #   # # #    -1579
#  ##  ## # -> -23679
#         #    -9
 ##### ###     12346780
     ##        45
     #         4

##   ##  ##    -45890
# # #   #      -137
##  #   #   -> -370
#   #   # #    -379
#    ##  ##    -4589

## ## ## ##    -2356890
#  #     ## -> -289
#  #           -2

##             -0
 ##            10
  ##           12
   ##          23
    ##      -> 34
     ##        45
      ##       56
       ##      67
        ##     78
         ##    89

```

# Answer
> 2 votes
# Stax, 11 bytes

```
ñ╬ü+U☻T→╡aN

```

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

```
m           for each line of input, run the rest and implicitly output
  |(        rotate string left once
  :A        get indices of maxima (indices of '#')
  Vd'-+s    push "0123456789-" under the top of the stack
  @         get characters at indices
  r         reverse string; puts '-' at the front
            output is implicit

```

Run this one

# Answer
> 3 votes
# Jelly, 13 bytes

<sup>...turns out it's slightly different to Dylnan's method, I thought they just beat me to it</sup>

```
ṙ€1T€ịØD;”-¤U

```

A monadic link accepting a list of lists of 1s and 0s which returns a list of lists of characters the output "numbers".

**Try it online!**

### How?

```
ṙ€1T€ịØD;”-¤U - Link: list of lists of integers (in {0,1})
ṙ€1           - rotate €ach list left by one
   T€         - get the truthy (1-based) indices of €ach
           ¤  - nilad followed by link(s) as a nilad:
      ØD      -   decimal digit characters = "0123456789"
         ”-   -   literal '-' character
        ;     -   concatenate
     ị        - index into (vectorises)
            U - upend (reverses each resulting list of characters)

```

# Answer
> 2 votes
# Perl 5 `-lp`, 35 bytes

Uses `#` and `;`

```
#!/usr/bin/perl -lp
s/./"$&@--1"/eeg;s/-1/-/;s;0(.);$+0

```

Try it online!

# Answer
> 1 votes
# 05AB1E, ~~18~~ 17 bytes

Currently 3 bytes to make sure the number doesn't start with zero. Looking for a shorter way.

```
vžh'-ìyƶ0K<ΣΘ}èJˆ

```

Try it online! or with ascii-art input

Uses **1** instead of **#** and **0** instead of **space**.

# Answer
> 1 votes
# JavaScript (ES7), ~~60~~ 55 bytes

Takes input as an array of strings with `0` instead of `#`. Returns an array of strings.

```
a=>a.map(r=>('-'+2**67).replace(/./g,c=>[c[r[++c|0]]]))

```

Try it online!

### Commented

```
a =>                    // given the input array a[]
  a.map(r =>            // for each row r of a[]
    ('-' + 2**67)       //   generate the string '-147573952589676410000'
    .replace(/./g, c => //   replace each character c of r with either c or ''
      [                 //     wrap the result into [] so that undefined is coerced to ''
       c[               //     read c['0'] (gives c) or c[' '] (gives undefined)
         r[             //     read r[] --> gives '0' or ' '
           ++c | 0]]]   //     gives (NaN | 0) = 0 if c is '-', or (c + 1) if c is a digit
    )                   //   end of replace()
  )                     // end of map()

```

# Answer
> 1 votes
# Java 10, ~~176~~ 136 bytes

```
c->{int l=c.length,i=0,j;var o=new String[l];for(String s;i<l;o[i]=c[i++][0]<8?"-"+s:s)for(s="",j=10;j>0;)s+=c[i][j--]<8?j:"";return o;}

```

Returns an array of Strings. Uses the *BEL* character instead of *#*.

Try it online here.

Thanks to Kevin Cruijssen for golfing 40 bytes.

Ungolfed version:

```
c -> { // lambda taking a char[][] as argument
    int l = c.length, // the number of lines
    i = 0, //used for iterating over all lines
    j; // used for iterating over each line
    var o = new String[l]; // output array
    for(String s; // the output for the current line
        i < l; // iterate over all lines
        o[i] = c[i++][0] < 8 ? "-"+s : s) // add a minus if necessary
        for(s = "", j = 10; j>0; ) // to avoid leading zeroes, we step through the line backwards
            s += c[i][j--] < 8 ? j : ""; // append the next digit, if applicable
    }
    return o; // return the output array
}

```

# Answer
> 1 votes
# Jelly, ~~20~~ 14 bytes

```
ØD”-;ẋ"Ð€ṙ€1Ṛ€

```

Try it online!

Function submission. Takes a list of lines as input. Characters are `1` for on and `0` for off.

**Explanation**

```
ØD”-;ẋ"Ð€ṙ€1Ṛ€
ØD               Digits 0-9 as characters
  ”-             Character literal -
    ;            Concatenate -> -0123456789
                 Turn each 0 and 1 from the input (characters) into an integer.
       Ð€        For each list of integers 0 and 1 corresponding to the list of lines in the input...
      "          Zip the characters -0123456789 with the 0s and 1s.
     ẋ           Include each of the characters if paired with a 1, not if paired with a 0.
                 Characters that get included turn into ['3'] (3 as an example)
                 Those that don't turn into []. This is important for the next step.
          €      For each of the lists of [character]s and []s.
         ṙ 1     rotate it by 1. This moves the ['-'] or [] in place of ['-'] to the end of the line.
            Ṛ€   Reverse €ach line. Brings the ['-'] to the front and the leading ['0'] if present to the end.

```

# Answer
> 1 votes
# APL+WIN, 58 bytes

Prompts for a character matrix:

```
(⊂[2]z[;1],⌽0 1↓z←' -0123456789'[1+n×(⍴n←⎕='#')⍴⍳11])~¨' '

```

Outputs digits in reverse order to cope with leading zeros.

# Answer
> 1 votes
# Python 2, 74 bytes

```
lambda s:[''.join(`i-1`[0]for i in[0]+range(10,0,-1)if' '<l[i])for l in s]

```

Try it online!

# Answer
> 0 votes
# Perl 6, 54 bytes

```
{.map:{(.ords.grep(:k,*>32)X-1).sort(1/*)>>.ord.chrs}}

```

Try it online!

Takes a list of lines. Explanation:

```
{
    .map:{                     # For each line.
        (.ords.grep(:k,*>32)   # Find non-whitespace indices.
         X- 1)                 # Decrement each, range is now -1..9.
        .sort(1/*)             # Sort by reciprocal, moving 0s to the end.
        >>.ord.chrs            # Join first characters.
    }
}

```

# Answer
> 0 votes
# , 83 bytes

```
for(i in gregexpr("#",readLines()))cat(sub(99,0,sort(c("-",99,1:9)[i])),'
',sep="")

```

Try it online!

A nasty 83 bytes; would have been so much shorter (and simpler of a challenge, I suppose) to not have to move the `0` to the end. Ah well. Uses `99` in place of `0` to utilize `sort` to move `0` to the end, but that comes at the cost of having to use `sub`.

# Answer
> 0 votes
# C# (Visual C# Compiler), 123 bytes

```
using System.Linq;l=>l.Select(k=>{var c=k[0]!=' '?"-":"";for(int a=k.Length;a>1;a--)if(k[a-1]!=' ')c+=$"{a-2}";return c;});

```

Try it online!

# Answer
> 0 votes
# Retina 0.8.2, 34 bytes

```
(.)(.*)
$2$1
-(?=.)
$.%`

%O^$`.

```

Try it online! Takes input using `-`s instead of `#`s, but the linked header includes the substitution. Explanation:

```
(.)(.*)
$2$1

```

Move the first character of each line to the end.

```
-(?=.)
$.%`

```

Replace each `-` not at the end of a line with its column number.

```

```

Delete the spaces.

```
%O^$`.

```

Reverse each line.

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


title: Console print a bar graph

text:
# Question
Title: Console print a bar graph
The objective is to print a graph from an array of numbers, of the design below. Printing the X and Y scale exactly as in the "design", with padding, is part of the challenge. The input array of numbers can be of virtually any range of integers in X and Y, but not 0 and not negative - though I would suggest keeping it small considering this is ASCII art! (x \< 15, y \< 50 or so).

**Specifics**

1) the graph should print the Y scale on the left, padded to the max length of the input, and with a pipe '|' between the number and the first column.

2) the bar should have all empty spaces with periods '.' filled spaces with pipes '|' and the number itself should be an 'o'.

3) there are three "tween" columns between each number that interpolates between the two numbers. These cannot just be a duplication of the previous or next column, but need to interpolate between the values linearly. (Unless two adjacent numbers in the list are only 1 apart or the same.)

4) The bottom of the graph should look: " +---------" to the length of the graph.

5) There should be an X scale padded to the length of the max number, similar to the Y scale. The last digit of the x scale should align with the value (I guess that means we're limited to two digits...)

6) Lastly, there should be an "empty" column in the beginning of the graph and an "empty" column at the end.

**Example**

This:

```
 [5, 3, 7, 8, 10, 7, 8, 7, 9, 2]

```

Generates:

```
10|.................o.....................
09|................||...............o.....
08|.............o|||||......o......||.....
07|.........o||||||||||.o|||||..o||||.....
06|........|||||||||||||||||||||||||||....
05|.o.....||||||||||||||||||||||||||||....
04|.||...|||||||||||||||||||||||||||||....
03|.|||.o||||||||||||||||||||||||||||||...
02|.|||||||||||||||||||||||||||||||||||.o.
01|.|||||||||||||||||||||||||||||||||||||.
  +---------------------------------------
   01  02  03  04  05  06  07  08  09  10

```

Trailing spaces on each line, or trailing newlines at the end are permitted. As long as the output is visually the same.

Here's a working Python3 example, in "long hand" if you wish:

Try it online!

# Answer
# JavaScript (Node.js), 316 bytes

```
a=>a.map((x,i)=>{d=Math.abs(x-~-(n=a[i+1]))/3
for(i in n?"    ":s=" ")for(j in o="|o"[+!+i].padEnd(x>n?x-d*i|0:x+d*i|0,"|")[S="padStart"](m,"."))A[j]+=o[j]},A=Array((m=Math.max(...a))+2).fill(""))&&A.map((x,i)=>x?(m-i+"|.")[S](4,0)+x+".":i>m?s+s+a.map((_,I)=>s+(-~I+s)[S](3,0)).join``:"  +".padEnd(a.length*4+2,"-"))

```

Try it online!
> 2 votes

# Answer
# Python 2, ~~261~~ 246 bytes

```
lambda a:[["   0","  +-","%02d|."%~-i][min(i,2)]+"".join(s)[3:]+" -."[min(i,2)]for i,s in enumerate(zip(*[list(("  %02d"%-~j)[i]+"-"+"o|"[i<3].rjust(a[j-1]+(v-a[j-1])*-~i/4,"|").ljust(max(a),"."))for j,v in enumerate(a)for i in range(4)]))][::-1]

```

Try it online!

Anonymous lambda returning the list of strings comprising the chart. Performs linear interpolation between points with floor rounding, in 4 steps from `a[i-1]` to `a[i]`.

# Python 2, ~~271~~ 256 bytes

```
lambda a:[["   0","  +-","%02d|."%~-i][min(i,2)]+"".join(s)[3:]+" -."[min(i,2)]for i,s in enumerate(zip(*[list(("  %02d"%-~j)[i]+"-"+["o".rjust(v,"|"),"|"*(a[j-1]+(v+~a[j-1])*-~i/3)][i<3].ljust(max(a),"."))for j,v in enumerate(a)for i in range(4)]))][::-1]

```

Try it online!

Alternative version that interpolates in the same manner as defined in the OP's reference code. Interpolation occurs in 3 steps from `a[i-1]` to `a[i]-1`. This way, the value of the third 'tween' column is always 1 below the actual data point, and these two columns always have the same number of pipes. This matches the reference code except for zero values, which we are not required to support.

Probably the longest lambda I've ever written to date. Will try to revisit and golf a bit more when I have time.
> 2 votes

# Answer
# Python 3, 505, 484, 480 bytes

```
i=list(map(int,input().split(',')))
l=len(i)
r=range
e=enumerate
m=max(*i)
s=len(str(m))
t='%%0%dd'
f=t%s
g=t%len(str(l))
d=[['.']*(l*4+s)for _ in r(m+2)]
for x,y in e(d):y[:s]=f%(m-x);y[s]='|'
d[-2][:]=' '*s+'+'+'-'*(l*4-1)
d[-1][:s+2]=' '*(s+2)
d[-1][s+1:]=['%-4s'%(g%-~x)for x in r(l)]
for x,y in e(i):
 n=y
 def r(z,o):
  for v in d[m-n+(n-y)*z//4+1:m]:v[x*4+s+o]='|'
 d[m-y][x*4+s+2]='o';r(0,2)
 if x==l-1:break
 n=i[x+1];r(3,3);r(2,4);r(1,5)
print('\n'.join(map(''.join,d)))

```

Try it online!

With some help of @kevin-cruijssen
-25 with some cleanup in newlines etc. by me

Could probably be compacted a bit more
> 2 votes

# Answer
# PHP, 231 bytes

```
for($e=strlen($y=max($argv));$y>$x=0;$y-=print".
")for(printf("%{$e}d|.",$y);$n=$argv[++$x];print"o.|"[$y<=>$n])while($x>1&&++$k%4)echo".|"[$y<$p+=$n/4-$p/4];echo str_pad("  +",$argc*4-1,"-"),"
 ";while(++$x<$argc)printf("%4d",$x);

```

## fixed width (y\<100), 219 bytes

```
for($y=max($argv)+1;--$y>$x=0;print".
")for(printf("%2d|.",$y);$n=$argv[++$x];print"o.|"[$y<=>$n])while($x>1&&++$k%4)echo".|"[$y<$p+=$n/4-$p/4];echo str_pad("  +",$argc*4-1,"-"),"
 ";while(++$x<$argc)printf("%4d",$x);

```

requires PHP 7.1 for negative string indexing. Run with `-nr` or try them online.
> 2 votes

# Answer
# Jelly, 68 bytes

```
J+ȷ2DḊ€
x4S4Ƥ:4;00;”|ẋ”o0¦€2¦4ÐƤẎz”.µÇ,"j€”|ṚY⁷⁶⁶”+³Çj⁾  ;©⁶”-ṁ⁷⁶⁶⁶®

```

Try it online!
> 2 votes

# Answer
# Charcoal, ~~110~~ ~~106~~ 103 bytes

```
ＡθＵＢ.⮌Ｅ⌈θ⁺⁺×0⁻Ｌ⌈θＬ⊕κκ|Ｇ↓²→Ｌ⌈θ↑² ↓Ｐ⁺⪫Ｅθ◧⁺×0⁻ＬＬθＬ⊕κκ⁴ω ↗≔Ｅ⁻×⁴Ｌθ³§θ÷κ⁴θ+Ｐ⁺²Ｌθ↗↑Ｅθ⎇﹪κ⁴⁺ι÷×﹪κ⁴⁻§θ⁺⁴κι⁴⁺×|⊖ιo

```

Try it online! Link is to verbose version of code. Edit: Saved 3 bytes thanks to @ASCII-only. Explanation:

```
Ａθ

```

Input the array.

```
ＵＢ.

```

Set the background of the output to `.`.

```
⮌Ｅ⌈θ⁺⁺×0⁻Ｌ⌈θＬ⊕κκ|

```

Print the Y-axis with its labels left padded with zeros.

```
Ｇ↓²→Ｌ⌈θ↑² ↓

```

Blank out the bottom left corner so that it isn't filled with `.`s.

```
Ｐ⁺⪫Ｅθ◧⁺×0⁻ＬＬθＬ⊕κκ⁴ω ↗

```

Print the X labels.

```
≔Ｅ⁻×⁴Ｌθ³§θ÷κ⁴θ

```

Repeat the values in the array 4 times (except for the last value).

```
+Ｐ⁺²Ｌθ↗↑

```

Print the X-axis.

```
Ｅθ⎇﹪κ⁴⁺ι÷×﹪κ⁴⁻§θ⁺⁴κι⁴⁺×|⊖ιo

```

Print the graph itself, repeating `|`s with a final `o` for multiples of 4 and interpolating for intermediate values.
> 2 votes

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


title: Sum of five cubes

text:
# Question
Title: Sum of five cubes
Given an integer, output five perfect cubes whose sum is that integer. Note that cubes can be positive, negative, or zero. For example,

```
-10 == -64 - 64 + 64 + 27 + 27

```

so for input `-10` you could output `[-64, -64, 64, 27, 27]`, though other solutions are possible. Note that you should output the cubes, not the numbers being cubed.

A solution always exists -- you might enjoy puzzling this out for yourself. It's further conjectured that four cubes suffice.

# Answer
> 16 votes
# Brachylog, 18 bytes

```
∧5~lLȧᵐ≥₁∧L^₃ᵐ.+?∧

```

Try it online!

### Explanation

We basically describe the problem, with the additional constraint that we want the output list to be non-increasing in terms of magnitudes: this forces Brachylog to properly backtrack over all possible combinations of 5 values, instead of infinitely backtracking over the value of the last element of the list.

```
∧                ∧    (disable some implicit stuff)
 5~lL                 L is a list of length 5
    Lȧᵐ≥₁             L must be a non-increasing list in terms of magnitude
         ∧
          L^₃ᵐ.       The output is L with each element cubed
              .+?     The sum of the output is the input

```

### Finding different solutions

By appending a , it's possible to use this predicate to find all solutions with increasing magnitudes: for example, here are the first 10 solutions for `42`

# Answer
> 15 votes
# Brachylog, 11 bytes

Thanks Fatalize for saving one byte

```
~+l₅≥₁.√₃ᵐ∧

```

Try it online!

Firstly `~+` enforces that the output (`.`) must sum to the input. `l₅` again constrains the output, dictating that it must have a length of 5. `≥₁` declares that the list must be in decreasing order (I believe that this is necessary to stop the program entering an infinite loop)

We explicitly unify this list with `.`, the output variable, because our next predicate will "change" the values inside the list. We then take the cube root of each value in the list with `√₃ᵐ`. Since Brachylog is inherently integer-based, this dictates that all the numbers in the list are cube numbers.

Finally, we use  because there is an implicit `.` added to the end of each line. Since we don't want `.` to be unified with the list of cube roots, we unified it earlier on and use  to stop it unifying at the end.

# Answer
> 10 votes
# Python 2, ~~58~~ ~~57~~ 54 bytes

```
def f(n):k=(n**3-n)/6;return[v**3for v in~k,1-k,n,k,k]

```

Try it online!

---

* -2 bytes, thanks to Rod
* -1 byte, thanks to Neil

# Answer
> 9 votes
# Python 3, 65 bytes

```
def f(n):k=(n-n**3)//6;return[n**3,(k+1)**3,(k-1)**3,-k**3,-k**3]

```

Try it online!

I mean, an explicit formula is even here (although he abstracted the construction behind an existential)

# Answer
> 7 votes
# Java 8, ~~178~~ ~~87~~ ~~73~~ ~~71~~ 65 bytes

```
n->new long[]{n*n*n,(n=(n-n*n*n)/6+1)*n*n--,--n*n*n,n=-++n*n*n,n}

```

-6 bytes thanks to *@OlivierGrégoire*.

Same explanation at the bottom, but using the base equation instead of the derived one I used before (thanks to *@LeakyNun*'s Python 3 answer for the implicit tip):

***k = (n - n3) / 6
n == n3 \+ (k+1)3 \+ (k-1)3 \- k3 \- k3***

Try it online.

---

**Old 178 bytes answer:**

```
n->{for(long k=0,a,b,c,d;;){if(n==(a=n*n*n)+(b=(d=k+1)*d*d)+(c=(d=k-1)*d*d)-(d=k*k*k++)-d)return a+","+b+","+c+","+-d+","+-d;if(n==a-b-c+d+d)return-a+","+-b+","+-c+","+d+","+d;}}

```

Try it online.

**Explanation:**

I loop `k` from 0 upwards until a solution is found. In every iteration it will check these two equations:

* Positive `k`: *n == n3 \+ (k+1)3 \+ (k-1)3 \- k3 \- k3*
* Negative `k`: *n == n3 \- (k+1)3 \- (k-1)3 \+ k3 \+ k3*

**Why?**

Since ***n - n3 = n\*(1-n)\*(1+n)*** and then ***6|(n-n3)***, it can be written as ***n - n3 = 6k***.
***6k = (k+1)3 \+ (k-1)3 \- k3 \- k3***.
And therefore ***n = n3 \+ (k+1)3 \+ (k-1)3 \- k3 \- k3*** for some ***k***.
Source.

# Answer
> 7 votes
# Jelly, 13 bytes

```
‘c3µ;;C;~;³*3

```

Try it online!

Figure out the formula independently. (x+1)3 \+ (x-1)3 \- 2 × x3 == 6 × x.

---

```
 === Explanation ===
‘c3µ;;C;~;³*3   Main link. Input: (n).
‘               Increment.
 c3             Calculate (n+1)C3 = (n+1)×n×(n-1)÷6.
   µ            Start a new monadic link. Current value: (k=(n³-n)÷6)
    ;           Concatenate with itself.
     ;C         Concatenate with (1-k).
       ;~       Concatenate with bitwise negation of (k), that is (-1-k)
         ;³     Concatenate with the input (n).
           *3   Raise the list [k,k,1-k,-1-k,n] to third power.
                End of program, implicit print.

```

Alternative 13 bytes: Try it online!

# Answer
> 5 votes
# Octave, ~~47~~ ~~40~~ 33 bytes

```
@(n)[k=(n^3-n)/6,k,-k-1,1-k,n].^3

```

Try it online!

Saved 6 bytes thanks to Giuseppe, since I had forgotten to remove some old parentheses. Saved another bytes by changing the signs, thanks to rafa11111.

Uses the formula in the linked math.se post:

1. Since **n - n^3 = n(1-n)(1+n)** then **6 | (n - n^3)** and we can write **n - n^3 = 6k**.
2. **6k = (k+1)^3 + (k-1)^3 - k^3 - k^3**.

It appears to be longer if I try to *solve* the equation: **(n-n^3)=(k+1)^3 + (k-1)^3 - k^3 - k^3** with regards to **k**, instead of just using the equation.

# Answer
> 4 votes
# Minecraft Functions (18w11a, 1.13 snapshots), 813 bytes

Uses six functions:

a

```
scoreboard objectives add k dummy
scoreboard objectives add b dummy
scoreboard objectives add c dummy
scoreboard players operation x k = x n
function d
function f
scoreboard players operation x k -= x b
scoreboard players set x b 6
scoreboard players operation x k /= x b
scoreboard players set x b 1
function d
scoreboard players operation x c += x b
function f
scoreboard players set x b 1
function d
scoreboard players operation x c -= x b
function f
function d
function e
scoreboard players operation x b -= x c
scoreboard players operation x b -= x c
function c
function b

```

b

```
tellraw @s {"score":{"name":"x","objective":"b"}}

```

c

```
scoreboard players operation x b *= x c
scoreboard players operation x b *= x c
function b

```

d

```
scoreboard players operation x c = x k

```

e

```
scoreboard players operation x b = x c

```

f

```
function e
function c

```

"Takes input" from a scoreboard objective named `n`, create it with `/scoreboard objectives add n dummy` and then set it using `/scoreboard players set x n 5`. Then call the function using `/function a`

Uses the formula from this math.se answer

# Answer
> 2 votes
# Haskell, ~~43~~ 42 bytes

```
p n|k<-div(n^3-n)6=map(^3)[n,-k-1,1-k,k,k]

```

Just the popular answer, translated to Haskell. Thanks to @rafa11111 for saving a byte!

Try it online!

# Answer
> 2 votes
# JavaScript (Node.js), 48 45 bytes

* thanks to @Arnauld for reducing 3 bytes

```
n=>[n,1-(k=(n**3-n)/6|0),~k,k,k].map(x=>x**3)

```

Try it online!

# Answer
> 2 votes
# MATL, 21 bytes

```
|_G|&:5Z^3^t!sG=fX<Y)

```

This tries all 5-tuples of numbers from the set `(-abs(n))^3, (-abs(n)+1)^3, ..., abs(n)^3`. So it is very inefficient.

Try it online!

# Answer
> 2 votes
# Husk, 12 bytes

```
ḟo=⁰Σπ5m^3İZ

```

Try it online!

Tries all possible lists of 5 cubes, and returns the first one with the correct sum.

### Explanation

```
ḟo=⁰Σπ5m^3İZ
          İZ    List of all integers [0,1,-1,2,-2,3,-3...
       m^3      Cube of each integer [0,1,-1,8,-8,27,-27...
     π5         Cartesian power with exponent 5. This returns a list of all possible
                lists built by taking 5 elements from the input list. This infinite
                list is ordered in such a way that any arbitrary result occurs at a
                finite index.
ḟo              Find and return the first element where...
    Σ             the sum of the five values
  =⁰              is equal to the input

```

# Answer
> 1 votes
# C (gcc), 85 81 75 bytes

Saved 4 bytes and then 6 bytes thanks to @ceilingcat's re-ordering of assignments

```
r[5];f(n){r[1]=(n=(n-(*r=n*n*n))/6+1)*n*n--;r[3]=r[4]=-n*n*n;r[2]=--n*n*n;}

```

Try it online!

# Answer
> 1 votes
# APL (Dyalog Unicode), ~~30~~ 26 bytes

```
3*⍨⊢,∘(1 ¯1∘+,2⍴-)6÷⍨⊢-*∘3

```

Try it online!

APL translation of LeakyNun's answer.

Thanks to Adám for 4 bytes by going tacit.

### How?

```
3*⍨⊢,∘(1 ¯1∘+,2⍴-)6÷⍨⊢-*∘3 ⍝ Tacit function
                   6÷⍨⊢-*∘3 ⍝ (n-n^3)/6 (our k)
                 -)         ⍝ Negate
               2⍴           ⍝ Repeat twice; (yields -k -k)
       (1 ¯1∘+,             ⍝ Append to k+1, k-1
     ,∘                     ⍝ Then append to
    ⊢                       ⍝ n
3*⍨                         ⍝ And cube everything

```

# Answer
> 1 votes
# Python 3, ~~65~~ ~~61~~ 60 bytes

```
lambda N:[n**3for k in[(N**3-N)//6]for n in[N,-k-1,1-k,k,k]]

```

Edit: dropped some unnecessary spaces.

Edit: thanks to rafa11111's smart reordering.

Inspired by this.

Try it online!

# Answer
> 1 votes
# Fortran (GFortran), 53 bytes

```
READ*,N
K=(N**3-N)/6
PRINT*,(/N,1-K,-1-K,K,K/)**3
END

```

Try it online!

Fortran outgolfing Python? What's going on here?

# Answer
> 1 votes
# , ~~40~~ 38 bytes

Makes use of the formula in the linked math.SE post. Down to 2 bytes thanks to Giuseppe.

```
c(n<-scan(),k<-(n^3-n)/6,k,1-k,-k-1)^3

```

Try it online!

# Answer
> 1 votes
# Husk, 20 bytes

```
m^3m‼:_:→:←;K¹÷6Ṡ-^3

```

Try it online!

Uses the formula from this post.

### Explanation

```
m^3m‼:_:→:←;K¹÷6Ṡ-^3  Implicit input
                Ṡ-    Subtract itself from it
                   ^3    raised to the third power
              ÷6       Divide by six
   m                   Map over the value with a list of functions:
           ;             Create a singleton list with
            K¹             the function of replace by the input
         :←              Append the function of decrement
       :→                Append the function of increment
    ‼:_                  Append the function of negate twice
m^3                    Cube the numbers of the list

```

# Answer
> 1 votes
# x86, ~~41~~ 39 bytes

Mostly straightforward implementation of the formula with input in `ecx` and output on the stack.

The interesting thing is that I used a cubing function, but since `call label` is 5 bytes, I store the label's address and use the 2 byte `call reg`. Also, since I'm pushing values in my function, I use a `jmp` instead of `ret`. It's very possible that being clever with a loop and the stack can avoid calling entirely.

I did not do any fancy tricks with cubing, like using `(k+1)^3 = k^3 + 3k^2 + 3k + 1`.

Changelog:

* Fix byte count using `not` instead of `neg`/`dec`.
* -2 bytes by not `xor`ing `edx` since it is probably 0 from `imul`.

```
.section .text
.globl main

main:
        mov     $10, %ecx   # n = 10

start:
        lea     (cube),%edi # save function pointer
        call    *%edi       # output n^3

        sub     %ecx, %eax  # n^3 - n
                            # edx = 0 from cube
        push    $6
        pop     %ebx        # const 6
        idiv    %ebx        # k = (n^3 - n)/6
        mov     %eax, %ecx  # save k

        call    *%edi       # output k^3
        push    %eax        # output k^3

        not     %ecx        # -k-1
        call    *%edi       # output (-k-1)^3

        inc     %ecx
        inc     %ecx        # -k+1
        call    *%edi       # output (-k+1)^3

        ret

cube:                       # eax = ecx^3
        pop     %esi
        mov     %ecx, %eax
        imul    %ecx
        imul    %ecx

        push    %eax        # output cube
        jmp     *%esi       # ret

```

Objdump:

```
00000005 <start>:
   5:   8d 3d 22 00 00 00       lea    0x22,%edi
   b:   ff d7                   call   *%edi
   d:   29 c8                   sub    %ecx,%eax
   f:   6a 06                   push   $0x6
  11:   5b                      pop    %ebx
  12:   f7 fb                   idiv   %ebx
  14:   89 c1                   mov    %eax,%ecx
  16:   ff d7                   call   *%edi
  18:   50                      push   %eax
  19:   f7 d1                   not    %ecx
  1b:   ff d7                   call   *%edi
  1d:   41                      inc    %ecx
  1e:   41                      inc    %ecx
  1f:   ff d7                   call   *%edi
  21:   c3                      ret

00000022 <cube>:
  22:   5e                      pop    %esi
  23:   89 c8                   mov    %ecx,%eax
  25:   f7 e9                   imul   %ecx
  27:   f7 e9                   imul   %ecx
  29:   50                      push   %eax
  2a:   ff e6                   jmp    *%esi

```

---

Here is my testing version that does all the cubing at the end. After the values are pushed on the stack, the cube loop overwrites stack values. It's currently ~~42~~ 40 bytes but there should be some improvements somewhere.

```
.section .text
.globl main

main:
        mov     $10, %ecx       # n = 10

start:
        push    %ecx            # output n

        mov     %ecx, %eax
        imul    %ecx
        imul    %ecx
        sub     %ecx, %eax      # n^3 - n
                                # edx = 0 from imul

        push    $6
        pop     %ecx            # const 6
        idiv    %ecx            # k = (n^3 - n)/6

        push    %eax            # output k
        push    %eax            # output k

        not     %eax            # -k-1
        push    %eax            # output -k-1

        inc     %eax
        inc     %eax            # -k+1
        push    %eax            # output -k+1

        dec     %ecx            # count = 5
        add     $20, %esp
cube:
        mov     -4(%esp),%ebx   # load num from stack
        mov     %ebx, %eax
        imul    %ebx
        imul    %ebx            # cube
        push    %eax            # output cube
        loop    cube            # --count; while (count)

        ret

```

# Answer
> 1 votes
# Ruby, 43 bytes

```
->n{[~k=(n**3-n)/6,1-k,n,k,k].map{|i|i**3}}

```

Try it online!

# Answer
> 0 votes
# Cubically, 51 characters, 55 bytes

```
⇒-6-^0+7/0»8
$F:^0%@5-7/0»8^0%@5%@5f1+8^0%@5f1-8^0%

```

Try it online!

Apparently MDXF forgot to implement the SBCS...

# Answer
> 0 votes
# Unefunge 98, 35 bytes

```
j&3k:**-6/:1-\:1+\0\-::!#@_::**.37*

```

Try it online!

It uses the popular formula from this math.se answer.

# Answer
> 0 votes
# Perl 5 `-nE`, 48 bytes

```
say$_**3for$i=($_**3-($n=$_))/6,$i,-1-$i,1-$i,$n

```

hat-tip

# Answer
> 0 votes
# PowerShell Core, 52 bytes

```
$o,(1-($k=($o*$o-1)*$o/6)),(-$k-1),$k,$k|%{$_*$_*$_}

```

Try it online!

Uses the equation `o=o^3 + (1-k)^3 + (-k-1)^3 + k^3 + k^3`, where `k=o^3 - o`; this is a minor refactoring of the popular `l=o-o^3` (with `k=-l`).

As a side note, the expression `l=o-o^3` looks like a cat with a hurt ear.

---
Tags: code-golf, arithmetic, integer-partitions
---


title: Asterisks viral

text:
# Question
Title: Asterisks viral
Given a positive integer *N* ("virality"), your program should create an ASCII-art drawing of a tree with two branches of length *N* extending downwards and/or rightwards from the top-left corner.

The direction taken by each branch *after the first asterisk* can be either rightwards or downwards, and this choice should be made *randomly*1 at every next step.

For example, given an input of 5, the output might look like:

```
***
* ***
**
 **

```

The two branches are allowed to touch (be on adjacent cells), but not overlap (be on the same cell), so the following would not be allowed:

```
***
* *
*****
  *
  *

```

## Examples

For input `1`, the only possible output is:

```
**
*

```

(This will be present in all valid outputs, since having the two branches take the same path would cause them to overlap.)

Possible outputs for an input of `3` include:

```
***
* *
**

```

```
**
***
*
*

```

For input `7`:

```
****
*  **
*   **
*
***
  *

```

For input `10`:

```
****
*  *
*********
  *
  *****

```

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

1. This should uniformly random (i.e. a 50/50 chance of each direction), or as close to uniformly random as you can get on normal hardware.

# Answer
# CJam, ~~58~~ 51 bytes

```
[TT]{_2_m*\f.+{:-},mR}ri*]ee{~\)S*\{'*t}/}%::a:.+N*

```

Try it online!

The basic idea is that we start with `[0 0]` and then repeatedly add either 0 or 1 to each element (making sure that they are never equal except at the start to avoid overlap), collecting all intermediate results.

```
[[0 0] [0 1] [0 2] [0 2] [1 3]]

```

We then create a large array of arrays where each subarray contains `*` at indices given by the corresponding pair in the original array and spaces everywhere else.

```
["*"
 "**"
 "* *"
 "* * "
 " * * "]

```

This yields diagonal slices of the output matrix (where moving left to right corresponds to moving top-right to bottom-left in the actual matrix).

We can then use `::a:.+` to "de-diagonalize" and get the resulting lines:

```
[ "**** "
  "*  *"
  "** "
  " *"
  ""     ]

```
> 5 votes

# Answer
# Java 10, ~~273~~ ~~272~~ ~~268~~ 239 bytes

```
n->{var c=new char[++n][n];for(var d:c)java.util.Arrays.fill(d,' ');for(int i=0,j=0,k=0,l=0,r=0,s=0,t=0,u=0;n-->0;){c[i+=r][j+=s]=c[k+=t][l+=u]=42;do{r=t=2;r*=Math.random();t*=Math.random();s=r^1;u=t^1;}while(i+r==k+t&j+s==l+u);}return c;}

```

Try it online here.

Thanks to Kevin Cruijssen for golfing 29 bytes.

Ungolfed version:

```
n -> { // lambda taking an int as argument
    var c = new char[++n][n]; // the output; increment the virality since the root does not count
    for(var d : c) // for every line
        java.util.Arrays.fill(d,' '); // initialize it with spaces
    for(int i = 0, j = 0, // coordinates of the first branch
            k = 0, l = 0, // coordinates of the second branch
            r = 0, s = 0, // offsets for the first branch, one will be 0 and the other 1 always except for the first '*' where the two branches overlap
            t = 0, u = 0; // offsets for the second branch, one will be 0 and the other 1 always except for the first '*' where the two branches overlap
        n-- > 0; ) { // decrement virality and repeat as many times
        c[i+=r][j+=s] = c[k+=t][l+=u] = 42; // move according to offsets and place an '*' for each branch, 42 is ASCII code
        do { // randomly pick offsets for both branches
            r = t = 2; // Math.random() provides results in [0,1)
            r *= Math.random(); // flip a coin for the first branch
            t *= Math.random(); // flip another coin for the second
            s = r^1; // set s to 0 if r=1, to 1 if r=0
            u = t^1; // set u to 0 if t=1, to 1 if t=0
        } while(i+r==k+t&j+s==l+u); // repeat if the branches overlap
    }
    return c; // return the output
}

```
> 3 votes

# Answer
# Charcoal, ~~31~~ 24 bytes

```
Ｆ²«Ｊ⁰¦⁰Ｆ⊕θ«¿ι*↓*≔‽²ι¿ＫＫ↗

```

Try it online! Link is to verbose version of code. Originally I thought it would be easier to make the first step random but it turned out to be golfier to make the first branch predictable. Explanation:

```
Ｆ²«

```

Loop twice, using index variable `i`. (This actually iterates over an implicit list, so it's safe to mutate `i` inside the loop.)

```
Ｊ⁰¦⁰

```

Jump to the origin of the canvas.

```
Ｆ⊕θ«

```

Loop `N+1` times.

```
¿ι*↓*

```

Print a `*`, but leave the cursor either to the right or below the cursor depending on the value of `i`.

```
‽²ι

```

Randomise the value of `i` for the next iteration of the inner loop.

```
¿ＫＫ↗

```

If the current character is a `*`, this means that we're the second branch and we went down instead of right, so move up right to correct that. (The first branch always starts downwards so the second branch will always be above it, meaning that we only need to check for a vertical collision.)
> 3 votes

# Answer
# Perl 5, ~~208~~ ~~124~~ ~~122~~ 118 bytes

118 bytes without newlines, indentation and comments. Takes *N* from stdin:

```
@b=1..2;                            #number of branches is 2
for(1..<>){                         #add length <> (the input) to each branch
  ($x,$y)=@$_                       #get where current branch has its tip now
 ,.5>rand?$x++:$y++                 #increase either x or y
 ,$o[$y][$x]++&&redo                #try again if that place is already occupied
 ,$_=[$x,$y]                        #register new tip of current branch
   for@b                            #...and do all that for each branch
}
say map$_||!$i++?'*':$",@$_ for@o;  #output the branches

```

Try it online!
> 3 votes

# Answer
# Python 2, 204 bytes

```
from random import*
N=input()
s=eval(`[[' ']*-~N]*-~N`)
s[0][0]='*'
I=x,y=1,0
J=X,Y=0,1
exec"s[y][x]=s[Y][X]='*';i,j,k,l=choice((J+I,I+I,I+J,J+J)[x-2<X:]);x+=i;y+=j;X+=k;Y+=l;"*N
for i in s:print`i`[2::5]

```

Try it online!
> 2 votes

# Answer
# Perl 5 `-a`, ~~97~~ ~~96~~ ~~93~~ 92 bytes

Has no right, down or off diagonal bias.

```
#!/usr/bin/perl -a
@;=[1];map{$x=$y=0;map++(.5<rand?$x:$y)*$;[$y][$x]++&&redo,1.."@F"}1,2;say+($","*")[@$_]for@

```

Try it online!
> 2 votes

# Answer
# PHP, 118 bytes

```
for($r="*",$w=$argn+2;$argn--;$r[$q+=rand(0,$r[$q+1]<"*")?:$w]=$r)$r[$p+=rand(!$i++,1)?:$w]=$r;echo wordwrap($r,$w-1);

```

requires PHP 5.4 or later for the Elvis operator. Replace `?:` with `?1:` for older PHP.

Run as pipe with `-nR` or try it online.
> 1 votes

# Answer
# Red, 195 190 bytes

```
func[n][g: func[s][i: 0 d: s while[i < n][b/(d): #"*"until[r: 1 if 1 = random 2[r: n + 1]b/(d + r) =#" "]d: d + r
i: i + 1]]b:""loop n[loop n[append b" "]append b"^/"]b/1: #"*"g n + 2 g 2 b]

```

Try it online!

## Readable:

```
f: func[n][
    g: func[s][
        i: 0
        d: s
        while[i < n][
            b/(d): #"*"
            until[
                r: 1 if 1 = random 2[r: n + 1]
                b/(d + r) = #" "
            ]
            d: d + r
            i: i + 1
        ]
    ]
    b: ""
    loop n[loop n[append b " "]append b "^/"]
    b/1: #"*"
    g n + 2
    g 2
    b
]

```
> 0 votes

# Answer
# Jelly, ~~50~~ ~~43~~ 41 bytes

```
2ḶẊ⁸Ð¡+\‘Ṗ
⁸ÇU;Ç¤⁻Q$¿
‘,þ`⁼€þÇS+»þ`Ị$ị⁾*

```

Try it online!

This was a really fun one to write. There could be some much more optimal method. There is probably some golfing to do within this method as well.

Right after I posted this I realized I could use `,þ`` instead of `aþ,""oþ`Ɗ`.
> 0 votes

# Answer
# , ~~148~~ 142 bytes

```
n=scan();`~`=sample;o=r=k=1;l=c(1,n);for(i in 1:n){r=r+l~1;t=l~1;k=k+"if"(k+t-r,t,l[l!=t]);o=c(o,r,k)};write(c(" ","*")[1:n^2%in%o+1],1,n,,"")

```

Try it online!

Additionally, although it won't meet the output spec, you can distinguish the two branches: Try it online!

Explanation:

Starting from index `1`, we randomly select a right or left move for branch `r` by adding `n` or `1`, respectively. Then we select another right or left move for branch `k`, and if it would intersect where `r` is going, we select the other direction. Then we use `r` and `k` as indices into `m`, setting those values as `"*"`. Iterating `n-1` times, we then print the result.
> 0 votes

# Answer
# Jelly, ~~39~~ 38 bytes

```
ḣ2+\€Ẏ
2Rd¤ṗẊÇ⁻Q$$¿Ç0,0ṭ‘Ṭ€×þ/$€Sị⁾* Y

```

Try it online!

Although seemingly unrelated, `d` is useful here to save a byte (over my previous approach).
> 0 votes

# Answer
# Python 2, ~~191~~ ~~187~~ 176 bytes

```
from random import*
n=input()
p,q=c=1,1j;s={p,q,0}
exec'z=choice(c);q,p=p+[z,1+1j-z][p+z in s],q;s|={q};'*2*~-n
R=range(n+1)
for y in R:print''.join(' *'[y+x*1jin s]for x in R)

```

Try it online!

Python has native support for complex numbers of the form `a+bj`; this makes some 2-D problems a bit more tractable...
> 0 votes

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


title: Largest rectangle in 2d array

text:
# Question
Title: Largest rectangle in 2d array
# Input

The board: A 2D container (matrix, list of lists, etc.) of letters like:

```
  ["B", "C", "C", "C", "C", "B", "B", "C", "A", "A"],
  ["B", "A", "C", "B", "B", "A", "B", "B", "A", "A"],
  ["B", "C", "B", "C", "A", "A", "A", "B", "C", "B"],
  ["B", "B", "B", "A", "C", "B", "A", "C", "B", "A"],
  ["A", "A", "A", "C", "A", "C", "C", "B", "A", "C"],
  ["A", "B", "B", "A", "A", "C", "B", "C", "C", "C"],
  ["C", "B", "A", "A", "C", "B", "B", "C", "A", "A"]

```

If you choose a list of lists you may assume that all of the sublists are of the same length.

# Rules

* To make a valid rectangle you need all rectangle corners with the same 'letter'.
* Example, look the *sample board with* **X** bellow. You can see 'X' on (1,0) also on (4,0) also on ( 1,3) and on (4,3) then you have the rectange \[1,0,4,3\] that means from (1,0) to (4,3):

*Sample board with* **X**:

```
  ["B", "X", "C", "C", "X", "B", "B", "C", "A", "A"],
  ["B", "A", "C", "B", "B", "A", "B", "B", "A", "A"],
  ["B", "C", "B", "C", "A", "A", "A", "B", "C", "B"],
  ["B", "X", "B", "A", "X", "B", "A", "C", "B", "A"],
  ["A", "A", "A", "C", "A", "C", "C", "B", "A", "C"],
  ["A", "B", "B", "A", "A", "C", "B", "C", "C", "C"],
  ["C", "B", "A", "A", "C", "B", "B", "C", "A", "A"]

```
* The goal is to find the rectangle or one of the rectangles with the largest area, calculated by (right-left+1)\*(bottom-top+1)
* If there are multiple rectangles with the same maximum area, output any one. Optionally the one with (top coordinate, left coordinate, right coordinate, bottom coordinate) lexicographically smallest.
* Rectangles must have edges parallel to the board's edge.
* Each letter is a printable ASCII char from A to Z (both included).

# Output

The output should be the left-up and right-down positions of the largest area rectangle corners. For the first sample "board" the big square is the yellow one:

And the answer should be:

> \[1, 1, 8, 4\]

### A second example test case

An input of:

```
["C", "D", "D", "D", "A", "A"],
["B", "D", "C", "D", "A", "A"],
["B", "D", "D", "C", "A", "C"],
["B", "D", "B", "C", "A", "C"]

```

Should yield one of these three coordinate lists identifying an area six rectangles:

> \[1, 0, 2, 2\]
> \[1, 0, 3, 1\]
> \[3, 2, 5, 3\]

This question is posted on Stack Overflow with title: How to find the largest rectangle in a 2D array formed by four identical corners? and with this rude JS solution (I can say "rude" because is my code ;) :

Ok, is my first post, be tolerant with me please. I will change all you say to improve the quiz.

# Answer
# Python 2, ~~148~~ 130 bytes

```
lambda x,e=enumerate:min(((a-c)*(d-b),b,a,d,c)for a,y in e(x)for c,k in e(x)for b,g in e(y)for d,h in e(y)if g==h==k[b]==k[d])[1:]

```

Try it online!
> 6 votes

# Answer
# Retina, ~~163~~ 162 bytes

```
Lw$`(?<=(.*\n)*((.)*))(?=(.))((.)*(?<=(.*))\4)((.*\n)*((?>(?<-3>.)*)(?=\4)(?>(?<-6>.)*))\4)?
$.7,$#1,$.2,-$.($5$#9*$5),$.2,$#1,$.7,$.($#1*_$#9*
4{N`
)m`^.*?,

0G`

```

Try it online! Edit: Saved 1 byte because the trailing `)` matching the `$.(` is implicit. Explanation:

```
Lw$`(?<=(.*\n)*((.)*))(?=(.))((.)*(?<=(.*))\4)((.*\n)*((?>(?<-3>.)*)(?=\4)(?>(?<-6>.)*))\4)?

```

This regular expression matches rectangles. The groups are as follows: 1) Top row (as capture count) 2) Left column (as length) 3) Balancing to ensure the left corners align 4) Letter for the corners 5) Width + 1 (as length) 6) Balancing to ensure the right corners align 7) Right column (as length) 8) unused 9) Height (as capture count). The `w` option ensures that all possible widths of rectangles are matched for each given top left corner. The `$` options lists the results using the following substitution pattern.

```
$.7,$#1,$.2,-$.($5$#9*$5),$.2,$#1,$.7,$.($#1*_$#9*

```

The substitutions are as follows: The right column, the top row, the left column, the negation of the area of the rectangle (literally calculated as the length of repeating the width string by one more than height number of times), the left column, the top row, the right column, followed by an expression that evaluates to the bottom row (a capture would have cost 12 bytes plus I've run out of single-digit variables). The first four captures represent the sort order in order of priority. As Retina sorts stably, a multicolumn sort can be established by sorting by each sort column in turn from least to greatest priority. (The area must be sorted in descending order, so a single string sort cannot be used.)

```
4{N`

```

Four numeric sorts are then performed.

```
)m`^.*?,

```

The sort column is then deleted after each sort.

```
0G`

```

The first entry is therefore now the desired result.

Note: The restriction on the choice of rectangle of a given area has since been relaxed and the following ~~144~~ 143-byte version prefers a wider rather than a taller rectangle:

```
Lw$`(?<=(.*\n)*((.)*))(?=(.))((.)*(?<=(.*))\4)((.*\n)*((?>(?<-3>.)*)(?=\4)(?>(?<-6>.)*))\4)?
-$.($5$#9*$5);$.2,$#1,$.7,$.($#1*_$#9*
N`
0G`
.*;

```

Try it online!
> 5 votes

# Answer
# Jelly, (27?)  ~~29~~  28 bytes

<sup>27 if 1-based indexing is allowed - remove trailing </sup>

```
Fṙ1s2;Uœị³EaZI‘P
ZLpLŒċÇÞṪF’

```

A full program.

**Try it online!** (or see the other test case)

### How?

```
Fṙ1s2;Uœị³EaZI‘P - Link 1, areaOrZero: list of pairs [[b,l],[t,r]]
F                - flatten the input                 [b,l,t,r]
 ṙ1              - rotate left one                   [l,t,r,b]
   s2            - split into twos                   [[l,t],[r,b]]
      U          - upend the input                   [[l,b],[r,t]]
     ;           - concatenate                       [[l,t],[r,b],[l,b],[r,t]]
         ³       - program's input
       œị        - multidimensional index into
          E      - all equal?                       X
            Z    - transpose the input              [[b,t],[l,r]]
           a     - logical AND (vectorises)         (if not X we now have [[0,0],[0,0]]
             I   - incremental differences          [t-b,r-l] (or [0,0] if not X)
              ‘  - increment (vectorises)           [t-b+1,r-l+1] (or [1,1] if not X)
               P - product                          area (or 1 if not X)

ZLpLŒċÇÞṪF’ - Main link: list of lists
Z           - transpose the input
 L          - length
   L        - length of the input
  p         - Cartesian product
    Œċ      - pairs with replacement
       Þ    - (stable) sort by:
      Ç     -   last link (1) as a monad
        Ṫ   - tail (note that the rightmost pre-sort represents the bottom-right 1x1
            -       so cannot be superseded by a non-matching rectangle)
         F  - flatten
          ’ - decrement (vectorises) (to get to 0-based indexing)

```
> 4 votes

# Answer
# Perl 6, ~~83~~ 73 bytes

```
{([X] (^$^a[0]X ^$a)xx 2).max:{[eq] $a[.[*;1];.[*;0]]and[*] 1 X-[Z-] $_}}

```

Try it online!

Returns a list of lists `((x0 y0) (x1 y1))`.

### Explanation

```
{
  ([X]                   # Cross product of corner pairs.
    (^$^a[0]             # Range of x coords.
     X                   # Cross product of coords.
     ^$a                 # Range of y coords.
    )xx 2                # Duplicate list.
  ).max:                 # Find maximum of all ((x0 y0) (x1 y1)) lists
  {                      # using the following filter.
    [eq]                 # All letters equal?
      $a[.[*;1];.[*;0]]  # Multidimensional subscript with y and x coord pairs.
    and                  # Stop if false.
    [*]                  # Multiply
      1 X-[Z-] $_        # for each axis 1 - (c0 - c1) == c1 - c0 + 1.
  }
}

```
> 4 votes

# Answer
# JavaScript (ES6), 121 bytes

*-1 byte thanks to @l4m2*
*-1 byte thanks to @tsh*
*+2 bytes to comply with the new rectangle scoring rule*

Takes input as a matrix of strings. Returns 0-indexed coordinates: **\[x0, y0, x1, y1\]**.

```
a=>a.map(b=(r,y)=>r.map((v,x)=>a.map((R,Y)=>R.map((V,X)=>V+R[x]+r[X]!=v+v+v|(A=(x+~X)*(y+~Y))<b||(o=[x,y,X,Y],b=A)))))&&o

```

Try it online!
> 3 votes

# Answer
# Haskell, 144 bytes

```
import Data.Array
o=assocs
f r=snd$maximum[((c-a+1)*(d-b+1),[a,b,c,d])|((a,b),x)<-o r,((c,d),y)<-o r,x==y,r!(a,d)==r!(c,b),x==r!(a,d),a<=c,b<=d]

```

Try it online!
> 3 votes

# Answer
# Jelly, 24 bytes

```
XLṭLp`€p/⁺œị€EɗÐfI‘PɗÞ0Ṫ

```

Try it online!

proves to be useful.

Output format: *\[top,bottom\],\[left,right\]*. 1-indexing.
> 3 votes

# Answer
# APL (Dyalog Classic), 38 bytes

```
a⊃⍨⊃⍒×/1+-/↑2 2∘⍴¨a←⍸≢¨↑∘.(∩¨)⍨∘.∩¨⍨↓⎕

```

Try it online!
> 2 votes

# Answer
# Java 8, ~~208~~ 205 bytes

```
m->{int r=0,R[]={},i=m.length,j,y,z,u,t,T;for(;i-->0;)for(j=m[i].length;j-->0;)for(y=i*j;y-->0;)if((T=m[i][j])==m[u=y/j][z=y%j]&T==m[i][z]&T==m[u][j]&r<(t=(i-u)*(j-z))){r=t;R=new int[]{z,u,j,i};}return R;}

```

Can definitely be golfed.. I now use the most obvious approach of using ~~four~~ three nested for-loops.

-3 bytes thanks to *@ceilingcat* combining the inner loops of rows and columns into a single loop.

**Explanation:**

Try it online.

```
m->{                         // Method with char-matrix parameter and int-array return-type
  int r=0,                   //  Largest area found, starting at 0
      R[]={},                //  Result coordinates, starting empty
      i=m.length,j,          //  x,y indices of the first corner
      y,z,                   //  x,y indices of the second corner
      u,t,T;                 //  Temp integers to reduce bytes
  for(;i-->0;)               //  Loop `i` over the rows
    for(j=m[i].length;j-->0;)//   Inner loop `j` over the columns
      for(y=i*j;y-->0;)      //    Inner loop over the rows and columns
        if((T=m[i][j])==m[u=y/j][z=y%j]
                             //      If the values at coordinates [i,j] and [y,z] are equal
           &T==m[i][z]       //      as well as the values at [i,j] and [i,z]
           &T==m[u][j]       //      as well as the values at [i,j] and [y,j]
           &r<(t=(i-u)*(j-z))){
                             //      And the current area is larger than the largest
          r=t;               //       Set `r` to this new largest area
          R=new int[]{z,u,j,i};}
                             //       And save the coordinates in `R`
  return R;}                 //  Return the largest rectangle coordinates `R`

```
> 1 votes

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


title: Block Rearrangement

text:
# Question
Title: Block Rearrangement
So your task is to take a 3x3 block where `-`'s mean blank spaces, and `*`'s mean filled spaces, for example:

```
-**
-*-
*-*

```

and rearrange the block so that the `*`'s form an X, like this:

```
*-*
-*-
*-*

```

**Input:** 3x3 squares like above, they can be 3 lines, an array, or however you want.

**Output:** The shortest amount of moves to rearrange into an X. Each move is flipping 2 characters that are touching, and are horizontal from each other, vertical from each other, or diagonal from each other. If it's not possible, return any impossible output, for example `999` or `-4242`. `5` is the smallest such number.

**Test Cases:**

1) Output: 1

```
-**
-*-
*-*

```

2) Output: -1

```
-*-
-*-
*-*

```

3) Output: 3

```
---
-**
***

```

4) Output: 0

```
*-*
-*-
*-*

```

**You can substitute the blank and non blank characters but be sure to include which is which in your post**

**Code Golf**

Remember this is code golf the shortest code wins!

# Answer
> 4 votes
# Jelly, 26 bytes

```
5ḶḤd3ạŒ!Ṁ€€ḅ1Ṃ
T’d3Ç-L=5Ɗ?

```

Try it online!

---

Take a flat list as input.

Too bad that Jelly doesn't have "multidimensional truthy indices"... `T€ṭ€"JẎ` also works but takes 1 more byte.

---

Algorithm: There are 5 current block positions and 5 targets (destinations), the algorithm tries each of the 5! matching, and output the minimum sum of \[source, destination\] Chebyshev distance.

# Answer
> 4 votes
## Haskell, 176 132 126 104 bytes

```
w=0:1:w
m a|sum a/=5=5|1>0=sum$[a!!4|3<-sum.map(a!!)<$>[[0,1,2],[0,3,6],[2,5,8],[6,7,8]]]++zipWith(*)a w

```

Try it online!

---

Takes a list of integers with 1 as the non-blank character. Sums the number of non-zero even-indexed squares, then adds 1 if any of the double move patterns are found (center square and edge column/row completely filled). The last part's a bit wasteful I think, probably could be much improved over this brute-force method. Returns 5 (an impossible output) on an impossible input.

# Answer
> 3 votes
# Python 2, ~~194~~ 192 bytes

```
from itertools import*
f=lambda l,k=0:-(sum(l)!=5)or[1,0]*4!=l[:-1]and k<4and-~min(f(l[:a]+[l[b]]+l[a+1:b]+[l[a]]+l[b+1:],k+1)for a,b in combinations(range(9),2)if max(b/3-a/3,abs(a%3-b%3))<2)

```

Try it online!

# Answer
> 3 votes
# JavaScript (ES6), 123 bytes

Takes input as a 9-bit integer. Solves the puzzle by naively applying the rules, which has been proven not to be the shortest approach.

```
f=(n,k=b=-1)=>n^341?k>2?b:[3,6,9,10,17,18,20,34,36].map(m=>[1,8,8].map(M=>(x=n&(m*=M))&-x^x||f(n^m,k+1)))|b:!~b|k<b?b=k+1:b

```

Try it online!

### Commented

```
f = (                           // f = recursive function taking:
  n,                            //   n = input
  k =                           //   k = number of moves, initialized to -1
  b = -1                        //   b = best result so far, initialized to -1
) =>                            //
  n ^ 341 ?                     // if n does not match the target pattern:
    k > 2 ?                     //   if we've already done more than 3 moves:
      b                         //     we're not going to find a solution -> abort
    :                           //   else:
      [3,6,9,10,17,18,20,34,36] //     for each swap bitmask m
      .map(m =>                 //     and
      [1,8,8]                   //     for each multiplier M:
      .map(M =>                 //       apply the multiplier to m and
        (x = n & (m *= M))      //       apply the final bitmask to n -> this gives x
        & -x                    //       isolate the least significant bit of x
        ^ x ||                  //       if it's the only bit set,
        f(n ^ m, k + 1)         //       then swap the bits and make a recursive call
      )) | b                    //     end of both map() loops; return b
  :                             // else:
    !~b | k < b ? b = k + 1 : b //   this is a solution in k+1 moves: update b

```

**NB**: This codes performs some illegal moves beyond the top of the board when **m** is multiplied by 64. But they are simply ignored, as they can't possibly lead to a shorter solution than the best legal solution.

Below are the 9 base swap bitmasks and the target pattern. The top left corner is the most significant bit.

```
000  000  001  001  010  010  010  100  100     101
011  110  001  010  001  010  100  010  100     010 (341)
(3)  (6)  (9)  (10) (17) (18) (20) (34) (36)    101

```

# Answer
> 2 votes
# Jelly, 26 bytes

```
“ċȤ‘ḤB;U$=a¥;Ḋm2ƊẠ€SɓSn5Nȯ

```

**Try it online!**

A monadic link.

### How?

Inspired by Bubbler's Python answer; golfed to suit Jelly...

```
“ċȤ‘ḤB;U$=a¥;Ḋm2ƊẠ€SɓSn5Nȯ - Link: length 9 list of ones & zeros, X
“ċȤ‘                       - list of code-page indices     = [232,154]
    Ḥ                      - double                        = [464,308]
     B                     - to binary     = [[1,1,1,0,1,0,0,0,0],[1,0,0,1,1,0,1,0,0]]
        $                  - last two links as a monad:
       U                   -   upend       = [[0,0,0,0,1,0,1,1,1],[0,0,1,0,1,1,0,0,1]]
      ;                    -   concatenate = [[1,1,1,0,1,0,0,0,0],[1,0,0,1,1,0,1,0,0],[0,0,0,0,1,0,1,1,1],[0,0,1,0,1,1,0,0,1]]
           ¥               - last two links as a dyad:
          a                -   logical AND (vectorises)
         =                 -   equal? (vectorises)
                Ɗ          - last three links as a monad:
             Ḋ             -   dequeue X (remove leftmost element)
               2           -   literal two
              m            -   modulo slice (keeps the "edge-elements")
            ;              - concatenate
                 Ạ€        - all? for €ach (edge-elements: no-op
                           -                else: 1 for any cost-2 element 0 otherwise)
                   S       - sum
                    ɓ      - new dyadic chain ^that on the right; X on the left
                     S     - sum X
                       5   - literal five
                      n    - not equal?
                        N  - negate (-1 if not exactly 5 1s, 0 otherwise)
                         ȯ - logical OR with right

```

# Answer
> 2 votes
# JavaScript, 85 bytes

```
s=>/^0*(10*){5}$/.test(s)*s.match(/(?=1.(..)*$|^1(..)?11.1|1.11(..)?1$)|$/g).length-1

```

This is a regex port of Bubbler's answer.

Input as a string of 0 / 1.

```
f=
s=>/^0*(10*){5}$/.test(s)*s.match(/(?=1.(..)*$|^1(..)?11.1|1.11(..)?1$)|$/g).length-1

document.write('<table>'+('<tr>'+'<td><label><input type=checkbox><span></span></label>'.repeat(3)).repeat(3)+'</table>');
document.write('Answer: <output id=o></output>');
U=()=>o.value=f(ii.map(i=>i.checked?1:0).join``);
ii=[...document.querySelectorAll('input')];
ii.forEach((i,p)=>{
i.checked=!(p%2);
i.oninput=U;
});
U()
```

```
label{display:block;position:relative;overflow:hidden;width:20px;height:20px;}
input{position:absolute;top:-200%;}
input~span{width:100%;height:100%;display:block;border:1px solid black;box-sizing:border-box;}
input:focus~span{border-color:red;}
input:checked~span{background:#ace;}
```

# Answer
> 2 votes
# Stax, ~~23~~ 22 bytes

```
Ç╙╤Ü┤└åVτ┐├Y-²▼░█∩¡3ëâ

```

Run and debug it

This program takes an array of `[0, 1]` as input, and returns an integer number of moves, or an empty string if no solution is possible.

Consider this indices for the grid

```
0 1 2
3 4 5
6 7 8

```
* If there are not exactly 5 `1`s in the input, then there is no solution, so we produce no output.
* The centers of each side are the incorrect positions. These are indices 1, 3, 5, and 7. Summing the distance for each `1` in these positions will produce the final result.
* For each `1` in an incorrect position its distance is either 1 or 2. It will be 2 iff it's surrounded by other `1`s. For example, if there are `1`s at indices \[0, 1, 2, 4\], then the distance for the incorrect `1` is 2.
* With this in mind, consider this pseudo-code for getting the distance contributed to the result by index 1.

1. Read 4 bits from indices \[1, 0, 2, 4\]. This puts the incorrect position in the most significant position.
    2. Convert these bits to a number `b` from 0 to 15.
    3. When `0 <= b <= 7` the distance is 0. When `8 <= b <= 14` the distance is 1. When `b == 15` the distance is 2. This can be calculated using integer division by `b * 2 / 15`.

So the total distance can be calculated by repeating this process 4 times and rotating the grid in between.

```
1#5=4*  if the number of 1s is 5, then 4, else 0
D       repeat the rest of the program that many times
  x     push the value in the x register, which is initially the input
  3/    split into 3 rows
  rM    rotate 90 degrees
  $X    flatten back into single array, and save the "rotated" array in the X register
  A|2E  get the digits of 2^10 i.e. [1,0,2,4]
  @     read the bits from the current rotation at indices [1,0,2,4]
  :b    convert bits to integer
  H15/  double, then divide by 2
  +     add to running total

```

Run this one

# Answer
> 1 votes
# Excel, ~~86~~ 81 Bytes

```
=SUM(B1,A2,B3,C2)+B2*(AND(A1:A3)+AND(A1:C1)+AND(C1:C3)+AND(A3:C3))/(SUM(A1:C3)=5)

```

**Old:** *When the 'impossible' output was `-1`*

```
=IF(SUM(A1:C3)=5,SUM(B1,A2,B3,C2)+B2*(AND(A1:A3)+AND(A1:C1)+AND(C1:C3)+AND(A3:C3)),-1)

```

Uses `1` for filled and `0` for empty, input in range `A1:C3`. ~~Possible to golf further if we can return values other than `-1` for "impossible".~~ Returns a `#DIV/0!` error on impossible grids

Operates on the same logic as Bubbler's Python answer.

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


title: Facey McFaceface

text:
# Question
Title: Facey McFaceface
Anyone remember Boaty?

You could totally make any old word, right?

* Write a function to turn a string into Somethingy McSomethingface.
* It should accept one string as input. Ignore the case of the input.
* If the word ends in 'y', your function should not add an additional 'y' to the first instance, but should remove it in the second instance.
* If the word ends in 'ey', it should not have an additional 'y' added in the first instance, but should remove both in the second instance.
* The output should only have upper case letters in the first character, the 'M' of 'Mc' and the first character after 'Mc'.
* it only needs to work with strings of 3 or more characters.

Examples:

```
boat                  =>  Boaty McBoatface
Face                  =>  Facey McFaceface
DOG                   =>  Dogy McDogface
Family                =>  Family McFamilface
Lady                  =>  Lady McLadface
Donkey                =>  Donkey McDonkface
Player                =>  Playery McPlayerface
yyy                   =>  Yyy McYyface
DJ Grand Master Flash =>  Dj grand master flashy McDj grand master flashface

```

# Answer
# Stax, 26 bytes

```
ëO╛εh╕⌠î&!}∞┌C^U╟«äδ◙Bg⌠└¿

```

Run and debug it

```
^           convert input to upper case                     "FACE"
B~          chop first character and push it back to input  70 "ACE"
v+          lowercase and concatenate                       "Face"
c'yb        copy, push "y", then copy both                  "Face" "Face" "y" "Face" "y"
:]          string ends with?                               "Face" "Face" "y" 0
T           trim this many character                        "Face" "Face" "y"
+           concatenate                                     "Face" "Facey"
p           output with no newline                          "Face"
"e?y$"z     push some strings                               "Face" "e?y$" ""
" Mc`Rface  execute string template; `R means regex replace " Mc Faceface"
            result is printed because string is unterminated

```

Run this one
> 7 votes

# Answer
# , 27 ~~28~~ ~~30~~ bytes

```
Vu~Ùóe¿y$
Hóy$
ÁyJaMc<Esc>Aface

```

Try it online!

`<Esc>` represents `0x1b`

* Golfed two bytes after learning that we did not need to support inputs with less than 3 characters.
* 1 byte saved thanks to @DJMcMayhem by working on the second line before the first one, thus removing the `G`

The input is in the buffer. The program begins by converting everything to lowercase

`V` selects the line and `u` lowercases it

`~` toggles the case of the first character (converting it to uppercase)

and `Ù` duplicates this line above, leaving the cursor at the bottom line

`ó` and replaces `e¿y$`, compressed form of `e\?y$` (optional `e` and a `y` at the end of the line), with nothing (happens on the second line)

`H` goes to the first line

`ó` replaces `y$` (`y` at the end of the line) with nothing on the first line

`Á` appends a `y` to the end of the first line

`J` and joins the last line with the first with a space in the middle, and the cursor is moved to this space

`a` appends `Mc` (`<Esc>` returns to normal mode)

`A` finally, appends `face` at the end of the line
> 15 votes

# Answer
# Python, 144 bytes

```
def f(s):
 s=s[0].upper()+s[1:].lower()
 y=lambda s:s[:-1]if s[-1]=='y'else s
 t=y(s)
 u=s[:-2]if s[-2:]=='ey'else y(s)
 return t+'y Mc%sface'%u

```

Try it online here
> 13 votes

# Answer
# Excel, ~~204~~ ~~144~~ ~~137~~ 165 bytes

```
=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(REPT(REPLACE(LOWER(A1),1,1,UPPER(LEFT(A1)))&"~",2),"~","y Mc",1),"yy ","y "),"ey~","~"),"y~","~"),"~","face")

```

From the inside outwards:

```
REPLACE(LOWER(A1),1,1,UPPER(LEFT(A1)))      Replaces PROPER to handle space-delimited cases
REPT(%&"~",2)                   Duplicate.                    Donkey~Donkey~
SUBSTITUTE(%,"~","y Mc",1)      Replace first ~.              Donkeyy McDonkey~
SUBSTITUTE(%,"yy ","y ")        Handle words ending in 'y'.   Donkey McDonkey~
SUBSTITUTE(%,"ey~","~")         Handle words ending in 'ey'   Donkey McDonk~
SUBSTITUTE(%,"y~","~")          Handle words ending in 'y'    Donkey McDonk~
SUBSTITUTE(%,"~","face")        Adding face.                  Donkey McDonkface

```

---

Old answer, creating all bits separately, and then concatenating (176 bytes). Does not handle space-delimited cases correctly.

```
=PROPER(A1)&IF(LOWER(RIGHT(A1,1))="y",,"y")&" Mc"&IF(LOWER(RIGHT(A1,2))="ey",LEFT(PROPER(A1),LEN(A1)-2),IF(LOWER(RIGHT(A1,1))="y",LEFT(PROPER(A1),LEN(A1)-1),PROPER(A1)))&"face"

```
> 12 votes

# Answer
# Perl 6, ~~42~~ ~~37~~ 35 bytes

```
{S/y$//~"y Mc{S/e?y$//}face"}o&tclc

```

Try it online!
> 11 votes

# Answer
# C# (.NET Core), ~~122~~ ~~108~~ ~~139~~ ~~175~~ ~~180~~ ~~179~~ 154 bytes

Thanks a lot, lee!

```
s=>((s.EndsWith("y")?s:s+"y")+" Mc"+(s+"$").Replace("ey$","")+"face").Replace(s,s.ToUpper()[0]+s.Substring(1).ToLower()).Replace("y$","").Replace("$","");

```

Try it online!

# C# (.NET Core, with LINQ), 152 bytes

```
s=>((s.Last()=='y'?s:s+"y")+" Mc"+(s+"$").Replace("ey$","")+"face").Replace(s,s.ToUpper()[0]+s.Substring(1).ToLower()).Replace("y$","").Replace("$","");

```

Try it online!
> 9 votes

# Answer
# Ruby, ~~61~~ 49 bytes

```
->s{s.capitalize=~/(e)?y$|$/;"#$`#$1y Mc#$`face"}

```

Try it online!

Saved 12 sweet bytes thanks to @MartinEnder:
> 8 votes

# Answer
# SOGL V0.12, 38 bytes

```
lW y≠F
u⁽³:F y*+pF‽j:lW e=⌡j}"‰θ`√►׀‘p

```

Try it Here!
> 7 votes

# Answer
# Python 3, 80 bytes

Long time avid reader, my first submission at last !

```
lambda y:re.sub("([\w ]+?)((e)?y)?$",r"\1\3y Mc\1face",y.capitalize())
import re

```

Try it online
> 7 votes

# Answer
## Retina, 29 bytes

```
.+
$T
0`(e)?y$|$
$1y Mc$`face

```

Try it online!
> 6 votes

# Answer
# Python 2, ~~88~~ 92 bytes

```
lambda s:(s+'y'*-~-(s[-1]in'yY')).title()+' Mc'+re.sub('e?y$','',s.title())+'face'
import re

```

Try it online!
> 5 votes

# Answer
# Java 8, ~~121~~ ~~112~~ ~~107~~ 106 bytes

```
s->(s=(char)(s.charAt(0)&95)+s.toLowerCase().substring(1)).split("y$")[0]+"y Mc"+s.split("e?y$")[0]+"face"

```

-1 byte thanks to *@OliverGrégoire*.

**Explanation:**

Try it online.

```
s->                         // Method with String as both parameter and return-type
  (s=                       //  Replace and return the input with:
     (char)(s.charAt(0)&95) //   The first character of the input as Uppercase
     +s.toLowerCase().substring(1))
                            //   + the rest as lowercase
  .split("y$")[0]           //  Remove single trailing "y" (if present)
  +"y Mc"                   //  Appended with "y Mc"
  +s.split("e?y$")[0]       //  Appended with the modified input, with "y" or "ey" removed
  +"face"                   //  Appended with "face"

```
> 5 votes

# Answer
# JavaScript, ~~103~~ ~~96~~ 94 bytes

Pretty naïve first pass at this.

```
s=>(g=r=>s[0].toUpperCase()+s.slice(1).toLowerCase().split(r)[0])(/y$/)+`y Mc${g(/e?y$/)}face`

```

Try it online
> 4 votes

# Answer
# Perl 5 `-p`, ~~47~~ 39 bytes

*Saved 6 bytes with @OlegV.Volkov's suggestions, 1 with @mwellnhof's, and 1 on my own*

```
$_=lc^$";$_=s/y?$/y Mc/r.s/e?y$//r.face

```

Try it online!
> 3 votes

# Answer
# vim, 35 34 bytes

```
Vu~Yp:s/ey$
:%s/y$
kgJiy Mc<ESC>Aface<ESC>

```

`<ESC>` is `0x1b`

### Ungolfed

```
Vu~                      # Caseify McCaseface
Yp                       # dup line
:s/ey$
:%s/y$                   # Get the suffixes right
kgJiy Mc<ESC>Aface<ESC>  # Join lines and add the extra chars

```

Try it online!

Saved 1 byte thanks to DJMcMayhem
> 3 votes

# Answer
# C++ 14 (g++), ~~181~~ ~~171~~ ~~148~~ ~~147~~ 134 bytes

```
[](auto s){s[0]&=95;int i=1,b;for(;s[i];)s[i++]|=32;b=s[--i]-'y';return s+(b?"y":"")+" Mc"+(b?s:s.substr(0,s[i-1]-'e'?i:i-1))+"face";}

```

Note that clang will not compile this.

Credit goes to Kevin Cruijssen and Olivier Grégoire for the `&95` trick.

Thanks to Chris for golfing 11 bytes.

Try it online here.

Ungolfed version:

```
[] (auto s) { // lambda taking an std::string as argument and returning an std::string
    s[0] &= 95; // convert the first character to upper case
    int i = 1, // for iterating over the string
    b; // we'll need this later
    for(; s[i] ;) // iterate over the rest of the string
        s[i++] |= 32; // converting it to lower case
    // i is now s.length()
    b = s[--i] - 'y'; // whether the last character is not a 'y'
    // i is now s.length()-1
    return s + (b ? "y" : "") // append 'y' if not already present
    + " Mc"
    + (b ? s : s.substr(0, s[i-1] - 'e' ? i : i-1)) // remove one, two, or zero chars from the end depending on b and whether the second to last character is 'e'
    + "face";
}

```
> 3 votes

# Answer
# Elixir, ~~112~~ ~~110~~ ~~107~~ 106 bytes

*now as short as java*

```
fn x->x=String.capitalize x;"#{x<>if x=~~r/y$/,do: "",else: "y"} Mc#{String.replace x,~r/e?y$/,""}face"end

```

Try it online!

Explanation:

```
x=String.capitalize x

```

Gets `x` with the first character in uppercase and all others lowercase.

```
#{ code }

```

Evaluate the code and insert it into the string.

```
#{x<>if x=~ ~r/y$/, do: "", else: "y"}

```

Concatenates **x** with `y` if it does not end with `y` (ie it does not match the regex `y$`).

```
#{String.replace x, ~r/e?y$/, "")}

```

Removes trailing `ey` and trailing `y`.
> 2 votes

# Answer
# , ~~38~~ ~~36~~ 32 bytes

-5 byte thanks to @Cows quack

```
Vu~hy$ó[^y]$/&y
A Mc<esc>póe¿y$
Aface

```

`<esc>` is a literal escape character and `[^` is encoded as `\x84`

Try it online!
> 2 votes

# Answer
# Ruby, 69 bytes

```
->s{"#{(s.capitalize!||s)[-1]==?y?s:s+?y} Mc#{s.gsub /e?y$/,""}face"}

```

Explanation:

```
->s{                                                                } # lambda
    "#{                                 } Mc#{                }face" # string interpolation
       (s.capitalize!||s) # returns string capitalized or nil, in that case just use the original string
                         [-1]==?y # if the last character == character literal for y
                                 ?s:s+?y # then s, else s + "y"
                                              s.gsub /e?y$/,"" # global substitute
                                                               # remove "ey" from end

```

Try it online!
> 2 votes

# Answer
# Python 3, ~~117~~ 114 bytes

*-3 bytes thanks to Dead Possum*

```
def f(s):s=s.title();return s+'y'*(s[-1]!='y')+' Mc'+([s,s[:-1],0,s[:-2]][(s[-1]=='y')+((s[-2:]=='ey')*2)])+'face'

```

Try it online!
> 2 votes

# Answer
# K4, ~~74~~ ~~69~~ 68 bytes

**Solution:**

```
{$[r;x;x,"y"]," Mc",_[r:0&1-2/:"ye"=2#|x;x:@[_x;0;.q.upper]],"face"}

```

**Examples:**

```
q)k)f:{$[r;x;x,"y"]," Mc",_[r:0&1-2/:"ye"=2#|x;x:@[_x;0;.q.upper]],"face"}
q)f each ("boat";"Face";"DOG";"Family";"Lady";"Donkey";"Player")
"Boaty McBoatface"
"Facey McFaceface"
"Dogy McDogface"
"Family McFamilface"
"Lady McLadface"
"Donkey McDonkface"
"Playery McPlayerface"

```

**Explanation:**

Figure out if the last characters are equal to `"ey"`, convert result to base-2 so we can ignore words that end `"e?"`. Index into a list of numbers of characters to trim.

Managed to shave 5 bytes off my code to determine whether the last two chars at `"ey"` but struggling to better it...

```
{$[r;x;x,"y"]," Mc",_[r:0&1-2/:"ye"=2#|x;x:@[_x;0;.q.upper]],"face"} / the solution
{                                                                  } / lambda function
                                                            ,"face"  / join with "face"
                    _[                  ;                  ]         / cut function
                                           @[_x; ;        ]          / apply (@) to lowercased input
                                                0                    / at index 0
                                                  .q.upper           / uppercase function
                                         x:                          / save back into x
                                      |x                             / reverse x
                                    2#                               / take first two chars of x
                               "ye"=                                 / equal to "ye"?
                             2/:                                     / convert to base 2
                           1-                                        / subtract from 1
                         0&                                          / and with 0 (take min)
                       r:                                            / save as r
             ," Mc",                                                 / join with " Mc"
 $[r;x;x,"y"]                                                        / join with x (add "y" if required)

```

**Bonus:**

**67 byte** port in K (oK):

```
{$[r;x;x,"y"]," Mc",((r:0&1-2/"ye"=2#|x)_x:@[_x;0;`c$-32+]),"face"}

```

Try it online!
> 2 votes

# Answer
# Red, 143 142 bytes

```
func[s][s: lowercase s s/1: uppercase s/1
w: copy s if"y"<> last s[append w"y"]rejoin[w" Mc"parse s[collect keep to[opt["y"|"ey"]end]]"face"]]

```

Try it online!

Ungolfed:

```
f: func[s][
   s: lowercase s                      ; make the entire string lowercase
   s/1: uppercase s/1                  ; raise only its first symbol to uppercase
   w: copy s                           ; save a copy of it to w
   if "y" <> last s[append w "y"]     ; append 'y' to w if it doesn't have one at its end
   rejoin[w                            ; assemble the result by joining:
          " Mc"
          ; keep the string until "y", "ey" or its end
          parse s[collect keep to [opt ["y" | "ey"] end]]
          "face"
    ]
]

```
> 2 votes

# Answer
# 05AB1E, 30 bytes

```
™D'y©Ü®«s¤®Qi¨¤'eQi¨]’McÿŠÑ’ðý

```

Try it online! or as a Test suite
> 2 votes

# Answer
# JavaScript (Node.js), 87 bytes

* thanks to @Shaggy for 5 reducing 5 bytes

```
s=>(g=r=>Buffer(s.replace(r,"")).map((x,i)=>i?x|32:x&~32))(/y$/)+`y Mc${g(/e?y$/)}face`

```

Try it online!
> 2 votes

# Answer
# Jstx, 27 bytes

```
h</►yT↓►y/◙♂ Mc♀/◄eyg►yg/íå

```

Explanation

```
      # Command line args are automatically loaded onto the stack
h     # Title case the top of the stack
<     # Duplicate the top value on the stack twice
/     # Print the top value on the stack
►y    # Load 'y' onto the stack
T     # Returns true if the 2nd element on the stack ends with the top
↓     # Execute block if the top of the stack is false
  ►y  # Load 'y' onto the stack
  /   # Print the top value on the stack
◙     # End the conditional block
♂ Mc♀ # Load ' Mc' onto the stack
/     # Print the top value on the stack
◄ey   # Load 'ey' onto the stack
g     # Delete the top of the stack from the end of the 2nd element on the stack if it exists
►y    # Load 'y' onto the stack
g     # Delete the top of the stack from the end of the 2nd element on the stack if it exists
/     # Print the top of the stack
íå    # Load 'face' onto the stack
      # Print with newline is implied as the program exits

```

Try it online!
> 2 votes

# Answer
# PHP: 132

```
<?php function f($s){$s=ucfirst(strtolower($s));return $s.(substr($s,-1)=='y'?'':'y').' Mc'.preg_replace('/(ey|y)$/','',$s).'face';}

```

## Explanation:

```
<?php

function f($s)
{
    // Take the string, make it all lowercase, then make the first character uppercase
    $s = ucfirst(strtolower($s));

    // Return the string, followed by a 'y' if not already at the end, then ' Mc'
    // and the string again (this time, removing 'y' or 'ey' at the end), then
    // finally tacking on 'face'.
    return $s
        . (substr($s, -1) == 'y' ? '' : 'y')
        . ' Mc'
        . preg_replace('/(ey|y)$/', '', $s)
        . 'face';
}

```
> 2 votes

# Answer
# Pyth, ~~36~~ 34 bytes

```
++Jrz4*\yqJK:J"e?y$"k+" Mc"+K"face

```

Try it online!

Explanation:

```
++Jrz4*\yqJK:J"(e)?y$"k+" Mc"+K"face

  Jrz4                                  Set J to the titlecase of z (input)
           K:J"e?y$"k                   Set K to (replace all matches of the regex e?y$ in J with k (empty string))
         qJ                             Compare if equal to J
      *\y                               Multiply by "y" (if True, aka if no matches, this gives "y", else it gives "")
 +                                      Concatenate (with J)
                             +K"face    Concatenate K with "face"
                       +" Mc"           Concatenate " Mc" with that
+                                       Concatenate

```
> 2 votes

# Answer
# Jelly, ~~77~~ ~~75~~ ~~74~~ 73 bytes

```
2ḶNṫ@€⁼"“y“ey”S
ØA;"ØaF
¢y⁸µ¢Uyµ1¦
Çṫ0n”yẋ@”y;@Ç;“ Mc”
⁸JU>ÑTị3Ŀ;@Ç;“face

```

Try it online!

Any golfing suggestions are welcome (and wanted)!
> 2 votes

# Answer
# Python, ~~105~~ 104

```
import re;r=re.sub;c=str.capitalize;f=lambda s:r('([^e^y])$','\\1y',c(s))+' Mc'+r('ey$','',c(s))+'face'

```

thx @Berry M. from noticing my dyslexia
> 1 votes

# Answer
## Pyth, ~~60~~ 59 bytesSBCS

```
K"ey"Jrz4Iq>2JK=<2J=kK.?=k\yIqeJk=<1J))%." s÷   WZÞàQ"[JkJ

```

Test suite

They don't display here, but three bytes, `\x9c`, `\x82`, and `\x8c` are in the packed string between `s` and `÷`. Rest assured, the link includes them.

Python 3 translation:
```
K="ey"
J=input().capitalize()
if J[-2:]==K:
    J=J[:-2]
    k=K
else:
    k="y"
    if J[-1]==k:
        J=J[:-1]
print("{}{} Mc{}face".format(J,k,J))

```
> 1 votes

# Answer
# APL (Dyalog Classic), ~~95~~ ~~90~~ ~~88~~ ~~87~~ ~~86~~ ~~85~~ ~~84~~ ~~82~~ ~~80~~ ~~78~~ ~~77~~ 73 bytes

```
{'face',⍨(' Mc',S↓⍨-+/∧/¨Y'ey'=¨↑∘S¨-⍳2),⍨S,(Y≠⊃⌽S←⍵(819⌶¨)⍨1=⍳⍴⍵)/Y←'y'}

```

Try it online!

This could be golfed down some more, and any suggestions are welcome!
> 1 votes

# Answer
# PHP, 45  ~~46~~ bytes

```
<?=($s=ucfirst(fgets(STDIN)))."y Mc{$s}face";

```

Try it online!
> 1 votes

# Answer
# Clojure: ~~161~~ 155

```
(use '[clojure.string :as s])
(defn f[t](s/join[(s/capitalize(cond(=(last t)\y)t :else(s/join[t "y"])))" Mc"(s/capitalize(s/replace t #"e*y$" ""))"face"]))

```

Ungolfed:

```
(defn facegen [s0]
  (let [ s1 (clojure.string/capitalize (cond
                                         (= (last s0) \y)  s0
                                         :else             (clojure.string/join [s0 "y"])))
         s2 (clojure.string/capitalize (clojure.string/replace s0 #"e*y$" ""))]
    (clojure.string/join [s1 " Mc" s2 "face"])))

```

Try it online!
> 1 votes

# Answer
# APL (Dyalog Classic), 62 bytes

```
{'face',⍨(' Mc','e?y$'⎕r''⊢S),⍨S,(Y≠⊃⌽S←⍵(819⌶¨)⍨1=⍳⍴⍵)/Y←'y'}

```

Try it online!

Thanks to @ngn for this solution!
> 1 votes

# Answer
**Unix** (**79 bytes**)

Using Standard input :

```
 rev|sed -r 's/(.*)(.)$/\L\1\U\2/;s/^(ye?)?(.*)$/ecaF\2cM y\1\2/;s/ yy/ y/'|rev

```

test :

```
echo -e "Lady\nFace\nDonkey\nyyy"|rev|sed -r 's/(.*)(.)$/\L\1\U\2/;s/^(ye?)?(.*)$/ecaF\2cM y\1\2/;s/ yy/ y/'|rev
Lady McLadFace
Facey McFaceFace
Donkey McDonkFace
Yyy McYyFace

```

or ( by Function) :

```
F(){ echo $1|rev|sed -r 's/(.*)(.)$/\L\1\U\2/;s/^(ye?)?(.*)$/ecaF\2cM y\1\2/;s/ yy/ y/'|rev;}

```

test :

```
 F donkey
 Donkey McDonkFace

```
> 1 votes

# Answer
# PowerShell Core, 98 bytes

```
(("y$","e?(?=y)y$"|%{$o.ToUpper()[0]+$o.ToLower().Substring(1)-replace $_,""})-join "y Mc")+"face"

```

Try it online!

Many thanks to @Anderson Pimentel for inspiring a solution using regex replacements!
> 1 votes

# Answer
# Excel VBA, 134 bytes

An anonymous VBE Immediate Window Function that takes input from range \[A1\] and outputs to the Immediate Window.

```
b=[Left(Upper(A1))]+Mid([Lower(A1)],2):l=len(b):y=[Right(A1)="y"]:?b;IIf(y,"","y")" Mc"IIf(y,Left(b,l-1+(InStrRev(b,"e")=l-1)),b)"face

```
> 1 votes

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


title: Get the number of images on a webpage

text:
# Question
Title: Get the number of images on a webpage
Recreational languages win at code golf too much. This challenge is simple, when using higher level functions.

**The task is as follows:**

**Given any valid url, which is guaranteed to result in a valid HTML document** *(for example https://en.wikipedia.org/wiki/Ruby\_on\_Rails, which has 9 images)***, count the number of images displayed from the resultant webpage.**

Only images visible in the HTML code are counted, marked by the HTML `<img>` tag.

Websites that can continually load images (Google Images) are not valid tests.

# Answer
> 2 votes
# JavaScript, 61 bytes

As per this consensus, the code needs to run under the same domain as the page being requested, to avoid CORS issues. Returns a Promise conatining the count.

```
u=>fetch(u).then(r=>r.text()).then(t=>t.split`<img`.length-1)

```

Thanks to tsh for pointing out some code I forgot to update before posting, saving 3 bytes.

---

## Try it

```
(f=
u=>fetch(`https://crossorigin.me/`+u).then(r=>r.text()).then(t=>t.split`<img`.length-1)
)(i.value=`https://codegolf.stackexchange.com/questions/161669/`).then(x=>o.innerText=x);b.addEventListener(`click`,_=>f(i.value).then(x=>o.innerText=x),0)
```

```
<input id=i><button id=b>Count</button><pre id=o></pre>
```

# Answer
> 2 votes
# CJam, 10 bytes

```
lg"<img"e=

```

Does not work online.

Description:

```
l          # read line
 g         # open url and get html
  "<img"   # this string
        e= # count arg2 in arg1

```

# Answer
> 2 votes
# Python 3 \+ Selenium \+ Firefox, 124 bytes

```
from selenium.webdriver import*
d=Firefox()
d.get(input())
c=len(d.find_elements_by_xpath('//img'))
d.quit()
print(c)

```

Notice that `https://en.wikipedia.org/wiki/Ruby_on_Rails` report 8 instead of 9. This is due to one of the `<img>` tag is contained by `<noscript>`, which is regarded as comment by a browser who enabled script.

~~Changing `webdriver.Firefox` to `webdriver.Ie` may save 5 bytes... But I just dislike IE.~~

**How to run:**

* First install Python 3, and Firefox
* install Selenium by `pip install selenium`
* Download gecko driver and put it to your path
* Run this script
* A Firefox will be started, ignore it and input the url to stdin
* The result will be shown on stdout

# Answer
> 1 votes
# Python 2 + BeautifulSoup, 103 bytes

```
import bs4 as B
import urllib as U
print len(B.BeautifulSoup(U.urlopen(input()).read()).findAll('img'))

```

Can't do a TIO as `BeautifulSoup` is not available there. This reports 9 for `https://en.wikipedia.org/wiki/Ruby_on_Rails`.

**Note:** A warning is displayed before the number as a parser is not specified and `lxml`is taken as the default. Adding the `lxml` parser explicitly suppresses the warning but costs another 7 bytes.

```
import bs4 as B
import urllib as U
print len(B.BeautifulSoup(U.urlopen(input()).read(),'lxml').findAll('img'))

```

# Answer
> -1 votes
# Bash, grep, and wc, ~~45~~ 28 bytes

```
curl $1|grep -o "<img"|wc -l

```

*-17 bytes thanks to tsh*

Explanation:

```
curl $1                      # download html from first parametre
       |grep -o "<img"       # find all <img strings
                      |wc -l # count lines

```

---
Tags: code-golf, parsing, internet
---