title: Generate the Chess Numbers™

text:
# Question
Title: Generate the Chess Numbers™
I was browsing Stack Overflow when I saw this post in Puzzling in the hot network questions and decided to make a challenge out of it (all credit goes to the creator of the challenge).

## Overview

A Chess Number is a number that, when converted to base 18, results in a valid chess coordinate pair, where the first character is a-h and the second character is 1-8 (inclusive). Your job is to generate the full list of them, ordered. Output may be an array/list, printed individually, as a matrix/grid, or in a string. **The numbers must be in decimal, not base 18.**

## Examples

Here is a Python program to generate the full list:

```
def baseN(num, b, numerals = "0123456789abcdefghijklmnopqrstuvwxyz"):
    return ((num == 0) and numerals[0]) or (baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b])

for i in range(0, 10000):
    s = baseN(i, 18)
    if len(s) == 2 and s[0].isalpha() and s[1].isdigit() and 0 < int(s[1]) < 9:
        print(i, s)

```

Try it online!

The complete list is:

```
181, 182, 183, 184, 185, 186, 187, 188, 199, 200, 201, 202, 203, 204, 205, 206, 217, 218, 219, 220, 221, 222, 223, 224, 235, 236, 237, 238, 239, 240, 241, 242, 253, 254, 255, 256, 257, 258, 259, 260, 271, 272, 273, 274, 275, 276, 277, 278, 289, 290, 291, 292, 293, 294, 295, 296, 307, 308, 309, 310, 311, 312, 313, 314

```

## Scoring

This is , shortest code in bytes wins

# Answer
> 12 votes
# Jelly, ~~8~~ 7 bytes

```
9Ṗ+pṖḅḤ

```

Try it online!

-1 byte thanks to Lynn by combining our answers, so make sure to upvote their answer as well!

## How it works

```
9Ṗ+pṖḅḤ - Main link. Takes no arguments
9       - Set the return value to 9, and execute with 9 on the left
 Ṗ      - Pop, yielding [1,2,3,4,5,6,7,8]
  +     - Add 9 to each: [10,11,12,13,14,15,16,17]
    Ṗ   - Pop, yielding [1,2,3,4,5,6,7,8]
   p    - Cartesian product: [[10,1],[10,2],...,[17,8]]
      Ḥ - Unhalve; Yield 18
     ḅ  - Unbase; Convert [a, b] to 18a+b

```

# Answer
> 11 votes
# Python 3, 55 bytes

Edit: Was 56 bytes, now 55. Thanks to Dronir for proposing printing the numbers as a list.

Edit: Was 57 bytes, now 56. Thanks to Neil for proposing the `-~j` modification.

```
print([18*i-~j for i in range(10,18)for j in range(8)])

```

Try it online!

# Python 2, 53 bytes

Thanks to Kevin Cruijssen for propsing switching to Python 2 to save a couple of bytes.

```
print[18*i-~j for i in range(10,18)for j in range(8)]

```

Try it online!

# Answer
> 9 votes
# , ~~35~~ 17 bytes

```
1:8+18*80:143%/%8

```

Try it online!

# Answer
> 8 votes
# Python 2, ~~37~~ 36 bytes

```
x=64
while x:x-=1;print 314-x-x/8*10

```

Try it online!

1 byte saved thanks to loopy walt

# Answer
> 8 votes
# Jelly, 8 bytes

```
18⁵rṖp8ḅ

```

Try it online!

```
18         18
  ⁵r       Range from ⁵=10: [10..18]
    Ṗ      Remove last element: [10..17] ([a..h])
     p8    Cartesian product with [1..8]
       ḅ   Convert from base 18

```

# Answer
> 7 votes
# , ~~44~~ ~~25~~ 22 bytes

```
x=180:313;x[x%%18<8]+1

```

Try it online!

# Answer
> 7 votes
# 05AB1E, ~~11~~ 10 bytes

```
8Lã18δβƵz+

```

-1 byte thanks to *@ovs*.

Try it online.

A port of *@JosephWalker*'s Python 3 answer is 11 bytes: `7ÝT+18*8LâO` \- Try it online.
A port of *@Arnauld*'s JavaScript first answer is 12 bytes: `ƵΔƵÖŸʒ<18%8‹` \- Try it online.
A port of *@GB*'s Ruby answer is 12 bytes as well: `63ÝD8÷T*ƵΘ++` \- Try it online.
A port of *@ovs*' APL answer is 13 bytes: `ƵgLD18%9›ÏƵη+` \- Try it online.
A port of *@Giuseppe*'s R answer is 14 bytes: `80ƵgŸ8÷18*8LÞ+` \- Try it online.

**Explanation:**

```
8L         # Push a list in the range [1,8]
  ã        # Create all possible pairs with the cartesian product
     δ     # Map over each pair:
   18 β    #  Convert it from a base-18 list to an integer
       Ƶz+ # And add 162 to each
           # (after which the result is output implicitly)

```

See this 05AB1E answer of mine (section *How to compress large integers?*) to understand why `Ƶz` is `162`.

# Answer
> 6 votes
# Ruby, 27 bytes

```
64.times{|x|p x+x/8*10+181}

```

Try it online!

# Answer
> 6 votes
# APL (Dyalog Unicode), 14 bytes

```
171+⍸9<18|⍳143

```

Try it online!

# Answer
> 6 votes
# BQN, 16 bytes

```
(181+⊢+18×⊣)⌜˜↕8

```

Run it online! Outputs an 8x8 array of numbers.

### Explanation

A port of my Pip solution.

```
(181+⊢+18×⊣)⌜˜↕8
               ↕8  Range(8)
(           )⌜˜    Generate a table, using that range twice, with this function:
        18×⊣         18 times left argument
     ⊢+              plus right argument
 181+                 plus 181

```

# Answer
> 5 votes
# JavaScript (V8), 35 bytes

Test modulo \\$18\\$.

```
for(n=180;n<314;)n++%18<8&&print(n)

```

Try it online!

---

# JavaScript (V8), 36 bytes

Expanding \\$\[0\dots63\]\\$ in reverse order to \\$\[181\dots314\]\\$.

```
for(n=64;n--;)print(314-(n>>3)*10-n)

```

Try it online!

# Answer
> 5 votes
# Husk, 12 bytes

```
ṠṪ+mo*18+9ḣ8

```

Try it online!

```
          ḣ8 # get the range from 1..8
Ṡ            # Ṡfgx = f(g(x),x)
             # so we use the range 1..8 twice
             # once directly as an argument to f
             # and once after applying g to it
 Ṫ+          # f = Ṫ+ = outer product by addition
   mo*18+9   # g =
   mo        #   map over each element
        +9   #   add 9
     *18     #   and then multiply by 18

```

# Answer
> 4 votes
# APOL, 38 bytes

Port of Joeph Walker's genius answer, all credit goes to him.

`ḟ(10 18 v(0 ∋) ḟ(1 9 p(*(18 +(∋ ⁰)))))`

Sadly, APOL doesn't support nested for counters, so I have to use a clunkier solution. Maybe I'll implement them and come back to this later.

# Answer
> 4 votes
# Python 3 with NumPy, 62 52 46 bytes

```
lambda:18*r_[10:18]+c_[1:9]
from numpy import*

```

Try it online!

Utilizing the option to return output in a 2d array. I'm a little fuzzy on how I/O is allowed in python so let me know if this is unacceptable / I need more boilerplate.

Thanks to loopy wait for `r_` and `c_`

# Answer
> 3 votes
# APL+WIN, 24 bytes

```
18⊥(∊9+¨8/¨⍳8),[.1]64⍴⍳8

```

Try it online! Thanks to Dyalog Classic

# Answer
> 3 votes
# MathGolf, 12 bytes

```
8r♂+G*mÉ8╒+─

```

Try it online.

**Explanation:**

```
8r           # Push a list in the range [0,8)
  ♂+         # Add 10 to each to make the range [10,18)
    G*       # Multiply each by 18
      m      # Map over this list,
       É     # Using 3 characters as inner code-block:
        8╒   #  Push range [1,8]
          +  #  Add the map-integer to each
           ─ # After the map: flatten the list of lists
             # (after which the entire stack is output implicitly as result)

```

# Answer
> 3 votes
# Charcoal, 14 bytes

```
Ｉ⁺¹⁸¹Ｅ⁶⁴↨¹⁸↨ι⁸

```

Try it online! Link is to verbose version of code. I had three 15 byte solutions (including one which generated the range `a1..h8` and converted them from base 18) but I was able to golf one of them down to 14. Explanation:

```
      ⁶⁴        Literal integer `64`
     Ｅ          Map over implicit range
            ι   Current integer
           ↨ ⁸  Divmod by 8 using base conversion
        ↨¹⁸     Interpret as base 18
 ⁺¹⁸¹           Vectorised add 181
Ｉ               Cast to string
                Implicitly print

```

# Answer
> 3 votes
# Pip, 13 bytes

```
181+18*_+BMC8

```

Use with some kind of list-formatting flag: `-P` and `-S` work well. Try it online!

### Explanation

```
181+18*_+BMC8
          MC   Map the following function to coordinate pairs
            8  from an 8x8 grid:
181+            181 plus
    18*_        18 times the row number
        +B      plus the column number

```

---

Here's a 16-byte solution that uses base conversion:

```
J_MzH8CP\,8FB:18
   z              Lowercase alphabet
    H8            First 8 characters
      CP          Cartesian product with
        \,8       1-based range up to 8
  M               To each of the resulting pairs, map:
J_                 Join into a single string
           FB:    Convert from base
              18  18

```

You can run it at Replit, or a 17-byte version on TIO.

# Answer
> 3 votes
# Wolfram Language (Mathematica), 23 bytes

```
18#+162+#2&~Array~{8,8}

```

Try it online!

Returns a 2d array.

# Answer
> 3 votes
# C, ~~64~~, 62 bytes

Thank you @JustinFinnerty for the improvement

```
j;main(i){for(i=9;++i%18;)while(++j%9)printf("%d ",i*18+j%9);}

```

Try it here!

Less golfed version:

```
i,j;
main(){
    for(i=9;++i%18;)
        while(++j%9)
            printf("%d ",i*18+j%9);
}

```

# Answer
> 3 votes
# Clojure, 59 45 bytes

`(map read-string(for[x"abcdefgh"y"12345678"](str"18r"x y)))`

`(for[x(range 10 18)y(range 1 9)](+(* 18 x)y))`

# Answer
> 2 votes
# Retina 0.8.2, 37 bytes

```

63$*¶

$.`
.+
$*_181$*
_{8}
18$*
%`.

```

Try it online! Explanation:

```

63$*¶

$.`

```

Insert the numbers from `0` to `63`.

```
.+
$*_181$*

```

Convert to unary and add 181.

```
_{8}
18$*

```

Add an extra 10 for each multiple of 8 in the original number.

```
%`.

```

Convert to decimal.

# Answer
> 2 votes
# Desmos, ~~37~~ 31 bytes

```
[a+bfora=[1...8],b=[10...17]18]

```

Try It On Desmos!

Try It On Desmos! - Prettified

Finally got a chance to utilize the new list comprehension feature in Desmos!

### Explanation:

```
[   for                       ]         initiate list comprehension for loop
       a=[1...8],                       loop from a=1 to a=8, incrementing by 1
                 b=[10...17]18          loop from b=10*18 to b=17*18, incrementing by 18
                                        (essentially creates a nested for loop)
 a+b                                    calculate a+b

```

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

```
8:Ẋ18vβ⁺=+

```

Try it Online!

~~I actually didn't port anything for once lol~~ 05ab1e porting go brrr.

## Explained

```
8:Ẋ18vβ⁺=+
8:Ẋ        # The cartesian product of the range(1, 9) and range(1, 9)
   18vβ    # convert each pair from arbitrary base 18
       ⁺=+ # add 162 to each (128 + the index of `=` in the vyxal codepage)

```

## 11 bytes

```
8ƛ₀*9ɾM18vβ

```

Try it Online!

```
8ƛ₀*9ɾM18vβ
8ƛ          # For each item n in the range [1, 8]:
  ₀*        #   Mulitply n by 10
    9ɾM     #   [[n * 10, x] for x in range(1, 10)]
       18vβ #   and convert each from arbitrary base 18 to base 10

```

# Answer
> 2 votes
# X86-64 Machine Code, Microsoft Calling Convention, 27 bytes

```
33 C0                xor         eax,eax
B0 B5                mov         al,0B5h
B2 08                mov         dl,8
outerLoop:
B6 08                mov         dh,8
innerLoop:
89 01                mov         dword ptr [rcx],eax
48 83 C1 04          add         rcx,4
FF C0                inc         eax
FE CE                dec         dh
75 F4                jne         innerLoop
04 0A                add         al,0Ah
FE CA                dec         dl
75 EC                jne         outerLoop
C3                   ret

```

Which has the following function signature:

```
extern "C" void chessNumbers(uint32_t* out);

```

# Answer
> 2 votes
# Scratch, 112 bytes

Try it online!

Not much room for improvement

```
when gf clicked
set[N v]to(170
delete all of[C v
repeat(8
change[N v]by(10
repeat(8
change[N v]by(1
add(N)to[C v

```

Commentated:

```
when gf clicked      Initiates code
set[N v]to(170       Sets N to 98 (in base-18)
delete all of[C v    Clears the list
repeat(8             Loops code for each column of the chessboard
change[N v]by(10     Increases the tens digit by 1 and decreases the ones digit by 8
repeat(8             Loops code for each row of the chessboard
change[N v]by(1      Increases the ones digit by 1
add(N)to[C v         Adds N to the list

```

# Answer
> 2 votes
# Brachylog, 14 bytes

```
8⟦₁+₉ᶻ\↔ẋ~ḃ₁₈ᵐ

```

Try it online!

```
8⟦₁               Range [1..8]
   +₉ᶻ            Add 9 to each element [[1,10],[2,11],..,[8,17]]
      \↔          Transpose and swap [[10..17],[1..8]]
        ẋ         Cartesian product [[10,1],[10,2]..]
         ~ḃ₁₈ᵐ    Convert each element from base 18

```

# Answer
> 2 votes
# Python 3, 53 bytes

```
b=181
while b<308:[print(b+x)for x in range(8)];b+=18

```

Try it online!

I believe this straightforward solution is currently the shortest vanilla Python 3 solution. :)

# Answer
> 1 votes
# Perl 5, 33 bytes

```
map{//;say$_+$'*18for 1..8}10..17

```

Try it online!

# Answer
> 1 votes
# SimpleTemplate 0.84, 163 bytes

This code simply outputs a space separated list of numbers.

```
{@setN 181}{@for to314}{@if_ matches"@18[2-8]|199|2([09][0-6]|3[5-9]|4[012]|5[3-9]|60|7[1-8]|89|9[0-6])|(21|30)[789]|(22|31)[0-4]@"}{@setN N,_}{@/}{@/}{@echoj" "N}

```

It looks yucky, but works!

## How it works?

The code loops from 0 to 314, and then verifies if the number matches the following regular expression:

```
@18[2-8]|199|2([09][0-6]|3[5-9]|4[012]|5[3-9]|60|7[1-8]|89|9[0-6])|(21|30)[789]|(22|31)[0-4]@

```

If it matches, it is added to the array of numbers we need.

The generated array looks like this:

```
[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[181,182],183],184],185],186],187],188],199],200],201],202],203],204],205],206],217],218],219],220],221],222],223],224],235],236],237],238],239],240],241],242],253],254],255],256],257],258],259],260],271],272],273],274],275],276],277],278],289],290],291],292],293],294],295],296],307],308],309],310],311],312],313],314]

```

And this is the final output:

```
181 182 183 184 185 186 187 188 199 200 201 202 203 204 205 206 217 218 219 220 221 222 223 224 235 236 237 238 239 240 241 242 253 254 255 256 257 258 259 260 271 272 273 274 275 276 277 278 289 290 291 292 293 294 295 296 307 308 309 310 311 312 313 314

```

The `{@echo}` will automatically flatten the array internally, before printing it.

---

## Ungolfed:

The code is pretty nasty to look at, so, here's an ungolfed version that does the same:

```
{@set numbers 181}

{@for i from 0 to 314}
    {@if i matches "@18[2-8]|199|2([09][0-6]|3[5-9]|4[012]|5[3-9]|60|7[1-8]|89|9[0-6])|(21|30)[789]|(22|31)[0-4]@"}
        {@set numbers numbers, i}
    {@/}
{@/}

{@echo separator " " numbers}

```

---

## About the language

There are a few things that are important to know to fully understand how it works.

* Almost all whitespace is optional.
* It is required to start with `181` in the variable.
If the variable isn't set to 181, the output will be incorrect, because the first value in the array will be `null`.
* The `{@for to314}` is the same as `{@for i from 0 to 314}`.
The variable is optional, and automatically assigns to `_`.
The `from 0` isn't required, as the loop will automatically start from 0 to the final number.
* Both `{@echo separator " " numbers}` and `{@echoj" "N}` do the same:
Output the variable values separated by `" "`. The `j` stands for "join", in `echoj`.

## Running the code:

You can run the code on: http://sandbox.onlinephpfunctions.com/code/117ed06567a1d0e710e75b963566b86b510ca7ab

Please pick a version between 5.6 and 7.4.13. Can't fix the 8.0.0 compatibility issue without invalidating this answer.

# Answer
> 0 votes
# Pyth, ~~12~~ 11 bytes

```
iR18*}T17S8

```

Try it here!

*-1 byte thanks to Steffan!*

##### Explanation:

```
iR18*}T17S8 | Full code
------------+--------------------------
    *       | Cartesian product of
     }T17   |  [10..17]
         S8 |  [1..8]
iR18        | Convert each from base 18

```

---
Tags: code-golf, kolmogorov-complexity, chess
---


# Question
Title: Check if a number is a product of consecutive integer numbers
Some numbers such as: 6, 12, 20, 30, 42, 56, 60, 90, 120 and so on as can be expressed as a product of consecutive integer numbers as shown below.

```
6   = 2 * 3
12  = 3 * 4
30  = 5 * 6
60  = 3 * 4 * 5
90  = 9 * 10
120 = 4 * 5 * 6

```

Write a program or function that outputs a list of consecutive integers which product equals the specified number.

Examples of numbers that are not fit for this logic are:

```
99  = 9 * 11  (Product of non-consecutive numbers)
121 = 11 * 11 (Same numbers)
2   = 1 * 2   (Product of itself and 1)
13  = 13      (Product of only one number)

```

Please note that for the case of `2 = 2 * 1`, we do not consider it as a valid result, as a integer multiplied by 1 gives the same result. For this question, we would consider only integers \>= 2 in the product.

**Input**

A valid 32-bit positive integer. Can be from standard input, a function argument, etc.

**Output**

A list of consecutive integer numbers \>= 2 (in either ascending or descending order). If there are several combinations of consecutive integers, just provide **one** instance will do. If you provide more, its fine.

**Restrictions**

The code should take a reasonable amount of time (\< 5 minutes) to run on a standard computer for all valid inputs (positive 32-bit integers). If there is a consecutive integer product, the code should output one or more within the time limit. Else, the code should terminate with no output within the time limit.

This is code golf, so the shortest code in bytes wins.

# Answer
> 8 votes
# Java - 124

```
String f(int t){int s=2,h=3,p=s,i;String o="";for(;p!=t&&s*s<t;p=p<t?p*h++:p/s++);if(p==t)for(i=s;i<h;o+++=i+" ");return o;}

```

Starting at 2, this loops until the start number is \> the square root of the target (or target is reached exactly). If the product is low, it multiplies by the high number and increments it. If high, it divides by the starting number and increments it.

For example, for 30, it would check:

```
2*3     = 6 (too low, multiply)
2*3*4   = 24 (too low, multiply)
2*3*4*5 = 120 (too high, divide)
3*4*5   = 60 (too high, divide)
4*5     = 20 (too low, multiply)
4*5*6   = 120 (too high, divide)
5*6     = 30 (bingo!)

```

Outputs a space-separated string of factors in ascending order.

With line breaks:

```
String p(int t){
    int s=2,h=3,p=s,i;
    String o="";
    for(;p!=t&&s*s<t;p=p<t?p*h++:p/s++);
    if(p==t)
        for(i=s;i<h;o+=i+" ");
    return o;
}

```

# Answer
> 8 votes
# Python - ~~104 97 95~~ 92 try it

```
n=input()
s=i=2
c=1
while s<n:
 s*=i+c;c+=1
 if s==n:print range(i,i+c)
 if s/n:i+=1;s,c=i,1

```

If `n` is, e.g., set to 120 beforehand, the program outputs the two solutions:

```
[2, 3, 4, 5]
[4, 5, 6]

```

# Answer
> 4 votes
## Clojure - ~~127~~ 109 bytes

```
(defn f[x](first(for[r[range]y(r 2 x)v[(take-while #(<=(apply * %(r y %))x)(r y x))]:when(=(apply * v)x)]v)))

```

Example:

```
(map f [6 12 30 60 90 120 1404816 99 121 2 13])
=> ((2 3) (3 4) (5 6) (3 4 5) (9 10) (2 3 4 5) (111 112 113) nil nil nil nil)

```

Explanation:

This is basic, quite unoptimized functional approach. I create a lazy list of all the possibilities using a simple loop over them (it does skip all combinations which would give too big numbers, preventing overflow) and take the first of them. If no possibilities exist, it returns nil.

Easiest to test in http://tryclj.com/ .

---

I also now noticed that I can return all the possibilities: ~~**120 bytes**~~ **102 bytes**, but gives results in a nested list.

```
(defn f[x](for[r[range]y(r 2 x)v[(take-while #(<=(apply * %(r y %))x)(r y x))]:when(=(apply * v)x)]v))

```

Example:

```
(map f [6 12 30 60 90 120 1404816 99 121 2 13])
=> (((2 3)) ((3 4)) ((5 6)) ((3 4 5)) ((9 10)) ((2 3 4 5) (4 5 6)) ((111 112 113)) () () () ())

```

# Answer
> 4 votes
# , ~~65~~ ~~63~~ ~~61~~ 58 bytes

*Edit: -2 bytes, and then -2 more bytes, thanks to Giuseppe*

*Edit: -3 bytes thanks to Robin Ryder*

```
x=scan();`[`=`for`;i[1:x,j[1:x-i,if(prod(i:j)==x)a=i:j]];a

```

Try it online!

I really tried to find something cleverer and shorter, but couldn't.
Loops (unusually for R) through all combinations of consecutive integers from 1..x ~~2..x, printing any that whose product equals x. Breaking out of two loops is very awkward, so its shorter code to just print all the successes~~. (see explanation of Robin Ryder's improvement below).

Giuseppe's (second) 2-byte saving comes from redefining the array-index operator `[]` as the `for` command. This is a classic  golf - since all operations and commands are functions that can be redefined (including indexing and `for`) - but has the side-effect of making the code almost unreadable afterwards... (and, if you ever used this in 'real' code, it would make all of  almost unuseable afterwards, since indexing is now no longer possible!).

Robin's 3-byte saving skips my previous careful avoidance of non-valid ranges that don't include `1`, and instead sets-up the loops so that the *last* range found will always be valid. So, we just need to remember this (as the variable `a` here) and output it when we're finished. This has the effect that non-valid inputs leave `a` undefined, and so 'terminate' with no output by throwing an error.

# Answer
> 3 votes
# CJam, 31 bytes

```
q~:Qmq,A,m*{2f+~,f+_:*Q={p}*}%;

```

It's a brute-force approach, but execution time is only a couple of seconds using the official Java interpreter.

If you want to test the code using the online interpreter, you should keep the input reasonably low. Anything less than 226 still works on my machine.

### Examples

```
$ TIME="%e s"
$ time cjam product.cjam <<< 2
0.12 s
$ time cjam product.cjam <<< 6
[2 3]
0.10 s
$ time cjam product.cjam <<< 120
[2 3 4 5]
[4 5 6]
0.12 s
$ time cjam product.cjam <<< 479001600
[2 3 4 5 6 7 8 9 10 11 12]
0.68 s
$ time cjam product.cjam <<< 4294901760
[65535 65536]
1.48 s
$ time cjam product.cjam <<< 4294967295
1.40 s

```

### How it works

```
q~:Q      " Read from STDIN, interpret the input and save the result in variable “Q”.     ";
mq,       " Push the array [ 0 1 2 … (Q ** 0.5 - 1) ].                                    ";
A,m*      " Push the array [ 0 1 2 … 9 ] and take the Cartesian product.                  ";
{         " For each pair in the Cartesian product:                                       ";
  2f+     " Add 2 to each component.                                                      ";
  ~       " Dump the array's elements on the stack.                                       ";
  ,       " Push the array [ 0 1 2 … n ], where “n” is the topmost integer on the stack.  ";
  f+      " Add “m” to each element, where “m” is the integer below the array.            ";
  _:*     " Duplicate the resulting array and push the product of its elements.           ";
  Q={p}*  " If the product is equal to “Q”, print.                                        ";
}%        " Collect the remaining results into an array.                                  ";
;         " Discard the array from the stack.                                             ";

```

# Answer
> 2 votes
# Java, 162

returns an array of integers, or `null` if there are no consecutive numbers that exist.

```
int[] e(int n){for(int i=1;i<n;i++){int h=i+1,c=1,s=i;while(s<n){c++;s*=h++;}if(s==n){int[] o=new int[c];for(int j=0;j<c;j++){o[j]=h-j-1;}return o;}}return null;}

```

ungolfed:

```
int[] execute(int input){
    for(int i=1; i<input; i++){
        int highest = i+1, count = 1, sum = i;
        while(sum < input){
            count++;
            sum *= highest++;
        }
        if(sum == input){
            int[] numbers = new int[count];
            for(int j=0; j<count; j++){
                numbers[j] = highest-j-1;
            }
            return numbers;
        }
    }
    return null;
}

```

# Answer
> 2 votes
# C 105 110 try it

```
n,k,l;main(i){for(scanf("%d",&n);++i<n;)for(k=1,l=i;k<n;)if(k*=l++,k==n)for(l=n;l/=i;)printf("%d ",i++);}

```

**144** with bonus: this one iterates through every number and finds matching products

```
main(i,j,k,l,m){for(scanf("%d",&m);++i<13;)for(j=0;++j<46341-i;){for(l=k=1;k<=i;)l*=j+k++;if(l==m)for(puts(""),k=0;k<i;)printf("%d ",j+k+++1);}}

```

# Answer
> 2 votes
## PHP 258 chars, 201 not counting factorial function.

The simplest way to mathematically express "consecutive factors that equal a number" is `X!/Y!` Where `X` is the highest number and `Y` is the lowest minus one. Unfortunately I stopped taking calculus before I learned to solve `Z = X!/Y!`, so I had to bruteforce it a little.

**Messy, ungolfed version:**

```
<?php
// PHP does not define a factorial function, so I've kludged one in.
function fact($n) {
    $r = 1;
    for($i=$n; $i>1; $i--) {
        $r *= $i;
    }
    return $r;
}

$input = intval($argv[1]);

if( $input < 2 ) { die('invalid input'); }

printf("input: %s\n", $input);

$max=min(ceil(sqrt($input)),170); // integer breakdown for > 170!
$grid = array();
for( $x=1;$x<$max;$x++ ) {
    for( $y=$max;$y>=1;$y-- ) {
        if( $y >= $x ) { continue; } // Skip results that would be < 1
        $cur = fact($x)/fact($y);
        if( $cur > $input ) { // too large!
            echo "\n"; continue 2;
        }
        if( $cur == $input ) { //just right
            printf("%7d\n\nFound %s == %s\n", $cur, implode(' * ', range($y+1, $x)), $cur);
            break 2;
        }
        printf("%7d ", $cur);
    }
    echo "\n";
}
if($cur!=$input){printf("No consecutive factors produce %d\n", $input);}

```

Example output:

```
input: 518918400

  2
  3       6
  4      12      24
  5      20      60     120
  6      30     120     360     720
  7      42     210     840    2520    5040
  8      56     336    1680    6720   20160   40320
  9      72     504    3024   15120   60480  181440  362880
 10      90     720    5040   30240  151200  604800 1814400 3628800
 11     110     990    7920   55440  332640 1663200 6652800 19958400 39916800
 12     132    1320   11880   95040  665280 3991680 19958400 79833600 239500800 479001600
 13     156    1716   17160  154440 1235520 8648640 51891840 259459200
 14     182    2184   24024  240240 2162160 17297280 121080960
 15     210    2730   32760  360360 3603600 32432400 259459200
 16     240    3360   43680  524160 5765760 57657600 518918400

Found 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 == 518918400

```

**Golfed:**

```
<? function f($n){$r=1;for($i=$n;$i>1;$i--)$r*=$i;return $r;}$i=$argv[1];$m=min(ceil(sqrt($i)),170);for($x=1;$x<$m;$x++){for($y=$m;$y>0;$y--){if($y>=$x)continue;$c=f($x)/f($y);if($c>$i)continue 2;if($c==$i){$y++;echo "$y $x";break 2;}}}if($c!=$i){echo 'No';}

```

Output:

```
[sammitch@vm ~/golf] time php consecutive_golf.php 518918400
9 16
real 0m0.019s
user 0m0.011s
sys  0m0.009s
[sammitch@vm ~/golf] time php consecutive_golf.php 518918401
No
real 0m0.027s
user 0m0.017s
sys  0m0.011s

```

I was not expecting the run time to be quite this quick!

# Answer
> 2 votes
# Pyth, 35

```
JvwKr2 4W-ZJ~@KgJZ1=YurGHK=Zu*NTY)Y

```

**Note:** My code actually finds the shortest representation of the input as a representation of consecutive integers \>=2, so on invalid input it will print a 1 element list, possibly after a very long time. Since the problem statement says the input will be valid, I assume this is OK.

**Short explanation:**

Essentially, the program stores the upper and lower limits of a range, calculates the product of the numbers in the range using a reduce, adjusts the endpoints as necessary, and repeats until the product equals the input.

**Long explanation:**

For each snippet of code, I will give equivalent python, as well as a more detailed explanation and reasoning.

`Jvw` =\> `J=eval(input())`

Standard way to take input in Pyth.

`Kr2 4` =\> `K=range(2,4)` =\> `K=[2,3]`

Here's the first weird part: Instead of storing the endpoints as separate variables, I'm storing them as elements of a list. The reason will soon be clear. Also, instead of doing a simple assignment, which in Pyth would be `K[2 3)`, I'm using a range to save a character.

`W-ZJ` =\> `while Z-J` =\> `while Z!=J`

At this point, you might ask, "What is Z? You haven't defined it." In Pyth, all variables come predefined. Z happens to start as 0. However, Z will be set to the value of the product later, so this check will serve to end the while loop once the list is at the correct value.

`~@K>JZ1` =\> `K[J>Z] += 1`

Here's why I'm storing the values in a list, not in separate variables: I want to increment one of the two endpoints, depending on whether the product is currently too high or too low. That would be a rather long conditional if the endpoints were separate variables, but with the magic of list indexing, it becomes short. Also, the fact that this check comes before the product, and the fact that Z is initialized to 0, ensure that K will be `[2,4]` by the time we first take the product, which are the proper endpoints.

`=YurGHK` =\> `Y=reduce(lambda G,H: range(G,H),K)` =\> `Y=range(K[0],K[1])`

Now, I need the actual list that the product will be taken over, and that will be printed out if we succeed. Clearly, we will use a range function. The trickiness lies in obtaining the inputs to the range function. The obvious way to do this, by indexing the list, would be `=Yr'K@K1`. However, by using a reduce function on this two element list, we can shorten that by a character.

`=Zu*NTY` =\> `Z=reduce(lambda N,T: N*T,Y)`

And now, for the whole point of this affair, the reduce operation to find the product of the list.

`)` =\> End while

`Y` =\> `print(Y)`

On success, print the list.

**Example run:**

```
$ cat seq_prod
JvwKr2 4W-ZJ~@K>JZ1=YurGHK=Zu*NTY)Y

$ cat seq_prod | python3 pyth.py
<debug stuff>
==================================================
[9, 10, 11, 12, 13, 14, 15, 16]

```

# Answer
> 2 votes
# Jelly, 7 bytes

```
’ḊẆP=¥Ƈ

```

Try it online!

-1 byte thanks to Shaggy's help!

## How it works

```
’ḊẆP=¥Ƈ - Main link. Takes an integer n on the left
’       - Decrement n
 Ḋ      - Generate the range [2, 3, ..., n-1]
  Ẇ     - Yield all contiguous sublists: [[2], [3], [4], [5], ..., [2, 3, 4, ... n-1]]
     ¥Ƈ - Keep those lists where the following is true:
   P    -   The product of the list...
    =   -   ...is equal to n

```

# Answer
> 2 votes
# Husk, 9 bytes

```
fo=¹ΠQ↓2ŀ

```

Try it online!

# Answer
> 2 votes
# Vyxal `m`, ~~9~~ ~~7~~ 6 bytes

```
ḢÞSvΠc

```

*-2 bytes thanks to emanresu A*

*-1 byte thanks to Steffan*

Try it online, or verify more test cases.

Explanation:

```
Ḣ       # Range from 2 to n-1 (m flag makes it n-1)
 ÞS     # All sublists
   vΠ   # Calculate the product on each
     c  # Contains the input

```

# Answer
> 1 votes
## Java - 115

```
void f(int i){for(int j=2;j<i;j++)for(int k=1,x=j;(x*=j+k)<i;k++);if(x==i)for(i=j;i<j+k;i++)System.out.println(i);}

```

Slightly less golfed:

```
void f(int i) {
 for(int j=2; j<i; j++)
  for(int k=1, x=j; (x*=j+k) < i; k++);
   if(x == i)
    for(i=j; i<j+k; i++)
     System.out.println(i);
}

```

# Answer
> 1 votes
# Matlab (88)

Code expects number to be stored in `x` and output in `l`.

```
for n=2:12
r=ceil(x^(1/n))
for s=-3*n:n
l=r-s+(1:n)
if prod(l)==x
return
end;end;l=x;end

```

Since `13! > 2^32` this code searches only for products of length 2 upto 12. This code has a constant runtime of around 0.001s.

# Answer
> 1 votes
# Scala - 86

```
def p(n:Int)=(2 to n).flatMap(i=>(i to n).map(i to _-1).find(_.product==n)).headOption

```

This code is very inefficient but optimizing it would only add a few more characters. It uses a functional approach to check the products of all possible consecutive sequences. (a consecutive sequence of integers is represented as a Range object in Scala)

ungolfed:

```
def product(n: Int): Option[Range] = {
  def productStartingAt(start: Int): Option[Range] =
    (start to n-1).map(start to _).find(_.product == n)

  (2 to n).flatMap(i => productStartingAt(i)).headOption
}

```

# Answer
> 1 votes
## CJam *does not currently work for large numbers due to long computation time*

This is my shortest CJam code. Test at http://cjam.aditsu.net/. It works by: defining input as A; creating an array of all numbers from 0 to A-1; Kicking 0; kicking the smallest numbers until multiplying all numbers in the array is not greater than A; checking if it is greater than A; if not, creating an array from 0 to A-2; and repeating until the answer is found. If none is found, an exception is thrown. I didn't consider that spaces between numbers were needed so they are inlcuded in the second code which is 32 characters long.

```
ri:A,{)\;,1{;(;_{*}*_A>}gA<}g

ri:A,{)\;,1{;(;_{*}*_A>}gA<}g" "*

```

# Answer
> 1 votes
## Dart - 102 chars

This is a slow implementation. It can be made faster but that requires more characters (like doing the loop only until `i*i<n`)

```
f(n,[i=2]){
  t(j,p,a)=>p<n?t(++j,p*j,a..add(j)):p>n?f(n,i+1):a;
  for(;i<n;i++)if(n%i<1)return t(i,i,[i]);
}

```

(The 102 chars is without line breaks and leading spaces).

To use it, do something like:

```
main() {
  print(f(123456789*123456790));
}

```

# Answer
> 1 votes
# Japt, 9 bytes

```
o ã æÈ×¶U

```

Try it

```
o ã æÈ×¶U     :Implicit input of integer U
o             :Range [0,U)
  ã           :Sub-arrays (in order of length)
    æ         :Get the first that returns true
     È        :When passed through the following function
      ×       :Reduce by multiplication
       ¶U     :Test for equality with U

```

# Answer
> 1 votes
# Brachylog, 8 bytes

```
⟦b₂s.×?∧

```

Try it online!

### How it works

```
 ⟦b₂s.×?∧
 ⟦b₂        in the range from 2 to input
    s       any consecutive sublist
            (with longer list tried out first,
             so [input] will be tried last)
     .      is the output, if …
      ×     the product of the list
       ?    is the input.
        ∧   return the output

```

# Answer
> 1 votes
# 05AB1E, 7 bytes

```
L¦¨ŒʒPQ

```

Outputs a list of all possible results.

Try it online or verify all test cases.

**Explanation:**

```
L        # Push a list in the range [1, (implicit) input-integer]
 ¦¨      # Remove the first and last values to make the range [2, input)
   Œ     # Get all sublists of this list
    ʒ    # Filter this list of lists by:
     P   #  Where the product of the sublist
      Q  #  Is equal to the (implicit) input
         # (after which the filtered list of lists is output implicitly as result)

```

# Answer
> 0 votes
# **Javascript, 88**

Golfed code:

```
function f(a){for(i=2;i<a;i++){b=[1];for(j=i;j>1;j--)if((b[0]*=b[i-j+1]=j)==a)alert(b)}}

```

Easier to read (nicely spaced) code:

```
function f(a){
    for(i=2;i<a;i++){
        b=[1];
        for(j=i;j>1;j--)
            if((b[0]*=b[i-j+1]=j)==a)
                alert(b);
    }
}

```

For each number from 2 to the input number, it finds the product of consecutive integers from the current number back down to 2. If this product equals the input number, then the series of consecutive numbers, along with the original input number, is output.

It outputs the input number followed by the consecutive integers whose product is the input number.

For example f(120) produces an alert with the text "120,5,4,3,2" and then a second alert with the text "120,6,5,4".

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

```
{⍵∊∊{⍵×/x}¨x←1↓⍳⍵}

```

Try it online!

## Explanation

```
{⍵∊∊{⍵×/x}¨x←1↓⍳⍵}
           x←1↓⍳⍵  assign range from 2 to n to x
          ¨        map over range using function
    {⍵×/x}         get products of subsets of size ⍵ in x
                   (this gets all reuquired products of consecutive numbers > 1)
   ∊               enlist/flatten the vector of vectors
 ⍵∊                is n present in the products?

```

---
Tags: code-golf, math, arithmetic, restricted-time, factoring
---


title: As close to flat as possible

text:
# Question
Title: As close to flat as possible
Write a program or function that fulfills the following

* Scores less than 101 bytes under normal rules
* Takes no input1 and always outputs a single integer.
* Every integer is a possible output.

Your score will be the probability of the most frequent integer occurring, with a lower scoring being the goal. That is \\$\mathrm{sup}\left\\{P(x)|x\in\mathbb{Z}\right\\}\\$.

Since a few of these properties are not program decidable, you should be ready to provide a proof that your answer is valid and obtains the score it claims.

---

1 You may optionally take a stream of random bits, or a subroutine which produces random bits on each call as an input to provide randomness. Each bit will be uniform and independent of other bits.

# Answer
> 10 votes
# Python 3, score \\$\approx \frac{1}{\sqrt{8\pi\lambda}}\\$ where \\$\lambda \approx 9\uparrow\uparrow (9\uparrow \uparrow (9 \uparrow \uparrow (9 \uparrow \uparrow (9\uparrow\uparrow 9)))))\\$

This is `g(9)`, approximately `10^(10^(10^(10^(10^(10^(10^8.567841344463464))))))`; I'm doing `g(g(g(g(g(9)))))` to get the \\$\lambda\\$ above.

\\$a \uparrow b\\$ (Knuth's up-arrow notation) is `a` to the power of `b`. \\$a \uparrow\uparrow b\\$ is `a` to the power of itself, `b` times. So \\$9\uparrow\uparrow 3 = 9^{9^9}\\$ and \\$9\uparrow\uparrow 9 = 9^{9^{9^{9^{9^{9^{9^{9^{9}}}}}}}}\\$

```
from numpy.random import*
g=lambda n:n and 9**g(n-1)
print(choice([-1,1])*poisson(g(g(g(g(g(9)))))))

```

DON'T Try it online! Blows the recursion limit, of course.

How it works:

The Poisson distribution is a random distribution that, by itself, already generates random positive integers from 0 to infinity. This distribution takes a parameter, \\$\lambda \\$, that affects how likely the smaller integers are. What we have to do is set \\$\lambda\\$ in such a way that small numbers become **very** unlikely.

Then we use the wiki page again to realize the *mode* of the distribution is related to its parameter and then we plug the mode into the probability density function to get the program's score. After that we use Sterling's approximation to simplify the expression to something that is only slightly more digestible.

If I really can't waive the recursion limit then a similar approach with a loop gives

### Python 2, score \\$\approx \frac{1}{\sqrt{8\pi\lambda}}\\$ where \\$\lambda = 9\uparrow\uparrow (9 \uparrow\uparrow 7)\\$

```
from numpy.random import*
print(choice([-1,1])*poisson(eval('**'.join(`9`*9**9**9**9**9**9**9**9))))

```

Don't try it online! Got some more bigness because @xnor taught me how `join` works when used directly on strings.

# Answer
> 9 votes
# 05AB1E, score 0.5 / 1000!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

*bug fix thanks to FryAmTheEggman*

*+1 `!` thanks to ExpiredData*

```
 [₄!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!LΩ#¼]¾D±)Ω

```

(dont't) Try it online! (will timeout).

Try it online without the factorials

```
[           ]            # loop:
 ₄                       #  1000
  !!...!                 #  take the factorial, 88 times
        LΩ               #  pick a random number from 1 to that many
          #              #  if the number was 1, exit the loop
           ¼             #  increment counter_variable
             ¾           # after the loop: push counter_variable
              D±         # push its bitwise negation
                )        # wrap the two in a list
                 Ω       # pick a random element of that list

```

Any integer would work instead of `1000!!...!`, so this approach could score as low as `0.5 / BB(89)`, where `BB` is 05AB1E's Busy Beaver function.

# Answer
> 3 votes
# Jelly, 1 / 2M ?\*,

* Any help scoring this appreciated, 0 and -1 are the two equally most likely answers at \\$\frac{1}{2M}\\$ \- see code breakdown.

Inspiration taken from Grimmy's 05AB1E answer.

```
‘ɼµ⁹!!!!;”!ẋ$VƊ;”!ẋ$VƊ;”!ẋ$VƊ;”!ẋ$VƊ;”!ẋ$VƊ;”!ẋ$VƊ;”!ẋ$VƊ;”!ẋ$VƊ;”!ẋ$VƊ;”!ẋ$VƊ;”!ẋ$VƊ;”!ẋ$VƊX’µ¿~2X¤¡

```

No point trying this online!

**Try incrementing with 4 increment tetrations** (with incrementing the self-referential tetration is just doubling, also start with 2 rather than 256 so n=(2+1+1+1+1)\*2\*2\*2\*2=96, much more likely to terminate)

### How?

```
‘ɼµ⁹!!!!;”!ẋ$VƊ;”!ẋ$VƊ ... X’µ¿~2X¤¡ - Link, no arguments
                              ¿      - while...
  µ                          µ       - ...condition: monadic chain (f(0)):
   ⁹                                 -     256
    !                                -     factorial = 256*255*...*1 = a
     !                               -     factorial = a*(a-1)*...*1 = b
      !                              -     factorial = b*(b-1)*...*1 = c
       !                             -     factorial = c*(c-1)*...*1 = A
              Ɗ                      -     last three links as a monad:
            $                        -       last two links as a monad:
         ”!                          -         literal '!' character
           ẋ                         -         repeated A times
        ;                            -       concatenate to A -> number A with A '!' after it
             V                       -       evaluate as Jelly code -> A!!..! * (A!!..!-1) * ... * 1
               ;”!ẋ$VƊ               -     call that B and repeat that process
                       ...           -     repeat 10 more times giving us M
                           X         -     choose a random integer in [1..M] inclusive
                            ’        -     decrement (i.e. while random choice != 1)
                                   ¡ - repeat...
                                  ¤  - ...number of times:
                                2    -   two
                                 X   -   random integer in [1,2] inclusive
                               ~     - ...action: bitwise NOT

```

# Answer
> 3 votes
# C (gcc), 99 bytes

```
f(b,t)long b(),t;{for(b()/4503599627370496&&printf("-");t-9007199254740992;t=b())putchar(t%10+48);}

```

`b` is a function returning 52 random bits in the form of an integer in the range of \[0, 9007199254740992).

Try it online!

# Answer
> 3 votes
# Pyth, score of the order \\$f\_{\varphi(\omega,0)+1}(10^{10^{64}})^{-1}\\$

```
M,-.<hG@H1.<hH@G1+@G1@H1D%ZYI<hZ0R,_hZ@Z1J,1 0V.<1Y=J%gZJY)R,hJ+@J1YVC*GCG=T@%TT1)K0WOT=+K1)IO2K.?_K

```

Don't try it online!

# Pyth, score of the order \\$f\_{\varphi(\omega,0)+\omega}(4)^{-1}\\$

(More precisely around \\$f\_{\varphi(\omega,0)+4}(10)^{-1}\\$)

```
M,-.<hG@H1.<hH@G1+@G1@H1D%dYI<hd0R,_hd@d1J,1 0V.<1Y=J%gdJY)R,hJ+@J1YVTVTVTVT=T@%TT1;WOT=+Z1)IO2Z.?_Z

```

Don't try it online!

# Original python, but in the Pyth I made changes to increase size:

```
import random
g=lambda G,H:(G[0]<<H[1]-H[0]<<G[1],G[1]+H[1])
def C(Z,Y):
  if Z[0]<0: return -Z[0],Z[1]
  J=(1,0)
  for N in range(1<<Y):J=C(g(Z,J))
  return J[0],J[1]+Y
T=10
for N in range(T): T=C(T,T)[1]
K=0
while random.randint(0,T):
  K+=1
if random.randint(0,1):
  print(K)
else:
  print(-K)

```

# Explanation

This uses the extremely fast growing functions \\$M\_n\\$ defined here. They're actually my go-to when I need fast-growing functions, since they have a growth rate approaching \\$\varphi(\omega,0)\\$ and are simple to implement. Since they operate on fractions, I use the representation \\$(a,b)=\frac{a}{2^b}\\$. I iterate the operation \\$n\mapsto M\_{2^n}(n)\\$ starting from 10 roughly \\$10^{10^{64}}\\$ times, then output integers in a geometric distribution with parameter \\$\frac{1}{n}\\$, with signs attached. Thus, the score is \\$\frac{1}{n}\\$. Yes, you can slightly improve it, but it's so big your improvements are negligible.

Yes, this absolutely dominates every other entry so far.

# Answer
> 1 votes
# Charcoal, 26 bytes, score 0.0005

```
Ｗ‽φ⊞υωＩ⎇‽²Ｌυ±⊕Ｌυ

```

Try it online! Link is to verbose version of code. `0` and `-1` have probabilities of 0.0005, then each subsequent integer has a probability 0.999 times that of the previous. Obviously there are still 75 bytes with which to create some form of arbitrary large expression in order to obtain a lower score, but the resulting code would take longer than the heat death of the universe to run, so it's not quite suitable for TIO. Explanation:

```
Ｗ‽φ

```

While a random number `0..999` is non-zero...

```
⊞υω

```

...push the empty string to the empty list.

```
Ｉ⎇‽²Ｌυ±⊕Ｌυ

```

Randomly print either the length of the list or `-1` minus that length.

# Answer
> -1 votes
# bash + linux, 1 / big number

```
cat /dev/random | hexdump -n `b` -ve '/1 "%02u"'

```

This program will print out 'b' bytes of decimal digits, where b is a program producing a random input number.

(edited to try to be more infinity-ish, although technically still limited by the bash shell)

---
Tags: code-challenge, restricted-source, random, open-ended-function, busy-beaver
---


title: Sum the deltas of my matrix

text:
# Question
Title: Sum the deltas of my matrix
### Background

*The deltas* of an array of integers is the array formed by getting the differences of consecutive elements. For example, `[1, 2, 4, 7, 3, 9, 6]` has the following deltas: `[1, 2, 3, -4, 6, -3]`.

We will now define the deltas of a matrix of integers as the deltas of each row and each column it contains.

As an example:

```
Row deltas:

1 2 3 4 │ => [1, 1, 1]
4 5 6 7 │ => [1, 1, 1]
7 1 8 2 │ => [-6, 7, -6]

Column deltas (the matrix' columns have been rotated into rows for simplicity):

1 4 7 │ => [3, 3]
2 5 1 │ => [3, -4]
3 6 8 │ => [3, 2]
4 7 2 │ => [3, -5]

```

Which gives us the following list of matrix deltas:

```
[[1, 1, 1], [1, 1, 1], [-6, 7, -6], [3, 3], [3, -4], [3, 2], [3, -5]]

```

And as we don't want them to be nested, we flatten that list:

```
[1, 1, 1, 1, 1, 1, -6, 7, -6, 3, 3, 3, -4, 3, 2, 3, -5]

```

---

### Task

Your task is to *sum all the deltas* of a matrix given as input. Note that the matrix will only consist of non-negative integers.

### Rules

* All standard rules apply.
* You may assume the matrix contains at least two values on each row and column, so the minimum size will be **2x2**.
* You may take the matrix in any reasonable format, as long as you specify it.
* You *may not* assume that the matrix is square.
* If it might help you reduce your byte count, you *may* optionally take the number of rows and the number of columns as input as well (Looking at you C!).
* This is code-golf, so the shortest code (in bytes), *in each language* wins!

### Test Cases

```
Input  =>  Output

[[1, 2], [1, 2]]                                    => 2
[[8, 7, 1], [4, 1, 3], [5, 5, 5]]                   => -9
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]                   => 24
[[9, 9, 9, 9, 9], [9, 9, 9, 9, 9]]                  => 0
[[1, 3, 14], [56, 89, 20], [99, 99, 99]]            => 256
[[1, 2, 3, 4], [4, 5, 6, 7], [7, 1, 8, 2]]          => 9
[[13, 19, 478], [0, 12, 4], [45, 3, 6], [1, 2, 3]]  => -72

```

# Answer
# Python 2, 42 bytes

```
lambda m:sum(r[-1]-r[0]for r in m+zip(*m))

```

An unnamed function taking a list of lists, `m`, and returning the resulting number.

**Try it online!**

### How?

The sum of the deltas of a list is the last element minus the first, everything else just cancels:
**(r\[n\]-r\[n-1\])+(r\[n-1\]-r\[n-2\])+...+(r\[2\]-r\[1\]) = r\[n\]-r\[1\]**

The `zip(*m)` uses unpacking (`*`) of `m` to pass the rows of `m` as separate arguments to `zip` (interleave) and hence transposes the matrix. In python 2 this yields a list (of tuples, but that's fine), so we can add (concatenate) it to (with) `m`, step through all our rows and columns, `r`, perform the above trick for each and just add up the results (`sum(...)`).
> 12 votes

# Answer
# Octave, 33 bytes

```
@(x)sum([diff(x)(:);diff(x')(:)])

```

Try it online!

### Explanation:

This is an anonymous function taking `x` as input. It takes the difference between all columns, and concatenates it with the difference between the columns of the transposed of `x`. It then sums this vector along the second dimension.
> 8 votes

# Answer
# , 34 bytes

```
function(m)sum(diff(m),diff(t(m)))

```

Try it online!

Anonymous function. Originally, I used `apply(m,1,diff)` to get the rowwise diffs (and `2` instead of `1` for columns) but looking at Stewie Griffin's answer I tried it with just `diff` and it worked.
> 8 votes

# Answer
# Jelly, 5 bytes

```
;ZIẎS

```

Try it online!

There are a couple ASCII-only versions too: `;ZIFS` `;ZISS`
> 5 votes

# Answer
# JavaScript (ES6), ~~68~~ 67 bytes

```
m=>m.map(r=>s+=[...l=r].pop()-r[0],s=0)|m[0].map(v=>s+=l.pop()-v)|s

```

### Formatted and commented

```
m =>                              // given a matrix m
  m.map(r =>                      // for each row r of m
    s += [...l = r].pop() - r[0], //   add to s: last value of r - first value of r
    s = 0                         //   starting with s = 0
  ) |                             //
  m[0].map(v =>                   // for each value v in the first row of m:
    s += l.pop() - v              //   add to s: last value of last row of m - v
  ) |                             //
  s                               // return s

```

Because the minimum size of the input matrix is 2x2, `m.map(...)|m[0].map(...)` is guaranteed to be coerced to `0`. That's why it's safe to return the final result with `|s`.

### Test cases

```
let f =

m=>m.map(r=>s+=[...l=r].pop()-r[0],s=0)|m[0].map(v=>s+=l.pop()-v)|s

console.log(f( [[1, 2], [1, 2]]                                   )) // => 2
console.log(f( [[8, 7, 1], [4, 1, 3], [5, 5, 5]]                  )) // => -9
console.log(f( [[1, 2, 3], [4, 5, 6], [7, 8, 9]]                  )) // => 24
console.log(f( [[9, 9, 9, 9, 9], [9, 9, 9, 9, 9]]                 )) // => 0
console.log(f( [[1, 3, 14], [56, 89, 20], [99, 99, 99]]           )) // => 256
console.log(f( [[1, 2, 3, 4], [4, 5, 6, 7], [7, 1, 8, 2]]         )) // => 9
console.log(f( [[13, 19, 478], [0, 12, 4], [45, 3, 6], [1, 2, 3]] )) // => -72
```
> 5 votes

# Answer
# MATL, 7 bytes

```
dG!dhss

```

Try it online!

### Explanation:

Suppose the input is

```
[8 7 1; 4 1 3; 5 5 5]

d        % Difference between rows of input
         % Stack:
         % [-4 -6  2; 1  4  2]
 G       % Grab the input again. Stack:
         % [-4 -6  2; 1  4  2]
         % [8 7 1; 4 1 3; 5 5 5]]
  !      % Transpose the bottom element. Stack:
         % [-4 -6  2; 1  4  2]
         % [8 4 5; 7 1 5; 1 3 5]
   d     % Difference between rows. Stack:
         % [-4 -6  2; 1  4  2]
         % [-1 -3  0; -6  2  0]
    h    % Concatenate horizontally. Stack:
         % [-4 -6  2 -1 -3  0; 1  4  2 -6  2  0]
     ss  % Sum each column, then sum all column sums. Stack:
         % -9

```
> 5 votes

# Answer
# 05AB1E, 6 bytes

```
ø«€¥OO

```

Uses the **05AB1E** encoding. Try it online!
> 4 votes

# Answer
# , 14 bytes

```
+/@,&({:-{.)|:

```

Try it online!

## Explanation

```
+/@,&({:-{.)|:  Input: matrix M
            |:  Transpose
     (     )    Operate on M and M'
      {:          Tail
        -         Minus
         {.       Head
   ,&           Join
+/@             Reduce by addition

```
> 4 votes

# Answer
# Pyth, 7 bytes

```
ss.+M+C

```

Try it here.

My first ever answer in a golfing language! Thanks to @EriktheOutgolfer for -1 byte!

## Explanation

```
ss.+M+C    ~ This is a full program with implicit input (used twice, in fact)

      C    ~ Matrix transpose. Push all the columns;
     +     ~ Concatenate with the rows;
  .+M      ~ For each list;
  .+       ~ Get the deltas;
 s         ~ Flatten the list of deltas;
s          ~ Get the sum;
           ~ Print Implicitly;

```
> 3 votes

# Answer
# Husk, 7 bytes

```
ΣṁẊ-S+T

```

Try it online!

-1 thanks to Mr. Xcoder taking my focus away from the `S` and `¤` and towards the `m` (which should've been ).
-1 thanks to Zgarb abusing `S`.

Explanation:

```
ΣṁẊ-S+T 3-function composition
    S   (x -> y -> z) (f) -> (x -> y) (g) -> x (x) (implicit): f x g x
     +    f: [x] (x) -> [x] (y) -> [x]: concatenate two lists
      T   g: [[x]] (x) -> [[x]]: transpose x
 ṁ      (x -> [y]) (f) -> [x] (x) -> [y]: map f on x and concatenate
  Ẋ       f: (x -> y -> z) (f) -> [x] (x) -> [z]: map f on splat overlapping pairs of x
   -        f: TNum (x) -> TNum (y) -> TNum: y - x
Σ       [TNum] (x) -> TNum: sum x

```
> 3 votes

# Answer
# APL, ~~18~~ 15 bytes

```
{-+/∊2-/¨⍵(⍉⍵)}

```

Try it online!
> 3 votes

# Answer
# Haskell, 60 bytes

```
e=[]:e
z=zipWith
f s=sum$(z(-)=<<tail)=<<(s++foldr(z(:))e s)

```

Try it online! Uses the shorter transpose I found a while ago.

### Explanation

`e` is an infinite list of empty lists and used for the transposing. `z` is a shorthand for the `zipWith` function, because it is used twice.

```
f s=                                        -- input s is a list of lists
                            foldr(z(:))e s  -- transpose s
                         s++                -- append the result to the original list s
                     =<<(                 ) -- map the following function over the list and concatenate the results
        (z(-)=<<tail)                       -- compute the delta of each list by element-wise subtracting its tail
    sum$                                    -- compute the sum of the resulting list

```
> 3 votes

# Answer
# Brachylog, 13 bytes

orignally based of @sundar's design

```
⟨≡⟨t-h⟩ᵐ²\⟩c+

```

## Explanation

```
⟨≡      \⟩          #   Take the original matrix and it's transpose
      ᵐ             #       and execute the following on both
       ²            #           map for each row (this is now a double map "ᵐ²")
  ⟨t h⟩             #               take head and tail
   -                #               and subtract them from each other (sum of deltas in a row)
         c+         #       and add all the values
                    #           (we have two arrays of arrays so we concat them and sum them)

```

the `⟨⟩` are messing up formatting, sorry

Try it online!
> 3 votes

# Answer
# Japt `-x`, ~~11~~ ~~10~~ 9 bytes

```
cUy)®än x

```

Try it

---

## Explanation

```
c             :Concatenate
 U            :  Input array
  y           :  Transpose
   )          :End concatenation
    ®         :Map
     än       :  Deltas
        x     :  Reduce by addition
              :Implicitly reduce by addition and output

```
> 2 votes

# Answer
# Brachylog, ~~22~~ 16 bytes

```
⟨≡{s₂ᶠc+ᵐ-}ᵐ\⟩+ṅ

```

Try it online!

*(-6 bytes inspired by @Kroppeb's suggestions.)*

```
?⟨≡{s₂ᶠc+ᵐ-}ᵐ\⟩+ṅ.       Full code (? and . are implicit input and output)
?⟨≡{       }ᵐ\⟩          Apply this on both the input and its transpose:
    s₂ᶠ                  Get pairs of successive rows, [[row1, row2], [row2, row3], ...]
       c                 Flatten that: [row1, row2, row2, row3, row3, row4, ...]
        +ᵐ               Sum the elements within each row [sum1, sum2, sum2, sum3, ...]
          -              Get the difference between even-indexed elements (starting index 0)
                         and odd-indexed elements, i.e. sum1+sum2+sum3+... - (sum2+sum3+sum4+...)
                         This gets the negative of the usual difference i.e. a-b instead of b-a
                         for each pair of rows
               +         Add the results for the input and its transpose
                ṅ        Negate that to get the sign correct
                 .       That is the output

```
> 2 votes

# Answer
# Factor \+ `math.unicode`, 48 bytes

```
[ dup flip [ [ differences Σ ] map Σ ] bi@ + ]

```

Try it online!

## Explanation:

It's a quotation (anonymous function) that takes a sequence of sequences (matrix) from the data stack as input and leaves a number (sum) on the data stack as output. Assuming `{ { 1 2 3 } { 4 5 6 } }` is on the data stack when this quotation is called...

* `dup` Duplicate an object.

**Stack:** `{ { 1 2 3 } { 4 5 6 } } { { 1 2 3 } { 4 5 6 } }`
* `flip` Transpose a matrix.

**Stack:** `{ { 1 2 3 } { 4 5 6 } } { { 1 4 } { 2 5 } { 3 6 } }`
* `[ [ differences Σ ] map Σ ]` Push a quotation for `bi@` to use later.

**Stack:** `{ { 1 2 3 } { 4 5 6 } } { { 1 4 } { 2 5 } { 3 6 } } [ [ differences Σ ] map Σ ]`
* `bi@` Apply a quotation to two objects. (Inside the quotation now...)

**Stack:** `{ { 1 2 3 } { 4 5 6 } }`
* `[ differences Σ ]` Push a quotation for `map` to use later.

**Stack:** `{ { 1 2 3 } { 4 5 6 } } [ differences Σ ]`
* `map` Take a sequence and a quotation and apply the quotation to each element in the sequence, collecting the results into a new sequence of the same length. (Inside the quotation now...)

**Stack:** `{ 1 2 3 }`
* `differences` Calculate the first-order differences of a number sequence.

**Stack:** `{ 1 1 }`
* `Σ` Sum the elements of a sequence.

**Stack:** `2`
* Now `map` applies the quotation to the next row and the result is also `2`.

**Stack:** `{ 2 2 }`
* `Σ` Sum the elements of a sequence.

**Stack:** `4`
* Thus, the first result of `bi@` is `4`. Now `bi@` repeats the process for its second input (the transposed matrix) and ends up with `9`.

**Stack:** `4 9`
* `+` Add.

**Stack:** `13`
> 2 votes

# Answer
# SOGL V0.12, 9 bytes

```
:⌡-≤H⌡-¹∑

```

Try it Here! ( added because this takes input on the stack)

Explanation:

```
:          duplicate ToS
 ⌡         for each do
  -          get deltas
   ≤       get the duplicate ontop
    H      rotate it anti-clockwise
     ⌡     for each do
      -      get deltas
       ¹   wrap all of that in an array
        ∑  sum

```
> 1 votes

# Answer
# Mathematica, 45 bytes

```
Tr@Flatten[Differences/@#&/@{#,Transpose@#}]&

```

**Input**

> \[{{13, 19, 478}, {0, 12, 4}, {45, 3, 6}, {1, 2, 3}}\]
> 1 votes

# Answer
# CJam, 19 bytes

```
0q~_z+2few:::-:+:+-

```

Input is a list of lists of numbers. **Try it online!**

### Explanation

```
0       e# Push 0
q~      e# Evaluated input.
_       e# Duplicate
z       e# Zip (transpose)
+       e# Concatenate. This gives a lists of lists of numbers, where the
        e# inner lists are the original rows and the columns
2few    e# Replace each inner list of numbers by a list of overlapping
        e# slices of size 2. We not have three-level list nesting
:::-    e# Compute difference for each of those size-two slices. We now
        e# have the deltas for each row and column
:+      e# Concatenate all second-level lists (de-nest one level)
:+      e# Sum all values
-       e# Subtract from 0, to change sign. Implicitly display

```
> 1 votes

# Answer
# APL (Dyalog Classic), 12 bytes

```
(+/⊢⌿,⊣/)⌽-⊖

```

Try it online!
> 1 votes

# Answer
# Vyxal `d`, 5 bytes

```
:∩"v¯

```

Try it online, or verify all test cases.

Explanation:

```
:      # Duplicate
 ∩     # Transpose
  "    # Pair
   v¯  # Deltas of each
       # Flatten and sum with the d flag

```
> 1 votes

# Answer
# MY, 9 bytes

```
ωΔω⍉Δ ḟΣ↵

```

Try it online!

~~Since I cannot ping Dennis in chat to pull MY (due to a suspension), this will currently not work. (`Δ` previously didn't vecify when subtracting)~~ Thanks to whomever got Dennis to pull MY!

## How?

* `ωΔ`, increments of the first command line argument
* `ω⍉Δ`, increments of the transpose of the first command line argument
* , in a single list
* , flatten
* `Σ`, sum
* , output
> 0 votes

# Answer
## Pyt, 11 bytes

```
Đ⊤ʁ-⇹ʁ-áƑƩ~

```

Explanation:

```
          Implicit input (as a matrix)
Đ         Duplicate the matrix
⊤         Transpose the matrix
ʁ-        Get row deltas of transposed matrix
⇹         Swap top two elements on the stack
ʁ-        Get row deltas of original matrix
á         Push the stack into an array
Ƒ         Flatten the array
Ʃ         Sum the array
~         Flip the sign (because the deltas are negative, as subtraction was performed to obtain them)
          Implicit output

```
> 0 votes

---
Tags: code-golf, math, integer, matrix
---


title: Converting integers to English words

text:
# Question
Title: Converting integers to English words
The goal of this code golf is to convert integers to English words.

The program prompts for input. If this input isn't an integer, print `NaN`. If it is an integer, convert it to English words and print these words. Minimum input: 0 (zero). Maximum input: 9000 (nine thousand).
So, `5` returns `five` (case doesn't matter), and `500` returns `five hundred` or `five-hundred` (dashes don't matter).

Some other rules:

A `one` before `hundred` or `thousand` is optional: `one hundred` is correct, but `hundred` too (if the input is `100` of course).

The word `and` in for example `one hundred and forty five` is optional too.

Whitespace matters. So, for `500`, `five-hundred` or `five hundred` is correct, but `fivehundred` is not.

Good luck!

# Answer
> 7 votes
## Perl 281 bytes

```
print+0eq($_=<>)?Zero:"@{[((@0=($z,One,Two,Three,Four,Five,@2=(Six,Seven),
Eight,Nine,Ten,Eleven,Twelve,map$_.teen,Thir,Four,@1=(Fif,@2,Eigh,Nine)))
[$_/1e3],Thousand)x($_>999),($0[($_%=1e3)/100],Hundred)x($_>99),
($_%=100)>19?((Twen,Thir,For,@1)[$_/10-2].ty,$0[$_%10]):$0[$_]]}"||NaN

```

Newlines added for horizontal sanity. The above may be used interactively, or by piping it a value via stdin.

Works correctly for all integer values on the range *\[0, 19999\]*, values outside this range exhibit undefined behavior. Non-integer values will be truncated towards zero, and as such, only values which are truly non-numeric will report `NaN`.

Sample usage:

```
for $n (14, 42, 762, 2000, 6012, 19791, 1e9, foobar, 17.2, -3) {
  print "$n: ", `echo $n | perl spoken-numbers.pl`, $/;
}

```

Sample output:

```
14: Fourteen
42: Forty Two
762: Seven Hundred Sixty Two
2000: Two Thousand
6012: Six Thousand Twelve
19791: Nineteen Thousand Seven Hundred Ninety One
1000000000: Thousand
foobar: NaN
17.2: Seventeen
-3: Nine Hundred Ninety Seven

```

# Answer
> 14 votes
## JavaScript (375)

Probably a terrible attempt, but anyway, here goes...

```
alert(function N(s,z){return O="zero,one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir,,fif,,,eigh,,,,twen,,for".split(","),(z?O[s]||O[s-10]||O[s-20]:s<13?N(s,1):s<20?N(s,1)+"teen":s<100?N(a=20+(s/10|0),1)+"ty"+(s%10?" "+N(s%10):""):s<1e3?N(s/100|0)+" hundred"+(s%100?" "+N(s%100):""):s<1e5?N(s/1e3|0)+" thousand"+(s%1e3?" "+N(s%1e3):""):0)||NaN}(prompt()))

```

Pretty-printed (as a function):

```
function N(s,z) {
  return O = "zero,one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir,,fif,,,eigh,,,,twen,,for".split(","),
      (z? O[s] || O[s-10] || O[s-20]
       : s < 13?  N(s,1)
       : s < 20?  N(s,1) + "teen"
       : s < 100? N(a=20+(s/10|0),1) + "ty" + (s%10?" "+N(s%10):"")
       : s < 1e3?  N(s/100|0) +  " hundred" + (s%100?" "+N(s%100):"")
       : s < 1e5?  N(s/1e3|0) + " thousand" + (s%1e3?" "+N(s%1e3):"") : 0) || NaN
}

```

Sample conversion (note that it even outputs `NaN` when out of bounds, i.e. invalid input):

```
540: five hundred forty
4711: four thousand seven hundred eleven
7382: seven thousand three hundred eighty two
1992: one thousand nine hundred ninety two
hutenosa: NaN
1000000000: NaN
-3: NaN

```

# Answer
> 11 votes
# Mathematica ~~60~~ 57

```
f = ToString@#~WolframAlpha~{{"NumberName", 1}, "Plaintext"} &

```

**Usage:**

```
f[500]

```

> five hundred

**Edit:**

```
InputString[]~WolframAlpha~{{"NumberName", 1}, "Plaintext"}

```

# Answer
> 9 votes
# Lisp, 72 56 characters

I realize 1) that this is old, and 2) that it relies entirely on the standard library to function, but the fact that you can get the c-lisp printing system to do this kind of thing has always impressed me. Also, this does in fact take the input from a user, convert it, and print it.

```
(format t "~:[NaN~;~:*~r~]" (parse-integer (read-line) :junk-allowed t))

```

It totals 72 characters.

* `:junk-allowed` causes parse-integer to return nil on failure instead of raising an error.
* `~:[if-nil~;if-non-nill]` conditional predicated on nil, handles NaN where necessary
* `~:*` backs up the argument interpretation to re-consume the input
* `~r` prints the number as an english word string, as requested, except with full corrected punctuation

Sample:

```
17823658
seventeen million, eight hundred and twenty-three thousand, six hundred and fifty-eight

192hqfwoelkqhwef9812ho1289hg18hoif3h1o98g3hgq
NaN

```

Lisp info mainly from Practical Common Lisp.

## Edit, golfed properly down to 56 characters

```
(format t "~:[NaN~;~:*~r~]"(ignore-errors(floor(read))))

```

This version works rather differently. Instead of reading a line and converting it, it invokes the lisp reader to interpret the input as a lisp s-expression, attempts to use it as a number, and if any errors are produced ignores them producing nil to feed the format string conditional. This may be the first instance I've seen of lisp producing a truly terse program... Fun!

* `(read)` Invokes the lisp reader/parser to read one expression from standard input and convert it into an appropriate object
* `(floor)` attempts to convert any numeric type into the nearest lower integer, non-numeric types cause it to raise an error
* `(ignore-errors ...)` does what it says on the tin, it catches and ignores any errors in the enclosed expression, returning nil to feed the NaN branch of the format string

# Answer
> 3 votes
# PHP, ~~327~~ ~~310~~ 308 bytes

```
<?$a=['',one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir,0,fif,0,0,eigh];echo($n=$argv[1])>999?$a[$n/1000].' thousand ':'',$n%1000>99?$a[$n/100%10].' hundred ':'',$n?($k=$n%100)<20?($a[$k]?:$a[$k%10]).[teen][$k<13]:[2=>twen,thir,'for',fif,six,seven,eigh,nine][$k/10].'ty '.$a[$k%10]:zero;

```

takes the number as parameter, works for 0\<=n\<=12999

**breakdown**

```
// define names
$a=['',one,two,three,four,five,six,seven,eight,nine,
    ten,eleven,twelve,thir,0,fif,0,0,eigh];
// print ...
echo
    ($n=$argv[1])>999?$a[$n/1000].' thousand ':'',                  // thousands
    $n%1000>99?$a[$n/100%10].' hundred ':'',                        // hundreds
    $n?
        // if remains <20:
        ($k=$n%100)<20?
            ($a[$k]?:$a[$k%10]) // no value at index (0,14,16,17,19)? value from index%10
            .[teen][$k<13]      // append "teen" for $k>12
        // else:
        :[2=>twen,thir,'for',fif,six,seven,eigh,nine][$k/10].'ty '  // tens
        .$a[$k%10]                                                  // ones
    // "zero" for $n==0
    :zero
;

```

# Answer
> 2 votes
# SAS, 70 characters

```
data;window w n;display w;if n=. then put 'NaN';else put n words.;run;

```

The `window` and `display` statements open up the SAS command prompt. Input for `n` goes on line 1. This takes advantage of the SAS format `words.` which will print the number as a word or series of words with "and", " ", and "-" as appropriate.

# Answer
> 2 votes
**PHP**

777 characters

This is definitely a terrible attempt, but you can't accuse me of taking advantage of any loopholes, plus it's a very lucky number. Thanks to ProgramFOX for the tip.

```
<?php $i=9212;$b = array('zero','one','two','three','four','five','six','seven','eight','nine');$t='teen';$c = array('ten','eleven','tweleve','thir'.$t,$b[4].$t,'fif'.$t,$b[6].$t,$b[7].$t,$b[8].$t,$b[9].$t);$d = array('','','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety');$e='hundred';$f='thousand';$j=str_split($i);if (strlen($i)===1){$a=$b[$i];}elseif (strlen($i)===3){$k=1;$a=$b[$j[0]].' '.$e.' '.x($j,$k);}elseif (strlen($i)===4){$k=2;$a=$b[$j[0]].' '.$f.' '.$b[$j[1]].' '.$e.' '.x($j,$k);}elseif (substr($i, -2, 1)==='1'){$a=$c[$j[1]];}else{$a=$d[$j[0]].' '.$b[$j[1]];}$a = str_replace('zero hundred','',$a);echo $a;function x($j,$k){global $i, $b, $c, $d;if (substr($i, -2, 1)==='1'){return $c[$j[$k+1]];}else{return $d[$j[$k]].' '.$b[$j[$k+1]];}}

```

**Long hand**

```
<?php
// Input
$i=9212;
// 0-9
$b = array('zero','one','two','three','four','five','six','seven','eight','nine');
// 10-19 (Very tricky)
$t='teen';
$c = array('ten','eleven','tweleve','thir'.$t,$b[4].$t,'fif'.$t,$b[6].$t,$b[7].$t,$b[8].$t,$b[9].$t);
// Left digit of 20-99
$d = array('','','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety');
// Hundreds
$e='hundred';
// Thousands
$f='thousand';
// Split input
$j=str_split($i);
// 1 digit inputs
if (strlen($i)===1){$a=$b[$i];}
// 3 digit input
elseif (strlen($i)===3){$k=1;$a=$b[$j[0]].' '.$e.' '.x($j,$k);}
// 4 digit input
elseif (strlen($i)===4){$k=2;$a=$b[$j[0]].' '.$f.' '.$b[$j[1]].' '.$e.' '.x($j,$k);}
// 10-19
elseif (substr($i, -2, 1)==='1'){$a=$c[$j[1]];}
// 20-99
else{$a=$d[$j[0]].' '.$b[$j[1]];}
// Fix for thousand numbers
$a = str_replace('zero hundred','',$a);
// Result
echo $a;
// Abstracted function last 2 digits for 3 and 4 digit numbers
function x($j,$k){
    global $i, $b, $c, $d;
    // 10-19
    if (substr($i, -2, 1)==='1'){return $c[$j[$k+1]];}
    // 20-99
    else{return $d[$j[$k]].' '.$b[$j[$k+1]];}
}

```

# Answer
> 1 votes
# Python 2.x - 378

Derivative of Fireflys answer, although by changing `P` to include million or trillions, etc.. it could recursively be used for any range of positive numbers. This also supports values up to 999,999

```
O=",one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir,,fif,,,eigh,,,,twen,thir,for,fif,,,eigh,".split(",")
P=",thousand".split(',')
def N(s,p=0):
 h,s=divmod(s,1000);x=N(h,p+1)if h>0 else" "
 if s<20:x+=O[s]or O[s-10]+["","teen"][s>12]
 elif s<100:x+=(O[s/10+20]or O[s/10])+"ty"+N(s%10)
 else:x+=N(s/100)+"hundred"+N(s%100)
 return x+" "+P[p]
print N(input())

```

Sample test (input is `<<<`, output is `>>>`):

```
<<< 1234
>>> one thousand two hundred thirty four

<<< 999999
>>>  nine hundred ninety nine   thousand nine hundred ninety nine

```

Although, if someone can explain this odd "buffer underflow" issue I have, that'd be swell...

```
<<< -1
>>>  nine hundred ninety nine

<<< -2
>>>  nine hundred ninety eight

```

# Answer
> 1 votes
# SmileBASIC, ~~365~~ Three Hundred Forty Seven bytes

```
DIM N$[22]D$="OneTwoThreeFourFiveSixSevenEightNineTenElevenTwelveThirFourFifSixSevenEighNineTwenFor
WHILE LEN(D$)INC I,D$[0]<"_
INC N$[I],SHIFT(D$)WEND
INPUT N
W=N MOD 100C%=N/100MOD 10M%=N/1E3T=W<20X=W/10>>0?(N$[M%]+" Thousand ")*!!M%+(N$[C%]+" Hundred ")*!!C%+(N$[X+10+(X==2)*8+(X==4)*7]+"ty "+N$[N MOD 10])*!T+N$[W*T]+"teen"*(T&&W>12)+"Zero"*!N

```

There's a trailing space if the last one or two digits are 0.

# Answer
> 1 votes
# Vyxal, 11 bytes

```
⌈≠[`NaN`|∆ċ

```

Try it Online!

Easy win when it's a built-in :p

# Answer
> 0 votes
# MOO \- ~~55~~ 83 bytes

```
x=$code_utils:toint(read(p=player));p:tell(x==E_TYPE?"NaN"|$string_utils:english_number(x))

```

Note: this code does not print any prompt to the standard output.

As a bonus, this code can handle any number withing the bounds of the moo language (`2147483647`-`-2147483648`).

# Answer
> 0 votes
# Wolfram Language ~~27~~ 40 bytes

Making use of the native function, `IntegerName`,

```
 Check[Input[]~IntegerName~"Words","NaN"]

```

The above prompts for user input. The present implementation returns "NaN" if the user enters anything other than an integer.

---

**Some examples (with pre-set inputs)**:

```
 Check[243~IntegerName~"Words","NaN"]

```

> two hundred forty-three

---

```
 Check[1234567890~IntegerName~"Words","NaN"]

```

> one billion, two hundred thirty-four million, five hundred sixty-seven thousand, eight hundred ninety

---

```
 Check["abc"~IntegerName~"Words","NaN"]

```

> NaN

# Answer
> 0 votes
# Python 2, 333 bytes

```
def f(n):S=str.split;D=S('z one two three four five six seven eight nine');K=' fif six seven eigh nine';k=n/1000;n,m=n/100%10,n%100;e,d=m/10,m%10;return' '.join([k and f(k),'thousand']*(k>0)+[D[n],'hundred']*(n>0)+([S('ten eleven twelve thir four'+K)[d]+'teen'*(d>2)]if 9<m<20else[S('twen thir for'+K)[e-2]+'ty']*(e>0)+[D[d]]*(d>0)))

```

Try it online!

This is good for 1 to 999,999, inclusive.

# Answer
> 0 votes
# Pyth, ~~239~~ 242 bytes

```
L:rjdb6"  +"dAm+cd;"nine"," one two three four five six seven eight""  twen thir for fif six seven eigh"|y_.ey+Wk.e?Y?thZjd,?hZ+@HhZ"ty"""@GeZ@+c"ten eleven twelve"d+R"teen"+c"thir four"d>H5eZ?hZ+@GhZ" hundred"""c.[03_b]1"thousand"c_jQT3"zero

```

Input is an integer in range \[0-999,999\]. Try it online here. Explanation pending.

Previous version, very similar operation, but doesn't support 0:

```
L:rjdb6"  +"dJc" one two three four five six seven eight nine"dKc"  twen thir for fif six seven eigh nine"dy_.ey+Wk.e?Y?thZjd,?hZ+@KhZ"ty"""@JeZ@+c"ten eleven twelve"d+R"teen"+c"thir four"d>K5eZ?hZ+@JhZ" hundred"""c.[03_b]1"thousand"c_jQT3

```

Explanation of previous version:

```
Implicit: Q=eval(input()), d=" "

Step 1: output formatting helper function
L:rjdb6"  +"d
L               Define a function, y(b):
   jdb          Join b on spaces
  r   6         Strip whitespace from beginning and end
 :              In the above, replace...
       "  +"    ... strings of more than one space...
            d   ... with a single space

Step 2: Define number lookup lists
Jc"..."dKc"..."d
  "..."            Lookup string
 c     d           Split the above on spaces
J                  Store in J - this is list of unit names
        Kc"..."d   As above, but storing in K - this is list of tens names, without "ty"

Step 3: Bringing it all together
y_.ey+Wk.e?Y?thZjd,?hZ+@KhZ"ty"""@JeZ@+c"ten eleven twelve"d+R"teen"+c"thir four"d>K5eZ?hZ+@JhZ" hundred"""c.[03_b]1"thousand"c_jQT3
                                                                                jQT    Get digits of Q
                                                                                _       Reverse
                                                                                c    3   Split into groups of 3
  .e                                                                                Map the above, element as b, index as k, using:
                                                                                _b                       Reverse the digits in the group
                                                                                .[03                         Pad the above on the left with 0 to length 3
                                                                                c      ]1                     Chop at index 1 - [1,2,3] => [[1],[2,3]]
        .e                                                                                Map the above, element as Z, index as Y, using:
          ?Y                                                                                If second element in the group (i.e. tens and units):
            ?thZ                                                                                If (tens - 1) is non-zero (i.e. 0 or >=2):
                   ?hZ                                                                                If tens is non-zero:
                       @KhZ                                                                                Lookup in tens names
                      +    "ty"                                                                                Append "ty"
                                                                                Else:
                               ""                                                                                Empty string
                  ,                                                                                Create two-element list of the above with...
                                 @JeZ                                                                                ... lookup units name
                jd                                                                                Join the above on a space - this covers [0-9] and [20-99]
                                                                                Else:
                                                                     c"thir four"d                                                             ["thir", "four"]
                                                                    +             >K5                                                          Append last 5 element of tens names ("fif" onwards)
                                                            +R"teen"                                                                           Append "teen" to each string in the above
                                      +c"ten eleven twelve"d                                                                                Prepend ["ten", "eleven", "twelve"]
                                     @                                               eZ                                                        Take string at index of units column - this covers [10-19]
                                                                                Else: (i.e. hundreds column)
                                                                                ?hZ                                                   If hundreds column is non-zero:
                                                                                @JhZ                                                Lookup units name
                                                                                +    " hundred"                                      Append " hundred"
                                                                                ""                                  Else: empty string
                                                                                Result of map is two element list of [hundreds name, tens and units name]
      Wk                                                                                If k is nonzero (i.e. dealing with thousands group)...
     +                                                                                "thousand"           ... Append "thousand"
    y                                                                                Apply output formatting (join on spaces, strip, deduplicate spaces)
                                                                                Result of map is [units group string, thousands group string]
 _                                                                                Reverse group ordering to put thousands back in front
y                                                                                Apply output formatting again, implicit print

```

---
Tags: code-golf
---


title: Selective Caesar Cipher

text:
# Question
Title: Selective Caesar Cipher
# Input

A string of text.

# Output

The string of text, however, every consonant is the next consonant in the alphabet, and every vowel is the next vowel in the alphabet (z becomes b, u becomes a). The case of the new letter should be the same as the letter it is replacing (a becomes e, A becomes E). If there are two consonants in a row, they will be separated by the characters 'ei', the case of 'ei' can be whatever you please. Characters outside of the 26 character Latin alphabet should remain unchanged. This includes whitespace and punctuation.

(For clarity, the vowels are aeiou. Y is not considered a vowel)

Examples: The phrase "Hello World" becomes "Jimeimu Xuseimeif" The phrase "codegolf" becomes "dufihumeig"

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

```
s=>s.replace(/[a-z]/gi,c=>(s+g(i=B(c)[0]-1)?"":"ei")+(h=j=>g(i)^g(j=-~j%26)?h(j):B([j+1|i&96]))(i&31),B=Buffer,g=i=>s=1065233>>i&1)

```

Try it online!

### Commented

```
s => s.replace(    // replace in the input string s ...
  /[a-z]/gi, c =>  //   ... each letter c (case insensitive)
  (                //
    s +            //   if the previous letter was a vowel (or this
                   //   is the 1st iteration and s is still a string)
    g(             //   or the current letter
      i =          //     whose ASCII code - 1 is loaded in i
      B(c)[0] - 1  //
    ) ?            //   is a vowel:
      ""           //     append nothing
    :              //   else:
      "ei"         //     append "ei"
  ) + (            //
    h = j =>       //   h is a recursive function looking for the
                   //   replacement letter
    g(i) ^         //     if the type of the current letter
    g(             //     does not match the type of
      j = -~j % 26 //       the next letter in the alphabet
                   //       obtained by incrementing j modulo 26
    ) ?            //     then:
      h(j)         //       keep advancing by doing a recursive call
    :              //     else:
      B([          //       output the letter
        j + 1 |    //         whose ASCII code is j + 1
        i & 96     //         with bits #5 and #6 taken from i
      ])           //
  )(i & 31),       //   initial call to h with j = i mod 32
  B = Buffer,      //   define B for Buffer
  g = i =>         //   g is a helper function taking an integer
    s = 1065233    //   representing an ASCII code minus 1,
        >> i & 1   //   returning 0 for consonant / 1 for vowel,
                   //   and also saving the result in s
)                  // end of replace()

```
> 5 votes

# Answer
# Vyxal, 27 bytes

```
k⁰kv":ɾJJƒ*‛ß+k⁰⇧1Ṁ$‡‛eijøṙ

```

Try it Online!

This is a bit of a mess.

```
k⁰kv"                       # Consonants and vowels, paired
     :ɾ                     # Duplicate and make an uppercase copy of each
       J                    # Concatenate to the original
        J                   # Concatenate to the input
         ƒ*                 # Reduce by ring translation, ring translating by each string
           ‛ß+              # "[bcdfghjklmnpqrstvwxyz]+"
                 1Ṁ         # Insert at position 1...
              k⁰⇧           # "BCDFGHJKLMNPQRSTVWXYZ"
                   $        # Put that under the value
                         øṙ # Regex replace that with...
                    ‡       # A function that...
                     ‛eij   # Joins by "ei"

```
> 5 votes

# Answer
# sed `-E`, 131 bytes

```
s/[A-Z]/@\l&/g
y/bcdfghjklmnpqrstvwxyzaeiou/cdfghjklmnpqrstvwxyzbeioua/
:a
s/@(.)/\u\1/
s/[b-df-hj-np-tv-z]{2}/!&/i
s/!(.)/\1ei/
ta

```

Attempt This Online!

This code expect that there won't be characters `@` and `!` input. Any two characters could be used instead of those, I think that even unprintable ones should work (at least using escape codes), but I chose to keep it as is to make it readable. Also this program could be made without this restriction, but it would be longer and less interesting.

**Explanation:**

```
s/[A-Z]/@\l&/g              # lowercase all characters and make note which characters were lowercased
                              # this have to be done because transliteration (following command) is case sensitive
                              # otherwise there would have to also be all uppercase characters
y/bcdfghjklmnpqrstvwxyzaeiou/cdfghjklmnpqrstvwxyzbeioua/ # change character to next one
:a                          # beginning of loop
s/@(.)/\u\1/                # uppercase back all characters where we made note
                              # it is inside of loop, to save 1B by not using g flag
s/[b-df-hj-np-tv-z]{2}/!&/i # make note where to place string ei
                              # this is done so that the long bracket expression doesn't need to be repeated twice
                              # also this command is the reason for loop as sed doesn't supported overlapping replacements
s/!(.)/\1ei/                # put ei after noted character
ta                          # repeat till there is nothing to replace

```
> 4 votes

# Answer
# Goruby `-p`, 99 bytes

```
c="aeiou"+b="bcdfghj-np-tv-z"
d="eioua"+b[1..]+?b
$_.t!c+c.up,d+d.up
gsub(/[#{b}]{2}/i){_1.t.j"ei"}

```

Attempt This Online!

# Ruby, 110 bytes

```
c="aeiou"+b="bcdfghj-np-tv-z"
d="eioua"+b[1..]+?b
$_.tr!c+c.upcase,d+d.upcase
gsub /#{"([#{b}])"*2}/i,'\1ei\2'

```

Attempt This Online!
> 4 votes

# Answer
# C (clang), ~~152~~ 149 bytes

-3 bytes thanks to ceilingcat!!

```
*i,c,u,p;z(s){i=wcschr(s,c-u);c=i?i[1]:c;}f(*s){for(p=0;c=*s++;p=i)u=c/91*32,z(L"AEIOUA"),z(L"BCDFGHJKLMNPQRSTVWXYZB"),printf("ei%c"+(!p|!i)*2,c+u);}

```

Try it online!
> 3 votes

# Answer
# Retina 0.8.2, 85 bytes

```
T`_o`A\EIOUA-DF-HJ-NP-TV-ZBaei\oua-df-hj-np-tv-zb
i`(?![_aeiou])\w\B(?![_aeiou])
$&ei

```

Try it online! Link includes test cases. Explanation:

```
T`_o`A\EIOUA-DF-HJ-NP-TV-ZBaei\oua-df-hj-np-tv-zb

```

Translate each letter in the string to the next letter in the string. `E` and `o` are special so have to be quoted in the replacement string (`o` in the source string refers to a copy of the replacement string) while `-` indicates a character range (also avoids having to quote `H` and `h`). `_` in the source string is just a filler to align the strings.

```
i`(?![_aeiou])\w\B(?![_aeiou])
$&ei

```

Case-insensitively find pairs of consecutive consonants and insert `ei` after the first.
> 3 votes

# Answer
# Python, 166 bytes

```
f=lambda s,v='UOIEA',c='BZYXWVTSRQPNMLKJHGFDC':s and[y:=(q:=[x:=(t:=s.upper())[0],[v,c][x in c]][x in v+c])[~-q.find(x)],y.lower()][y<s]+'ei'*({*t[:2]}<{*c})+f(s[1:])

```

Attempt This Online!
> 2 votes

# Answer
# 05AB1E, ~~28~~ 26 bytes

```
žNÃü2D€S„aeý:žNžM‚Du«vyDÀ‡

```

Try it online.

`ü2D€S` could alternatively be `SãDJs`: try it online.

**Explanation:**

```
žN             # Push the consonants constant
  Ã            # Only keep those characters from the (implicit) input-string
   ü2          # Pop and push its overlapping pairs as strings
     D         # Duplicate this list of string-pairs
      €S       # Convert each 2-letter string to a character-pair
        „aeý   # Join each pair with "ae" delimiter
            :  # Replace all pairs with the 4-letter strings in the (implicit) input
žN             # Push the consonants constant
  žM           # Push the vowels constant
    ‚          # Pair them together
     Du«       # Merge an uppercase copy of this pair
        vy     # Loop over all four strings:
          D    #  Duplicate the current string
           À   #  Rotate its copy once towards the left
            ‡  #  Transliterate the characters in the input-string
               # (after which the result is output implicitly)

   S           # Convert it to a list of characters
    ã          # Create all possible character-pairs with the cartesian power of 2
     D         # Duplicate this list of character-pairs
      J        # Join each inner character-pair to a 2-letter string
       s       # Swap so the character-pair list is at the top of the stack again

```
> 2 votes

# Answer
# Charcoal, 57 bytes

```
≔⪪aeiou¹θ≔⁻⪪β¹θη⊞υ⁰⭆Ｓ⁺×ei×⊟υΣ⊞Ｏυ№η↧ι⊟ＥΦ⟦ιθη↥θ↥η⟧№λι§λ⊕⌕λι

```

Try it online! Link is to verbose version of code. Explanation:

```
≔⪪aeiou¹θ

```

Get a list of the vowels in lowercase.

```
≔⁻⪪β¹θη

```

Subtract them from the lowercase alphabet to leave the consonants.s

```
⊞υ⁰

```

Start off with no previous consonant.

```
⭆Ｓ⁺

```

Map over each input character, joining together...

```
×ei×⊟υΣ⊞Ｏυ№η↧ι

```

... "ei" repeated the number of times the previous character was a consonant times the number of times the current character is a consonant, saving the result for the next iteration, ...

```
⊟ＥΦ⟦ιθη↥θ↥η⟧№λι§λ⊕⌕λι

```

... taking any of the uppercase consonants, uppercase vowels, lowercase consonants or lowercase vowels that contain the character, or as a last resort the original character, cyclically rotating the character in that list.
> 2 votes

---
Tags: code-golf, natural-language
---


title: Maximum distance to station

text:
# Question
Title: Maximum distance to station
Looking at the following hackerrank problem: https://www.hackerrank.com/challenges/flatland-space-stations

You are given a number n where cities can be at indices 0 to n-1 and also given an unsorted list of indices of cities where there are stations. The goal is to find the maximum distance from a city to a station. For example, for n=5 and the station list \[0,4\], the answer would be 2 since index 2 is 2 away from both 0 and 4 and all other stations at indices 0-4 are closer to one of 0 or 4.

---

I'm particularly interested in a short Python3 solution. The function body takes in the number n and a list c (like \[0,4\] in the example). After some revisions, I came up with the 69 character function body below:

```
c.sort();return max(t-s for s,t in zip([-c[0]]+c,c+[2*n-c[-1]-1]))//2

```

Curious about whether anyone can come up with a shorter body.

# Answer
> 1 votes
Distance solution:

# Python 3, 52 Bytes

```
return max(min(abs(l-c)for l in s)for c in range(n))

```

Try it online!

Index solution (added after my first two comments):

~~Python 3, 59 bytes
```
return max((min(abs(l-c)for l in s),c)for c in range(n))[1]

```
Try it online!<br>~~

Edit: Switched back to Distance solution, Thanks to Jonathan Allan for -1 Byte

# Answer
> 1 votes
# Charcoal, 9 bytes

```
Ｉ⌈Ｅθ⌊↔⁻ηι

```

Try it online! Link is to verbose version of code. Explanation:

```
   θ        First input
  Ｅ         Map over implicit range
        ι   Current value
       η    Second input
     ↔⁻     Absolute difference
    ⌊       Minimum
 ⌈          Maximum
Ｉ           Cast to string
            Implicitly print

```

# Answer
> 0 votes
# Perl 5, 51 bytes

```
sub{max(map{$i=$_-1;min(map abs$i-$_,@_)}1..shift)}

```

Try it online!

# Answer
> 0 votes
# , ~~56~~ 55 bytes

```
function(n,l)max(apply(abs(sapply(1:n-1,`-`,l)),2,min))

```

Try it online!

# Answer
> 0 votes
# MATL, 8 bytes

```
:q-|X<X>

```

Try it at MATL Online

**Explanation**

```
       % Implicitly grab the first input, N as an integer
:      % Create an array from 1...N
q      % Subtract one from each element to get a 0-based range: 0...N-1
-      % Implicitly grab the second input (a column vector) and subtract the
       % the two, broadcasting this out into a matrix of distances between
       % all cities and stations where each city is a column and the distance
       % to each station is on each row
|      % Take the absolute value of the result
X<     % Compute the minimum value of each column (e.g. distance of each
       % city to closest station)
X>     % Compute the maximum value of these distances (furthest city
       % from any station)
       % Implicitly display the result

```

# Answer
> 0 votes
# Jelly, 6 bytes

```
ḶạṂ¥€Ṁ

```

Try it online!

**5 bytes** if you allow indexing from 1:

```
ạṂ¥€Ṁ

```

## Explanation

```
ḶạṂ¥€Ṁ   Main dyadic link
Ḷ        [0..n-1]
    €    Map
   ¥     (
 ạ         Absolute difference [from each station position]
  Ṃ        Minimum
   ¥     )
     Ṁ   Maximum

```

# Answer
> 0 votes
# 05AB1E, ~~7~~ 6 bytes

```
FINαßM

```

Inputs in the order \\$n,s\\$

Try it online or verify some more test cases.

**Explanation:**

```
F       # Loop `N` in the range [0, (implicit) input `n`):
 I      #  Push input-list `s`
  Nα    #  Get the absolute difference of each value in `s` with `N`
    ß   #  Pop and leave the minimum of the list
     M  #  Push a copy of the largest number on the stack to the top of the stack
        # (after the loop, the top of the stack is output implicitly as result)

```

# Answer
> 0 votes
# MathGolf, 12 bytes

```
ê├ô_ï-±╓\;]╙

```

Try it online.

Or alternatively:

```
rhêa*m-±mÄ╓╙

```

Try it online.

**Explanation:**

```
ê         # Push all inputs as list (`n` and `s` are merged as single list)
 ├        # Extract the first item: pop and have list `s` and integer `n` separated on
          # the stack
  ô       # Loop `n` amount of times, using 6 characters as inner code-block:
   _      #  Duplicate list `s`
    ï     #  Push the 0-based loop index
     -    #  Subtract it from each value in list `s`
      ±   #  Take the absolute value of each
       ╓  #  Pop and push the minimum
        \ #  Swap so list `s` is at the top again for the next iteration
   ;      # Discard the remaining `s` after the loop
    ]     # Wrap all minima on the stack into a list
     ╙    # Pop and push the maximum
          # (after which the entire stack is output implicitly as result)

```

```
r         # Push a list in the range [0, (implicit) input `n`)
 h        # Get its length (without popping): `n`
  ê       # Push input-list `s`
   a      # Wrap the list into a list
    *     # Multiply it to the length, so we have a list of `n` amount of lists `s`
     m-   # Subtract the values in the two lists from one-another
          # (which required the lists to be of equal length)
       ±  # Take the absolute value of each
m         # Map over each inner list,
 Ä        # using 1 character as inner code-block:
  ╓       #  Pop and push the minimum
   ╙      # Pop and push the maximum
          # (after which the entire stack is output implicitly as result)

```

# Answer
> 0 votes
# Japt `-h`, 10 bytes

```
ÆVËaXÃÍÎÃÍ

```

Try it

---
Tags: code-golf
---


title: Reduced Row-Echelon Form of a Matrix

text:
# Question
Title: Reduced Row-Echelon Form of a Matrix
The goal of this challenge is to create a program that takes in a matrix and outputs its reduced row-echelon form.

> A matrix is in reduced row-echelon form if it meets all of the following conditions:
>
> 1. If there is a row where every entry is zero, then this row lies below any other row that contains a nonzero entry.
> 2. The leftmost nonzero entry of a row is equal to `1`.
> 3. The leftmost nonzero entry of a row is the only nonzero entry in its column.
> 4. Consider any two different leftmost nonzero entries, one located in row i, column j and the other located in row s, column t. If `s>i`, then `t>j`.
>
> Source

The general process to transform the matrix is:

1. Deal with each row i from 1 to n in turn, and work across the columns j from 1 to m skipping any column of all zero entries.
2. Find the next column j with a nonzero entry.
3. Interchange rows, if necessary, so that the pivot element A(i,j) is nonzero.
4. Make the pivot equal to 1 by dividing each element in the pivot row by the value of the pivot.
5. Make all elements above and below the pivot equal to 0 by subtracting a suitable multiple of the pivot row from each other row.
6. Repeat for all rows.

If you want to read more on this type of matrix, view the Wikipedia article on it and a tool and article(steps above) that shows the steps to transform the matrix.

**As for the actual challenge, here it goes:**

The input can be given in any way you wish through STDIN or equivalent, just please explain it in your answer. The output will be the reduced row-echelon form of the input in the same form as the input through STDOUT or equivalent. Standard loopholes are not allowed and external libraries or functions that do this task are also not allowed (`TI-BASIC`'s `rref(` command, for example). You may write a full program or function. This is code golf, lowest BYTES wins. Good luck!

Example Input: `[[2,1,1,14][-1,-3,2,-2][4,-6,3,-5]]`

Example Output: `[[1,0,0,1][0,1,0,5][0,0,1,7]]`

# Answer
> 2 votes
# R, 232 bytes

```
function(M){p=1;R=nrow(M);C=ncol(M);for(r in 1:R){if(C<=p)break;i=r;while(M[i,p]==0){i=i+1;if(R==i){i=r;p=p+1;if(C==p)return(M)}};t=M[i,];M[i,]=M[r,];M[r,]=t;M[r,]=M[r,]/M[r,p];for(i in 1:R)if(i!=r)M[i,]=M[i,]-M[r,]*M[i,p];p=p+1};M}

```

This is just an implementation of the usual Gaussian elimination algorithm.

Ungolfed:

```
rref <- function(M) {
    p <- 1
    R <- nrow(M)
    C <- ncol(M)
    for (r in 1:R) {
        if (C <= p)
            break
        i <- r
        while (M[i, p] == 0) {
            i <- i + 1
            if (R == i) {
                i <- r
                p <- p + 1
                if (C == p)
                    return(M)
            }
        }
        t <- M[i, ]
        M[i, ] <- M[r, ]
        M[r, ] <- t
        M[r, ] <- M[r, ] / M[r, p]
        for (i in 1:R)
            if (i != r)
                M[i, ] <- M[i, ] - M[r, ] * M[i, p]
        p <- p + 1
    }
    M
}

```

# Answer
> 3 votes
# Vyxal, ~~29~~ 23 bytes

```
(ƛh/;ḣ„D"„-‟wJƛǓ:h±*]ƛǓ

```

it's so complex that I forget how it works, but it does work I guess...?

29 bytes by me

24 bytes by @emanresu A

23 bytes(current) by great god @lyxal

Try it Online!

---
Tags: code-golf, math, matrix, linear-algebra
---