title: Reverse Bit Order of 32-bit Integers

text:
# Question
Title: Reverse Bit Order of 32-bit Integers
Write the shortest code to reverse the bit order of a 32-bit integer.

**Rules:**

1. Input is assumed to be a valid integer or string equivalent if your language doesn't support numerical values (e.g. Windows Batch).
2. Output must be a valid integer or string equivalent if your language doesn't support numerical values (e.g. Windows Batch).
3. Standard library only.
4. It may be a function or a complete program.
5. Input may be either from `stdin` or as a function argument.
6. Output must be either `stdout` or as a returned value.
7. If your language has a built-in or standard library function that does this in one step (e.g. `rbit` in ARM assembly), that cannot be used.

**Examples:**

Key:

1. decimal
    * binary
    * (reverse)
    * reversed binary
    * decimal output

Examples:

1. `-90` (8-bit example for demonstration)

* `10100110b`
    * (reverse)
    * `01100101b`
    * `101`
2. `486`

* `00000000000000000000000111100110b`
    * (reverse)
    * `01100111100000000000000000000000b`
    * `1736441856`
3. `-984802906`

* `11000101010011010001100110100110b`
    * (reverse)
    * `01100101100110001011001010100011b`
    * `1704506019`

Note: Omissions are free game. If I didn't say it, and it's not one of the standard loopholes, then it's completely allowed.

# Answer
> 1 votes
x86 assembly, 9 bytes

```
    xor eax, eax
    inc eax
myloop:
    shr ecx, 1
    adc eax, eax
    jnc short myloop

```

In byte form: `33 C0 40 D1 E9 13 C0 73 FA`, 9 bytes.

# Answer
> 26 votes
## MMIX assembly (28 Bytes)

### 64 bit numbers

```
rbit:
    SETH $1,#0102 # load matrix in 16-byte steps
    ORMH $1,#0408
    ORML $1,#1020
    ORL  $1,#4080
    MOR  $0,$1,$0 # multiplication 1
    MOR  $0,$0,$1 # multiplication 2
    POP  1,0      # return

```

This assembles to:

```
rbit:
    E0010102 # SETH $1,#0102
    E9010408 # ORMH $1,#0408
    EA011020 # ORML $1,#1020
    EB014080 # ORL  $1,#4080
    DC000100 # MOR  $0,$1,$0
    DC000001 # MOR  $0,$0,$1
    F8010000 # POP  1,0

```

### How does it work?

The `MOR` instruction performs a matrix multiplication on two 64-bit quantities used as two 8x8 matrices of booleans. A boolean number with digits *abcdefghklmnopqr2* is used as a matrix like this:

```
/ abcd \
| efgh |
| klmn |
\ opqr /

```

The `MOR` instruction multiplies the matrices represented by their arguments where multiplication is `and` and addition is `or`. It is:

```
/ 0001 \      / abcd \      / opqr \
| 0010 |  \/  | efgh |  --  | klmn |
| 0100 |  /\  | klmn |  --  | efgh |
\ 1000 /      \ opqr /      \ abcd /

```

and furthermore:

```
/ opqr \      / 0001 \      / rqpo \
| klmn |  \/  | 0010 |  --  | nmlk |
| efgh |  /\  | 0100 |  --  | hgfe |
\ abcd /      \ 1000 /      \ dcba /

```

which is the reverse order of bits of the original number.

### 32 bit numbers

If you just want the reverse of a 32 bit number instead of a 64 bit number, you can use this modified method:

```
rbit:
    SETL   $1,#0408 # load first matrix in two steps
    ORML   $1,#0102
    MOR    $1,$1,$0 # apply first matrix
    SLU    $2,$1,32 # compile second matrix
    16ADDU $1,$2,$1
    MOR    $1,$0,$1 # apply second matrix
    POP    1,0      # return

```

assembled:

```
rbit:
    E3010408 # SETL   $1,#0408
    EA010102 # ORML   $1,#0102
    DC010001 # MOR    $1,$1,$0
    3B020120 # SLU    $2,$1,32
    2E010201 # 16ADDU $1,$2,$1
    DC010001 # MOR    $1,$0,$1
    F8010000 # POP    1,0

```

The first matrix multiplication basically works like this:

```
/ 0000 \      / 0000 \      / 0000 \
| 0000 |  \/  | 0000 |  --  | 0000 |
| 0001 |  /\  | abcd |  --  | efgh |
\ 0010 /      \ efgh /      \ abcd /

```

the corresponding octabyte is `#0000000001020408` which we load in the first two instructions. The second multiplication looks like this:

```
/ 0000 \      / 0001 \      / 0000 \
| 0000 |  \/  | 0010 |  --  | 0000 |
| efgh |  /\  | 0100 |  --  | hgfe |
\ abcd /      \ 1000 /      \ dcba /

```

The corresponding octabyte is `#0102040810204080` which we create from the first matrix like this:

```
SLU $2,$1,#32   # $2 = #0102040800000000
16ADDU $1,$2,$1 # $2 = $2 + $1 << 4
                     = $2 + #0000000010204080
                #    = #0102040810204080

```

The second multiplication is business as usual, the resulting code has the same length (28 bytes).

# Answer
> 17 votes
## 80386 assembly (~~13~~ 12 bytes)

As a function in AT&T syntax using the cdecl calling convention.

```
    # reverse bits of a 32 bit word
    .text
    .globl rbit
    .type rbit,@function
rbit:
    push $32       # prepare loop counter
    pop %ecx
0:  shrl 4(%esp)   # shift lsb of argument into carry flag
    adc  %eax,%eax # shift carry flag into lsb
    loop 0b        # decrement %ecx and jump until ecx = 0
    ret            # return

```

This function assembles to the following byte sequence:

```
6a 20 59 d1 6c 24 04 11 c0 e2 f8 c3

```

Broken down into instructions:

```
6a 20       push $32
59          pop %ecx
d1 6c 24 04 shrl 0x4(%esp)
11 c0       adc  %eax,%eax
e2 f8       loop .-6
c3          ret

```

It works like this: In each of the 32 iterations of the loop, the argument, which is located at `4(%esp)`, is right shifted by one position. The last bit is implicitly shifted into the carry flag. The `adc` instruction adds two values and adds the value of the carry flag to the result. If you add a value to itself, i.e. `%eax`, you effectively left-shift it by one position. This makes `adc %eax,%eax` a convenient way to left shift `%eax` by one position while shifting the content of the carry flag into the low-order bit.

I repeat this process 32 times so that the entire content of `4(%esp)` is dumped into `%eax`. I never explicitly initialize `%eax` as its previous contents are shifted out during the loop.

# Answer
> 7 votes
## C,  ~~63~~   ~~52~~  48

**Original version:**

```
int r(int n){int r=0,i=32;for(;i--;r=r<<1|n&1,n>>=1);return r;}

```

---

**Updated version** (with changes suggeted by *Allbeert*, *es1024*, and *Dennis*):

```
r(n){int r,i=32;for(;i--;r=r*2|n&1,n>>=1);return r;}

```

Note: Since the second version omits setting `r=0`, the code is assuming that an `int` is 32 bits. If this assumption is false, the function will most likely produce an incorrect result, depending on the initial state of `r` on entry to the function.

---

**Final version** (with further changes suggested by *Dennis* and *Alchymist*):

```
r(n,r,i){for(;32-i++;r=r*2|n&1,n>>=1);return r;}

```

Note: This puts the declaration of the work variables `r` and `i` into the parameter list. Parameters are as follows: `n` is the number to be bit-reversed. `r` and `i` are work variables that must be passed as 0.

# Answer
> 7 votes
## x86 assemply, 10 Bytes

```
   f9                      stc
   d1 d8            1:     rcr    %eax
   74 05                   je     2f
   d1 d2                   rcl    %edx
   f8                      clc
   eb f7                   jmp    1b
                    2:

```

This assume input in eax, output in edx. (Also, on output eax is zero and CF and ZF are set, if anyone cares).

Instead of a counter, an additional 1 is pushed in in the beginning as end-of data marker

# Answer
> 5 votes
## Julia 0.2, 33 bytes

```
f(n)=parseint(reverse(bits(n)),2)

```

Does what it looks like.

`bits` gives you the bit representation (respecting two's complement). `parseint` doesn't care about two's complement, but returns a 32 bit integer, so the two's complement is simply handled by overflow.

According to the changelogs, overflow detection was added to `parseint` in Julia 0.3, so this might not work any more.

# Answer
> 4 votes
# JavaScript (E6) 37 ~~39 40 50~~

Function, number input and returning reversed number. ~~Most basic algorithm, probably can be golfed more with some smart trick.~~

**Edit** Recursion instead of loop

**Edit 2** Following @bebe suggestion `k*2` instead of `k<<1`

**Edit 3** Something I had missed at all: it's a full 32 bit loop, no need to initialize k. Thanks @FUZxxl

```
R=(v,b=32,k)=>b?R(v>>1,b-1,k*2|v&1):k

```

*It was*

```
R=v=>{for(k=b=0;b++<32;)k+=k+(v&1),v>>=1;return k}

```

**Test** In FireFox console, test using numbers in OP and some more random 16 and 32 bit numbers

```
Bin=x=>('0'.repeat(32)+(x<0?-x-1:x).toString(2)).slice(-32).replace(/./g,d=>x>0?d:1-d),
Dec=x=>(' '.repeat(11)+x).slice(-11),
R16=_=>Math.random()*65536|0,
R32=_=>(Math.random()*65536<<16)|R16(),
[-90,486,-984802906,R16(),R16(),R16(),R32(),R32(),R32(),R32()]
 .forEach(n=> console.log(Dec(n)+' '+Bin(n)+' '+Dec(R(n))+' '+Bin(R(n))))

```

**Example of test output**

```
        -90 11111111111111111111111110100110  1711276031 01100101111111111111111111111111
        486 00000000000000000000000111100110  1736441856 01100111100000000000000000000000
 -984802906 11000101010011010001100110100110  1704506019 01100101100110001011001010100011
      45877 00000000000000001011001100110101 -1395851264 10101100110011010000000000000000
      39710 00000000000000001001101100011110  2027487232 01111000110110010000000000000000
      56875 00000000000000001101111000101011  -730136576 11010100011110110000000000000000
-1617287331 10011111100110100010011101011101 -1159439879 10111010111001000101100111111001
-1046352169 11000001101000011110111011010111  -344488573 11101011011101111000010110000011
 1405005770 01010011101111101010111111001010  1408597450 01010011111101010111110111001010
  -35860252 11111101110111001101000011100100   655047615 00100111000010110011101110111111

```

# Answer
> 4 votes
# Python 2, 50

```
print int("{:032b}".format(input()%2**32)[::-1],2)

```

Broadly the same as my Pyth solution. Take the input mod 2\**32, convert to 32-bit padded binary, reverse, convert binary sting back to decimal and print.

# Answer
> 4 votes
# CJam, 15 bytes

```
li4H#+2bW%32<2b

```

Try it online.

"Free game" joker used: The output will always be an *unsigned* integer.

### Test cases

```
$ cjam reverse32.cjam <<< 486; echo
1736441856
$ cjam reverse32.cjam <<< -984802906; echo
1704506019

```

### How it works

```
li   " Read from STDIN and cast to integer. ";
4H#+ " Add 4 ** 17 to avoid special cases. ";
2b   " Convert into array of digits in base 2. ";
W%   " Reverse the order. ";
32<  " Discard the 33th and all following digits. ";
2b   " Convert the array of digits into an integer. ";

```

# Answer
> 4 votes
# Dyalog APL, 10 bytes

```
2⊥⌽⎕⊤⍨32/2

```

`2⊥` from-base-2 of

the reversed

numeric input

`⊤⍨` in the number system consisting of

`32/2` 32 bits

TryAPL online!

# Answer
> 3 votes
# J (~~17~~ ~~15~~ 13 bytes)

```
_32#.@|.@{.#:

```

Here is an explicit definition to explain what it does:

```
3 : '#. |. _32 {. #: y'

```
1. `#: y` represents `y` as a base 2 number using as many places as necessary.
2. `x {. y` takes `|x` (magnitude of `x`) items from `y`, from the front if `x` is positive, from the back if `x` is negative. If we take more items than present, the result is padded with zeroes. `_32 {. #: y` effectively pads `#: y` to 32 bits.
3. `|. y` flips `y`, i. reverses the order of items in `y`.
4. `#. y` interprets `y` as a base-2 number.

# Answer
> 2 votes
## Python - 89

```
def r(n):
 if n<0:n=~n^0xFFFFFFFF
 print int(['','-'][n%2]+'{:032b}'.format(n)[::-1],2)

```

Python represents negative binary numbers as simply `-0b{positive_number}`. So to deal with this, complement negative numbers and then XOR with all 1's.

After that, create the string representation of the integer based on the format `{:032b}` which provides the 32bit representation of the number. Finally, reverse the string and turn it back into an integer.

**EDIT**

Thanks to @Martin Büttner for pointing out a two's complement issue. If `n` ends in a 1 then by two's complement the reversed version would be negative.

Luckily, as explained above, Python likes negative binary numbers in a pretty simple way. Also luckily, Python's `int` function allows optional sign characters in its first argument.

So now, add a minus sign if `n` is odd to satisfy two's complement.

# Answer
> 2 votes
## Java function, 64 chars.

```
 int r(int n){int r=0,i=32;for(;i-->0;n>>=1)r=r<<1|n&1;return r;}

```

Should also work in C.

# Answer
> 2 votes
# Pyth, 33 32 22

```
v_%"%032db0"vsc%Q^2 32

```

Explanation:

```
                 Q             Evaluated input.
                %Q^2 32        Q mod 2^32. Same 32 bit binary representation as Q.
             vsc%Q^2 32        Convert to binary string, then that to decimal int.
   %"%032db0"vsc%Q^2 32        Pad above number to 32 bits, and append b0.
  _%"%032db0"vsc%Q^2 32        Reverse it.
 v_%"%032db0"vsc%Q^2 32        Eval and print. Due to leading "0b", eval as binary.

```

Golfs:

33 -\> 32: Moved add to before reversing to save an end-quote.

32 -\> 22: Used Q mod 2^32 instead of complicated machinery. Combined both strings into one.

Test cases:

```
$ cat rev_bits
v_%"%032db0"vsc%Q^2 32

$ ./pyth.py rev_bits <<< -984802906
1704506019

$ ./pyth.py rev_bits <<< 486
1736441856

$ ./pyth.py rev_bits <<< 0
0

```

# Answer
> 2 votes
# GNU dc, 27 bytes

```
0?[2~rssr2*+dlsz34>m]dsmx+p

```

### Output:

```
$ dc revbits.dc <<< 15
4026531840
$ dc revbits.dc <<< 255
4278190080
$ dc revbits.dc <<< 65535
4294901760
$ dc revbits.dc <<< 4294901760
65535
$ dc revbits.dc <<< 4278190080
255
$ dc revbits.dc <<< 4026531840
15
$

```

---

# Bash+coreutils, 45 bytes

```
n=`dc -e2do32^n$1p`
dc -e2i`rev<<<${n: -32}`p

```

### Output:

```
$ ./revbits.sh 15
4026531840
$ ./revbits.sh 255
4278190080
$ ./revbits.sh 65535
4294901760
$ ./revbits.sh 4294901760
65535
$ ./revbits.sh 4278190080
255
$ ./revbits.sh 4026531840
15
$

```

---

# C function, 89 bytes

Same idea as https://codegolf.stackexchange.com/a/36289/11259 \- using the Stanford bit twiddling hacks. Not going to win the golfing, but interesting nonetheless:

```
// 89 byte function:
i;r(v){for(i=1;i<32;i*=2)v=v>>i&(1L<<32)/((1<<i)+1)|(v&(1L<<32)/((1<<i)+1))<<i;return v;}

// Test program:
#include <stdio.h>

int main (int argc, char **argv)
{
    printf("r(0x0000000f) = 0x%08x\n", r(0x0000000f));
    printf("r(0x000000ff) = 0x%08x\n", r(0x000000ff));
    printf("r(0x0000ffff) = 0x%08x\n", r(0x0000ffff));
    printf("r(0xffffffff) = 0x%08x\n", r(0xffffffff));
    printf("r(0x0f0f0f0f) = 0x%08x\n", r(0x0f0f0f0f));
    printf("r(0xf0f0f0f0) = 0x%08x\n", r(0xf0f0f0f0));
}

```

### Output:

```
$ ./revbits
r(0x0000000f) = 0xf0000000
r(0x000000ff) = 0xff000000
r(0x0000ffff) = 0xffff0000
r(0xffffffff) = 0xffffffff
r(0x0f0f0f0f) = 0xf0f0f0f0
r(0xf0f0f0f0) = 0x0f0f0f0f
$

```

# Answer
> 2 votes
# PHP, 46 Bytes

Online Versions

```
for(;$i<32;)$t.=$argn>>$i++&1;echo bindec($t);

```

or

```
<?=bindec(strrev(sprintf("%064b",$argn<<32)));

```

# Answer
> 1 votes
# C# ~~81~~ 74

```
int R(int V){int l,r=l=0,i=1;for(;i>0;i*=2)r|=i*(1&V>>(31-l++));return r;}

```

Bit operations which most likely can be done shorter in all programming languages.

Basically, loop through all powers of 2 up to integer maximum+1(Which turns into a power of two) and since (2,147,483,647+1)=0 I can loop to 0. Bit shift Left to right to move the bit into the first position. Last bit at place 32 goes 31 steps to the right, second last goes 30 etc. So by using AND operator with 1 i will know if it is 1 or 0. If it is 1 I will add the current i value to the result and return it.

```
int R(int V)
{
    int l,r=l=0,i=1;
    for(;i>0;i*=2)
        r|=i*(1&(V>>(31-l++)));
    return r;
 }

```

# Answer
> 1 votes
# JS 115

Well that doesn't look good at all :D

```
n=+prompt();alert(eval('0b'+(Array(33).join(0)+(n<0?n>>>0:n).toString(2)).slice(-32).split('').reverse().join('')))

```

@Florian F's method in JS is 53 bytes long:

```
for(n=+prompt(r=0),i=32;i--;n>>=1)r=r<<1|n&1;alert(r)

```

# Answer
> 1 votes
## C# 142

```
using System;using System.Linq;int f(int n){return Convert.ToInt32(new string(Convert.ToString(n,2).PadLeft(32,'0').Reverse().ToArray()),2);}

```

Expanded

```
int f(int n)
{
    return Convert.ToInt32(
        new string(
            Convert.ToString(n, 2)
            .PadLeft(32, '0')
            .Reverse()
            .ToArray()), 2);
}

```

# Answer
> 1 votes
# Python - 37

Similar to @isaacg's solution.

```
f=lambda n:int(bin(n%2**32)[:1:-1],2)

```

# Answer
> 1 votes
# C++, 160

This isn't the shortest one, however it uses only 24 operations.
Taken from Hacker's Delight book.

Golfed:

```
typedef unsigned U;U R(U&x){U a=-1u/3,b=-1u/5,c=-1u/17,d=65280;x=(x&a)*2|(x/2)&a;x=(x&b)*4|(x/4)&b;x=(x&c)<<4|(x>>4)&c;x=(x<<24)|((x&d)<<8)|((x>>8)&d)|(x>>24);}

```

Ungolfed:

```
unsigned R(unsigned x) {
    x = (x & 0x55555555) <<  1 | (x >>  1) & 0x55555555;
    x = (x & 0x33333333) <<  2 | (x >>  2) & 0x33333333;
    x = (x & 0x0F0F0F0F) <<  4 | (x >>  4) & 0x0F0F0F0F;
    x = (x << 24) | ((x & 0xFF00) << 8) | ((x >> 8) & 0xFF00) | (x >> 24);
    return x;
}

```

# Answer
> 1 votes
# Haskell, 145 - no bitwise operations

Bit-twiddling strikes me as the antithesis of Haskell, so I've avoided any use of bitwise operators. The resulting program is certainly not the shortest contestant, but I thought the use of math instead of bit-twiddling was interesting at least.

```
import Data.Tuple
import Data.List
f m=foldl1((+).(*2))$take 32$(unfoldr(\n->if n==0 then Nothing else Just$swap$divMod n 2)$mod m$2^32)++[0,0..]

```

### Explanation

```
f m=foldl1((+).(*2))$take 32$(unfoldr(\n->if n==0 then Nothing else Just$swap$divMod n 2)$mod m$2^32)++[0,0..]
    |------5-------|---4----|--------------------------2---------------------------------|----1-----|---3----|

```
1. uses modulo to bring the result into 32-bit range
2. constructs a list of `0`s and `1`s, least significant bit first by repeatedly dividing by 2 and taking the remainder
3. concatenates an infinite list of `0`s to the end of this list
4. grabs the first 32 elements of the list (These last two were needed to ensure the list is actually 32 bits long.)
5. converts a list of `0` and `1` into an integer assuming the *most* significant bit is first (repeated double and add).

I'm not quite sure what constitutes "the standard library" in Haskell so I assumed Data.Tuple and Data.List were OK (they are pretty standard).

Also, the output is an *unsigned* 32-bit integer since changing that would cost me bytes: I'm arguing this under "omissions are free game".

# Answer
> 1 votes
# PHP, ~~46~~ 41 bytes

try them online

```
while($i<32)$r=$r*2|$argn>>$i++&1;echo$r;

```

bitwise ... more or less. Run as pipe with `php -nR '<code>'`.

**PHP, 46 bytes**

```
while($i<32)$r|=($argn>>$i&1)<<31-$i++;echo$r;

```

a pure bitwise solution; run as pipe with `-nR`.

**PHP, ~~47~~ 59 bytes**

```
<?=bindec(str_pad(strrev(substr(decbin($argn),-32)),32,0));

```

another built-in approach; save to file and run as pipe with `-F`.

# Answer
> 1 votes
# ARM Thumb machine code, 10 bytes

```
00000000: 01 20 49 08 40 41 fc d3 70 47            . I.@A..pG

```

As per request, this does not use the `rbit` instruction.

```
    .syntax unified
    .arch armv7-a
    .thumb
    .globl rbit
    .thumb_func
    // input: r1
    // output: r0
rbit:
    // sentinel bit
    movs    r0, #1
.Lloop:
    // shift the lowest bit into the carry flag
    lsrs    r1, #1
    // shift in with adc, put highest bit in carry flag
    adcs    r0, r0
    // when the carry is set we flipped all 32 bits
    bcc     .Lloop
    // return
    bx      lr

```

---

# ARM Thumb machine code (with builtins), 6 bytes

```
00000000: 90 fa a0 f0 70 47                   ....pG

```

This is literally the `rbit` instruction that was explicitly disallowed but I am providing for reference

```
    .syntax unified
    .arch armv7-a
    .thumb
    .globl rbit_cheater
    .thumb_func
    // input: r0
    // output: r0
rbit_cheater:
    // Trivialize the challenge.
    rbit   r0, r0
    // Return
    bx     lr

```

# Answer
> 0 votes
## Perl - 60

```
$_=unpack"N",pack"B*",scalar reverse unpack"B32",pack"N",$_

```

+1 for the p flag (let me know if I'm counting this wrong).

Run with:

```
echo 486 | perl -pe'$_=unpack"N",pack"B32",scalar reverse unpack"B32",pack"N",$_'

```

# Answer
> 0 votes
## C++ 69

```
int r(int n){int e=0,i=0;for(;i<32;i++)e|=((n>>i)&1)<<31-i;return e;}

```

# Answer
> 0 votes
## R, 45

```
f=function(x)packBits(intToBits(x)[32:1],"i")

```

Examples:

```
f(486)
# [1] 1736441856
f(-984802906)
# [1] 1704506019

```

Always just shy of the Python answers. That damn function keyword.

# Answer
> 0 votes
# Ruby, ~~43~~ 41 bytes

`def r(n)(0..31).inject(0){|a,b|a*2+n[b]}end`

In Ruby, using the bracket index notation (foo\[i\]) returns the bit at the nth place.

### --Edit--

Refactoring the `inject` functionality shaves a couple bytes

`def r(n)z=0;32.times{|i|z=z*2+n[i]};z;end`

# Answer
> 0 votes
# Perl5: 46

```
sub r{for(0..31){$a=$a*2|$_[0]&1;$_[0]>>=1}$a}

```

Nothing fancy. It shifts output left, copy lsb before shifting source right.

# Answer
> 0 votes
## Clojure, ~~202~~ ~~156~~ 142

```
#(read-string (let [s (clojure.pprint/cl-format nil "~2r" %)](apply str (reverse (apply str (concat (repeat (- 32 (count s)) "0") s "r2"))))))

```

# Answer
> 0 votes
# Perl (37+1)

basically a port of the C solution by Todd Lehman

`perl -E '$t=<>;map$r=2*$r|1&$t>>$_,0..31;say$r'`

# Answer
> 0 votes
## JavaScript (ES6), 32 bytes

```
(n,m=32)=>(--m&&f(n,m)*2)|n>>m&1

```

Wrote this while trying to solve Bit-Reversal Permutations \- it didn't help there, but it works fine here!

# Answer
> 0 votes
# PASM (P8X32A assembly language), 4 bytes, 1 instruction

```
REV $1ef, #0

```

### Assembles to:

```
00 DE FF 3C

```

### Explanation:

Reverses the low 32-0 bits (e.g. all of them) in place in location 0x1ef.

Quite why this instruction exists is a mystery to me. Probably to make life extremely awkward for emulator authors. :)

# Answer
> 0 votes
# C, ~~40~~ 38 bytes

using a recursive function and multiplication by 1u to cast from int to unsigned

```
R(I){return I?I<<31|R(I*1u/2)*1u/2:0;}

```

edit: replaced right shift with division by 2

Try it online!

# Answer
> 0 votes
# 05AB1E, 9 bytes

```
b32jð0:RC

```

Try it online!

Uses unsigned integers.

```
b   convert input to binary
32j pad to length 32
ð0: replace spaces by zeroes
R   reverse
C   convert to decimal

```

I don't know if that counts as "omissions", but if input and output are allowed in binary, then the one-byter `R` will do the work.

# Answer
> 0 votes
# Factor, 33 bytes

```
[ 32 <bits> reverse bits>number ]

```

Try it online!

## Explanation:

* `32 <bits>` represent an integer as a virtual sequence of 32 bits (booleans)
* `reverse` reverse the sequence
* `bits>number` convert a sequence of booleans to an integer

---
Tags: code-golf, bitwise
---


title: This challenge uses the '+' character

text:
# Question
Title: This challenge uses the '+' character
Your task: given a number `n`, generate a '+' sign that is `n` characters away from its center. If this is confusing, check out the test cases.

Standard methods of input: output must be a string or printed. Standard loopholes apply.

```
Input: 1
Output: +           ] 1 away from center `+`.

Input: 2
Output:  +          ] 2 away from center `+`.
        +++         ] 1 away from center `+`.
         +

Input: 3
Output:   +         ] 3 away from center `+`.
          +
        +++++
          +
          +

```

This is , so shortest code wins!

# Answer
> 47 votes
# Charcoal, 5 bytes

```
Ｐ+×+Ｎ

```

Try it online!

# Answer
> 29 votes
# Python 2, 53 bytes

```
n=2*input()-1;C='+'.center
for c in C(n):print C(n,c)

```

Try it online!

# Answer
> 14 votes
# JavaScript (ES6), ~~67~~ ~~65~~ ~~63~~ ~~60~~ 59 bytes

```
x=>(v=(` `[r=`repeat`](--x)+`+
`)[r](x))+`+`[r](x*2)+`+
`+v;

```
* 2 bytes saved by replacing two occurrences of `x-1`, the first with `--x` and the second with `x`.
* 2 bytes saved thanks to Kritixi Lithos, replacing `"\n"` with ``[newline]``.
* 3 bytes saved thanks to user2428118, finally helping me to figure out a way to alias the `repeat` in a way that reduced the size. (With honourable mention to Marie for her efforts, too)
* 1 byte saved indirectly thanks to Herman.

---

## Try It

```
f=
x=>(v=(` `[r=`repeat`](--x)+`+
`)[r](x))+`+`[r](x*2)+`+
`+v;
oninput=_=>o.innerText=f(+i.value)
o.innerText=f(i.value=3)
```

```
<input id=i min=1 type=number><pre id=o>
```

# Answer
> 12 votes
# MATL, 11 bytes

```
tZv=&+g43*c

```

Try it online!

### Explanation with example

Consider `n = 3`.

```
t     % Implicitly input n. Duplicate
      % STACK: 3, 3
Zv    % Symmetric range
      % STACK: 3, [1 2 3 2 1]
=     % Equal, element-wise
      % STACK: [0 0 1 0 0]
&+    % All pair-wise additions. Gives a 2D array
      % STACK: [0 0 1 0 0;
                0 0 1 0 0;
                1 1 2 1 1;
                0 0 1 0 0;
                0 0 1 0 0]
g     % Logical: convert non-zero to one
      % STACK: [0 0 1 0 0;
                0 0 1 0 0;
                1 1 1 1 1;
                0 0 1 0 0;
                0 0 1 0 0]
43*   % Multiply by 43 (ASCII for '+'), element-wise
      % STACK: [ 0  0 43  0  0;
                 0  0 43  0  0;
                43 43 43 43 43;
                 0  0 43  0  0;
                 0  0 43  0  0]
c     % Convert to char. Char 0 is displayed as space. Implicitly display.
      % STACK: ['  +  ';
                '  +  ';
                '+++++';
                '  +  ';
                '  +  ']

```

# Answer
> 8 votes
# Charcoal, ~~16~~ 13 bytes

```
Ｎα×+α←↑×+α‖Ｏ↘

```

Try it online!

Uses a different approach from the other Charcoal answer.

### Explanation

```
Ｎα                       # Take input and store it in variable α
×+α                       # α times write a +
←                         # Go left
↑×+α                      # α times write a + upwards

```

Now the top left corner is complete, it will look something like this:

```
  +
  +
+++

‖Ｏ↘                      # Reflect-overlap it in a SE direction

```

The last step is the key to this program, it uses the top-left part of the plus to generate the rest of the plus by reflecting it in the southeast direction (rightwards and downwards).

# Answer
> 8 votes
# Shakespeare Programming Language, ~~749~~ ~~743~~ ~~666~~ 625 bytes

```
N.Puck,.Page,.Ford,.Ajax,.Act I:.Scene I:.[Enter Puck and Ford]Puck:Listen tothy!Ford:You is the difference betweena cat I.Scene V:.[Exeunt][Enter Page and Ajax]Ajax:You is the difference betweena cat Ford.Scene X:.Page:You is the product ofPuck I.Is you as big as zero?If soyou is the sum oftwice the sum oftwice twice the sum ofa big big cat a cat a cat a cat.If notyou big big big big big cat.Speak thy!Ajax:You is the sum ofyou a cat.Is you worse Ford?If soLet usScene X.Page:You is twice the sum ofa big big cat a cat.Speak thy![Exit Page][Enter Puck]Ajax:You is the sum ofyou a cat.Is you worse Ford?If soLet usScene V.

```

Try it online!

With added newlines:

```
N.
Puck,.
Page,.
Ford,.
Ajax,.
Act I:.
Scene I:.
[Enter Puck and Ford]
Puck:Listen tothy!
Ford:You is the difference betweena cat I.
Scene V:.
[Exeunt]
[Enter Page and Ajax]
Ajax:You is the difference betweena cat Ford.
Scene X:.
Page:You is the product ofPuck I.Is you as big as zero?
If soYou is the sum ofTwice the sum ofTwice twice the sum ofA big big cat a cat a cat a cat.
If notyou big big big big big cat.Speak thy!
Ajax:You is the sum ofyou a cat.Is you worse Ford?If soLet usScene X.
Page:You is twice the sum ofa big big cat a cat.Speak thy!
[Exit Page]
[Enter Puck]
Ajax:You is the sum ofyou a cat.Is you worse Ford?If soLet usScene V.

```

Golfed 6 bytes because scene numbers don't have to be consecutive. Golfed some more bytes by applying the tips in the new answers to the Shakespeare tips question, **though these golfs aren't reflected in the explanation**.

## (Slightly outdated) explaination

SPL is an esolang designed to look like Shakespeare plays. Positive nouns have the value of 1 (here **cat** is used) and negative nouns have the value of -1 (none were used but **pig** is one of them). Adjectives modify a constant by multiplying it by 2.

```
N.

```

Everything until the first dot is the title and doesn't matter.

```
Puck,.                           row counter
Page,.                           column counter
Ford,.                           input
Ajax,.                           temp

```

The characters are integer variables, each of them also has a stack but I did not need to use that feature.

```
Act I:.
Scene I:.

```

Acts and scenes are used as goto labels

```
[Enter Puck and Ford]

```

It's only useful if exactly two characters are on the stage at the same time.

```
Puck:Listen to thy heart!

```

Reads a number and makes Ford remember it.

```
Ford:You is the difference between a cat and I.

```

As you can see Engrish is valid in SPL. This makes Puck's value "the different between a cat and I". But what does it mean? `cat` is a positive noun, so it's `Puck = 1 - Ford`.

```
Scene II:.
[Exeunt]

```

Exeunt is just a plural of "exit", and without arguments means that everyone on the stage exits.

```
[Enter Page and Ajax]
Ajax:You is the difference between a cat and Ford.

```

It's also `Page = 1 - Ford` but it's spoken by a different actor so `I` would be wrong. Since it's a loop, I can't just copy the value of `Puck`.

```
Scene III:.
Page:You is the product of Puck and I.

```

Pretty straightforward by now. `Ajax = Puck * Page`.

```
Is you as big as zero?

```

"as \[adj\] as" is the `==` operator.

```
If so,you is the sum of the sum of the sum of a big big big big big cat and a big big big cat and a big cat and a cat.

```

If Ajax == 0... "cat" is 1, "big cat" is 2, "big big cat" is 4 and so on. After substituting the simple constants we get "the sum of the sum of the sum of 32 and 8 and 2 and 1" -\> "the sum of the sum of 40 and 2 and 1" -\> "the sum of 42 and 1" -\> "43", which is the ASCII for +.

```
If not,you fat fat fat fat fat cat.

```

else it's just "fat fat fat fat fat cat", so Ajax gets the value of 32, the ASCII for a space.

```
Speak thy mind!

```

This is the command for outputting a character.

```
Ajax:
You sum you and cat.Is you as big as Ford?If not,let us return to Scene III.

```

This is a loop construct. "You sum you and cat" increments Page, and `if(Page != Ford) goto Scene III`. The rest of the program uses the same components, so here is a more readable pseudocode version:

```
Scene1:
    input = [input number];
    row = 0 - input + 1;
Scene2:
    col = 0 - input + 1;
Scene3:
    temp = row * col;
    if(temp == 0){
        temp = '+';
    }else{
        temp = ' ';
    }

    putchar(temp);
    Page = Page + 1;
    if(Page != Ford) goto Scene3;
    Ajax = 10;
    putchar(Ajax);
    Puck = Puck + 1;
    if(Puck != Ford) goto Scene2;

```

# Answer
> 7 votes
# Jelly, 11 bytes

```
ṬŒB»þ`ị⁾+ Y

```

Try it online!

# Answer
> 6 votes
## Mathematica, 39 bytes

```
Print@@@(CrossMatrix[#-1]"+"/. 0->" ")&

```

`CrossMatrix` is a built-in that generates a matrix of the required shape with `1`s instead of `+`s and `0`s instead of spaces. If we multiply that matrix by `"+"`, that replaces the `1`s with `+`s while leaving the `0`s unchanged (obviously... `0*x = 0` and `1*x = x`, right?). Then we replace the zeros manually with spaces using `/. 0->" "`. Finally, we print each line of the matrix with `Print@@@(...)`.

# Answer
> 5 votes
# C, 69 bytes

Not very interesting... Loops over the square, printing out the appropriate character.

```
r,c;f(n){for(r=-n;++r<n;puts(""))for(c=-n;++c<n;putchar(r*c?32:43));}

```

# Answer
> 5 votes
# GNU sed, ~~104~~ 99 bytes

-5 thanks to seshoumara
Includes +1 for `-r`

```
s/1//;h;:;s/(.*)1/ \12/;t;s/( *2)2(2*)/\1\n\1\2/
t;G;s/1+/&&1/;s/(.*)(\n1*)/&\n\1/;/1/!c+
y/12/++/

```

Takes input in unary.

Try it online!

```
s/1//                    # Subtract 1 from input
h                        # Hold onto input
:                        # Start loop
s/(.*)1/ \12/            #   Remove a 1, prepend a space, and append a 2
t                        # Loop until all 1s are 2s
                         # Start Loop (uses the previous label)
s/( *2)2(2*)/\1\n\1\2/   #   Shift all but the first 2 from the last line to a new line
                         #   E.g.  "  2"      "  2"
                         #         "  222" -> "  2"
                         #                    "  22"
t                        # Loop until all 2s are on their own line
G                        # Append a newline and input
s/1+/&&1/                # Double the number of 1s and append an extra
s/(.*)(\n1*)/&\n\1/      # Copy all of the lines with 2s to the end
/1/!c+                   # If there aren't any 1s print a '+'
y/12/++/                 # Convert all 1s and 2s to +s

```

# Answer
> 5 votes
# Ruby, ~~41~~ 40 bytes

```
->x{puts k=[?\s*(r=x-1)+?+]*r,?+*r+=x,k}

```

Try it online!

# Answer
> 5 votes
# Python 2, 52 bytes

```
n=input()-1
p=(' '*n+'+\n')*n
print p+'++'*n+'+\n'+p

```

Try it online!

A 53-byte alternative (TIO):

```
n=input()-1
for c in' '*n+'+'+' '*n:print c*n+'+'+c*n

```

# Answer
> 5 votes
**R, 54 bytes**

Shaving off 7 bytes thanks to @Jarko Dubbeldam:

```
function(n){a=matrix("",y<-n*2-1,y);a[n,]=a[,n]="x";a}

```

previous answer:

```
f=function(n){a=matrix("",n*2-1,n*2-1);a[n,]="x";a[,n]="x";a}

```

# Answer
> 4 votes
# PowerShell, 48 bytes

```
param($n)($x=,(" "*--$n+"+")*$n);'+'*(1+2*$n);$x

```

Try it online!

Takes input `$n`. Starts by constructing a string of `--$n` spaces, concatenated with `+`. That's converted into an array using the comma operator, (newly-decremented) `$n` times. That array is stored in `$x` and encapsulated in parens to place a copy on the pipeline.

We then do the middle section, which is `+` string multiplied out the appropriate number of times. That's left on the pipeline. Finally, we put `$x` on the pipeline again.

Those are all left on the pipeline at program completion, and the implicit `Write-Output` inserts a newline between elements.

# Answer
> 4 votes
# Python 2, 65 bytes

```
lambda n:('g+\n'*~-n+'+'*~-(2*n)+'\ng+'*~-n).replace('g',' '*~-n)

```

Try it Online!

# Answer
> 4 votes
## CJam, 23 bytes

```
ri_(S*'++a\2*(*_z..e>N*

```

Try it online!

### Explanation

This feels a bit suboptimal, but the idea is to superimpose the following two grids:

```
  +
  +
  +
  +
  +

```

```

+++++

```

Which gives the desired result.

```
ri    e# Read input and convert to integer N.
_(    e# Duplicate and decrement.
S*    e# Get a string of N-1 spaces (indentation of the vertical bar).
'++   e# Append a + (the vertical bar).
a     e# Wrap the line in an array.
\2*(  e# Swap with the other copy of N and compute 2N-1.
*     e# Repeat the line that many times.
_z    e# Duplicate the grid and transpose it.
..e>  e# Pairwise maximum between the two grids. This superimposes them.
N*    e# Join with linefeeds.

```

# Answer
> 4 votes
# Lua ~~113~~, 90 bytes

~~```
r,w,p=string.rep,io.read(),io.write;s=r(' ',w-1)p(r(s..'+'..'\n',w-1))p(r('+',w*2-1)..'\n')p(r(s..'+'..'\n',w-1))

```~~
```
r,w=string.rep,io.read()d=w*2-1;for a=1,d do print(a~=w and r(' ',w-1)..'+'or r('+',d))end

```

# Answer
> 3 votes
# Python 2, ~~60,~~56 bytes

```
n=input()-1
z=(' '*n+'+\n')*n
print z+'+'*(2*n+1)+'\n'+z

```

Try it online!

* -4 bytes - thanks to math junkie!

# Answer
> 3 votes
# Perl 5, 45 bytes

44 bytes of code + `-p` flag.

```
$_=join"+
",@%=($"x--$_)x$_,"+"x($_*2),@%,""

```

Try it online!

---

Some similar (but still different) approaches:

48 bytes (47+`-p`):

```
$_=join"+"x($_*2-1).$/,(~~($"x--$_."+\n")x$_)x2

```

50 bytes (49+`-n`):

```
$,="+"x($_*2-1).$/;print+(~~($"x--$_."+\n")x$_)x2

```

# Answer
> 3 votes
# 05AB1E, ~~15~~ ~~14~~ 12 bytes

```
F'+}¹·<×)û.c

```

Try it online!

**-2 thanks to Emigna.**

# Answer
> 3 votes
# CJam, 17

```
ri(S*_]'+*_ffe>N*

```

Try it online

**Explanation:**

```
ri(      read n, convert to int and decrement
S*       make a string of n-1 spaces
_]       duplicate it and put the 2 strings in an array
'+*_     join the strings with a '+' and duplicate the result
ffe>     for each pair of characters from the 2 (identical) strings,
          get the larger character (results in a matrix)
N*       join the rows with newlines

```

# Answer
> 3 votes
# Octave, ~~36~~ 31 bytes

Inspired by @LuisMendo 's MATL answer.

```
@(n)' +'(((a=1:n*2-1==n)|a')+1)

```

Try it online!

Previous answer:

```
@(n)' +'(1+((a=padarray(1,n-1))|a'))

```

Try it online!

# Answer
> 2 votes
# , ~~19~~ ~~18~~ 15 bytes

*Golfed 3 bytes thanks to @nmjcman101 by using `.` and `Ò+`*

```
Àé r+À«Ä.MgJxÒ+

```

Try it online!

# Answer
> 2 votes
# JS (ES6), ~~88~~ ~~74~~ 73 bytes

```
x=>(x--,y=y=>(" ".repeat(x)+`+
`).repeat(x),y``+"+".repeat(x+x+1)+"\n"+y``)

```

Probably can be golfed more.

```
Snippetify(x=>(x--,y=y=>(" ".repeat(x)+`+
`).repeat(x),y``+"+".repeat(x+x+1)+"\n"+y``))
```

```
<script src="https://programmer5000.com/snippetify.min.js"></script>
<input type = "number">
<pre data-output></pre>
```

# Answer
> 2 votes
# PHP, 68 Bytes

```
for(;$i<$c=-1+2*$m=$argn;)echo"\n".str_pad("+",$c," +"[$m==++$i],2);

```

83 Bytes

```
for(;$i<($c=($n=$argn)*2-1)**2;)echo$i%$c?"":"\n".!++$k," +"[$k==$n|$i++%$c==$n-1];

```

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

```
f=
n=>(r=([s,t])=>(s=s.repeat(n-1))+t+s+`
`)([r(` +`),r(`++`)])
```

```
<input type=number min=1 oninput=o.textContent=f(this.value)><pre id=o>
```

Outputs two trailing newlines. Alternative formulation, also 60 bytes:

```
n=>(r=a=>(s=a[0].repeat(n-1))+a[1]+s+`
`)([r(` +`),r(`++`)])

```

# Answer
> 2 votes
## Batch, 108 bytes

```
@set p=+
@set l=@for /l %%i in (2,1,%1)do @
%l%call set p= %%p%%
%l%echo %p%
@echo %p: =+%
%l%echo %p%

```

Note: Line 3 ends in a space.

# Answer
> 2 votes
# MUMPS, 48 ~~50~~ ~~53~~ bytes

```
F i=1-n:1:n-1 W ! F j=1-n:1:n-1 W $C(i&j*-11+43)

```

# Answer
> 2 votes
# PowerShell, 48

Doesn't seem to get shorter than that (and pretty much the same approach as the other solution):

```
($a=,(' '*($n="$args"-1)+'+')*$n)
'+'+'++'*$n
$a

```

or

```
($a=(' '*($n="$args"-1)+'+
')*$n)+'++'*$n+"+
$a"

```

# Answer
> 2 votes
## REXX, 81 bytes

```
arg a
b=a*2-1
do i=1 to b
  if i=a then say copies('+',b)
  else say right('+',a)
  end

```

# Answer
> 2 votes
# Brain-Flak, 216 + 1 = 217 bytes

*+1 bytes from the `-A` flag*

```
([{}]())(()()){<>(((((()()()()()){})){}()){}())<>(({}[()])<({}<(({})){({}()<(({}<<>(({}<(({})<>)>)<>)<>>)<{({}()<(((((()()){}){}){}){})>)}{}>)>)}{}>){(<{}(({}<<>({}<({}<>)>)>)<(({}){}){({}()<(({}))>)}{}>)>)}{}>)}{}{}

```

Try it online!

## Explanation to come

# Answer
> 2 votes
# Japt, 30 26 24 bytes

23 bytes of code, +1 for the `-R` flag.

Saved 4 bytes thanks to @ETHproductions!

```
V=U+´UVÇ¦U?SpU +'+:'+pV

```

Try it online!

# Answer
> 2 votes
# GolfScript, 27 bytes

```
~.(." "*"+"n++*.@2*("+"*n+\

```

Try it online!

Explanation and Example Execution:

```
                              # Input: 3
~.(.                          # Eval input, duplicate twice, decrement duplicates
                              # Stack: 3 2 2
    " "*                      # That many spaces
                              # Stack: 3 2 "  "
        "+"n++                # Followed by a + and a newline
                              # Stack: 3 2 "  +\n"
              *.              # Create n of those strings and duplicate it
                              # Stack: 3 "  +\n  +\n" "  +\n  +\n"
                @2*(          # Pull bottom to top, double it, decrement
                              # Stack: "  +\n  +\n" "  +\n  +\n" 5
                    "+"*n+    # That many +s followed by a newline
                              # Stack: "  +\n  +\n" "  +\n  +\n" "+++++\n"
                          \   # Swap last 2 items and implicityly print
                              # Stack: "  +\n  +\n" "+++++\n" "  +\n  +\n"

```

# Answer
> 2 votes
# Vim, 36 bytes

```
<C-x>D@-i <esc>Y@-pVGy:1s/ /+/g
P:%s/.*/&+&

```

The byte-count includes a trailing newline. Try it online!

### Explanation

```
<C-x>D

```

Decrement the input number `n` and delete it. The deleted text is stored in the "small deletion" register `"-`.

```
@-i <esc>

```

Insert a space `"-` times.

```
Y@-p

```

Yank that line, and then paste it `"-` times. We now have `n` lines of `n-1` spaces each, with the cursor at the beginning of line 2.

```
VGy

```

Select all lines till the end of the file (i.e. `n-1` lines, all but the first one) and yank them.

```
:1s/ /+/g

```

On line 1, replace each space with a plus sign. This command leaves the cursor on line 1.

```
P

```

Paste the previously yanked lines above the current line. We now have `n-1` lines of spaces, one line of plus signs, and `n-1` more lines of spaces.

```
:%s/.*/&+&

```

Replace each line with itself followed by a plus sign followed by itself again.

# Answer
> 1 votes
# Pyke, 14 bytes

```
t.\+s FQt*\++s

```

Try it online!

# Answer
> 1 votes
## , 21 bytes

```
' +'{~+./~(0=}.,])i.n

```

# Answer
> 1 votes
# 8086 machine code, 57 bytes

```
00000000  a0 82 00 24 cf 98 48 89  c1 b4 4c e3 20 bf 39 01  |...$..H...L. .9.|
00000010  57 51 5a 52 51 b0 20 89  d1 f3 aa b8 2b 0a ab 59  |WQZRQ. .....+..Y|
00000020  e2 f2 c6 05 24 59 01 c9  b4 09 5a cd 21 41 b0 2b  |....$Y....Z.!A.+|
00000030  cd 29 e2 fa 4a cd 21 c3  0a                       |.)..J.!..|
00000039

```

Takes a number (one digit...) as command line argument.
How it works:

```
            |   use16
a0 82 00    |       mov al, byte [0x82]
24 cf       |       and al, not 0x30
98          |       cbw
48          |       dec ax
89 c1       |       mov cx, ax
b4 4c       |       mov ah, 0x4c
e3 20       |       jcxz a
bf 39 01    |       mov di, s+1
57          |       push di
51          |       push cx
5a          |       pop dx
52          |       push dx
51          |   @@: push cx
b0 20       |       mov al, ' '
89 d1       |       mov cx, dx
f3 aa       |       rep stosb
b8 2b 0a    |       mov ax, 0x0a2b
ab          |       stosw
59          |       pop cx
e2 f2       |       loop @b
c6 05 24    |       mov byte [di], 0x24
59          |       pop cx
01 c9       |       add cx, cx
b4 09       |       mov ah, 0x09
5a          |       pop dx
cd 21       |       int 0x21
41          |   a:  inc cx
b0 2b       |   @@: mov al, '+'
cd 29       |       int 0x29
e2 fa       |       loop @b
4a          |       dec dx
cd 21       |       int 0x21
c3          |       ret
0a          |   s db 0x0a

```

# Answer
> 1 votes
# Rust, 89 bytes

```
|n|{for i in 1..2*n{if i==n{println!("{:+^1$}","",2*n-1)}else{println!("{:>1$}","+",n)}}}

```

# Answer
> 1 votes
# 05AB1E, 5 bytes

```
'+90Λ

```

Try it online!

# Answer
> 1 votes
# , 17 bytes

Anonymous tacit prefix function

```
' +'{~0=*/~@i:@<:

```

Try it online!

For example for `3`:

`<:` decrement; `2`

`i:` steps; `[-2,-1,0,1,2]`

`*/~` times table; `[[4,2,0,-2,-4],[2,1,0,-1,-2],[0,0,0,0,0],[-2,-1,0,1,2],[-4,-2,0,2,4]]`

`0=` indicate where zero; `[[0,0,1,0,0],[0,0,1,0,0],[1,1,1,1,1],[0,0,1,0,0],[0,0,1,0,0]]`

`" +"{~` use that to index into `" +"`; `[" + "," + ","+++++"," + "," + "]`

# Answer
> 1 votes
# Keg, ~~39~~ 37 bytes

```
;(:|:⑬*,\+,
,):⑨⑵;`+`*,
,(:|:⑬*,\+,
,

```

*-2 bytes using built-ins*

Try it online!

This attempt prints the isolated +s first, then the big row of +s then the final isolated +s.

# Answer
> 1 votes
# Wren, 67 bytes

```
Fn.new{|n|(1...2*n).map{|i|i==n?"+"*(n+~-n):" "*~-n+"+"}.join("
")}

```

Try it online!

## Explanation

```
Fn.new{|n|                                                      // New anonymous function with parameter n
          (1...2*n).map{|i|                                     // Foreach 1 -> 2n-1:
                           i==n?                                // If i equals n:
                                "+"*(n+~-n)                     // Return "+" 2n-1 times
                                           :" "*~-n             // Otherwise return space n-1 times
                                                   +"+"         // Add a trailing "+"
                                                       }.join("
")}                                                             // Join with newline

```

# Answer
> 1 votes
# PowerShell, 47 bytes

```
param($n)($x=,(' '*--$n+'+')*$n)
'+'+'++'*$n
$x

```

Try it online!

This one is shorter than 48 bytes `¯\_(ツ)_/¯`

# Answer
> 1 votes
# Vyxal `C`, 12 bytes

```
\+*÷:?d›*Wøm

```

Try it Online!

-2 thanks to @astonearachnid. -1 thanks to lyxal.

# Answer
> 1 votes
# Regenerate `-a`, 38 bytes

```
(({2,$~1} |\+|{2,$~1} )$2{$~1-2}!)\+$1

```

Takes input as a command-line argument. Try it here!

### Explanation

Here, we're going to (ab)use Regenerate's backtracking algorithm. The regex describes several possibilities for a single line, and the `-a` flag instructs Regenerate to output all possible matches. I'm going to start with a slightly different version that doesn't work for input \\$n=1\\$, and then discuss how to deal with that corner case afterwards.

Space is represented by underscore for better visibility.

```
(({2,$~1} |\+|{2,$~1} )$2{$~1-2})\+$1
(                               )      Group 1: the part before the central + character:
                                       either n-1 spaces or n-1 + characters
 (                    )                 Group 2: which character to use
                                         Option 1:
  {2,$~1}                                 Repeat empty string between 2 and n times
                                          (this causes the backtracker to try n-1 different
                                          options, all of them equal to empty string)
         _                                followed by space
          |                              Option 2:
           \+                             + character
             |                           Option 3:
              {2,$~1}_                    Same deal as option 1
                       $2               Group 2 again...
                         {$~1-2}        ... repeated n-2 times, for a total of n-1
                                 \+    The central + character
                                   $1  followed by group 1 again

```

When backtracking over group 2, Regenerate will try space \\$n-1\\$ times, then `+`, then space another \\$n-1\\$ times. So the list of all possible matches will be \\$n-1\\$ lines of spaces with a `+` in the middle, one line of `+` characters with a + in the middle, and \\$n-1\\$ more lines of spaces with a `+` in the middle--exactly the output we want.

There is a problem with \\$n=1\\$, however. We want group 1 to match the empty string, so that the only possible match for the full regex is `+`. However, with input of \\$1\\$, group 1 *fails* to match. The culprit is `$2{$~1-2}`, "repeat group 2's contents \\$n-2\\$ times." It's not possible to repeat something \\$-1\\$ times, so the whole group fails.

We can get around this failure by providing empty string as another alternative inside group 1. However, using `|` here raises another issue: we don't want the empty string to be tried if the first alternative succeeded, only if it failed. (Since we're asking for *all* possible matches, we would get a stray `+` at the end of the output for \\$n\>1\\$.)

The solution is to use `!`, a greedy version of `|`. If its left side matches at all, it takes the left side's match(es) and never tries the right side. It only tries the right side if its left side fails entirely. Thus, our final solution is:

```
((...)$2{$~1-2}!)\+$1
(               )      Group 1: the part before the central + character
 (...)                  Group 2: same options as before
      $2{$~1-2}         Repeat group 2 again n-2 times
               !        Or, iff that fails because n-2 < 0...
                        Empty string
                 \+    The central + character
                   $1  followed by group 1 again

```

# Answer
> 0 votes
# Charcoal, ~~26~~ 25 bytes

```
ＮηＡ⁻η¹η××η²+Ｐ+Ｍη↙Ｇ↑⁺¹×η²+

```

Try it online!

**Explanation:**

```
Ｎη                   // Take the size as input.
Ａ⁻η¹η                // Set η to η-1.
××η²+                // Print '+' η*2 times.
Ｐ+                   // Print '+'
Ｍη↙                 // Move η steps down to the left.
Ｇ↑⁺¹×η²+            // Print '+' η*2+1 times upwards from current position.

```

# Answer
> 0 votes
# Common Lisp, SBCL, 69 bytes

```
(format t"~@?~@?~@?+
~@*~@?""~v@{~:*~v@t+
~}"(1-(read))"~1@*~v@{+~}")

```

### Explanation

```
format        ;printing function
~@?           ;execute current argument as format string
~@*           ;go to first argument in list, to reuse "~v@{~:*~v@t+
              ;~}"
~v@{~}        ;loop n times, where n is current argument
~:*           ;go back one argument - to reuse (1-(read))
~v@t          ;add n spaces where n is current argument
              ;if we were sure that we start on new line we could
              ;use ~vt, which moves to nth column
(1-(read))    ;take input and subtract 1 from it
~1@*          ;move to second argument, to reuse (1-(read))

"~@?~@?~@?+   ;main format string - calls others
~@*~@?"       ;prints one "+" and one newline
"~v@{~:*~v@t+ ;outputting input-1 lines of "+"s
~}"           ;preceded by correct amount of spaces
"~1@*~v@{+~}" ;outputting input-1 pluses. We do it two times
              ;and then add one + at the end. This way there
              ;is no need for argument like: (1-(* 2 INPUT))
              ;which would make me need a variable keeping INPUT

```

Ideas for improvement are welcomed.

# Answer
> 0 votes
# Pyth, 24 bytes

```
+J*+++K*dQ\+Kb/Q2*\+hyQJ

```

Try it online!

# Answer
> 0 votes
# Perl 5, 43 + 1 (-n) = 44 bytes

```
$,="+
";say@q=($"x--$_)x$_,'+'x(2*$_),@q,''

```

Try it online!

Independently came up with pretty much the same method as @Dada, but got it down by 1 byte.

# Answer
> 0 votes
# Excel, 86 bytes

```
=REPT(REPT(" ",A1-1)&"+
",A1-1)&REPT("+",2*A1-1)&"
"&REPT(REPT(" ",A1-1)&"+
",A1-1)

```

# Answer
> 0 votes
# Japt `-R`, 12 bytes

Look, Ma, no `+`!

```
çÄ ê
¬hNÉU û

```

Try it

# Answer
> 0 votes
**APL (NARS2000), 25 characters:**

```
{' +'[1+∨/¨⍵=∘.,⍨⍳⍵+⍵-1]}

```

**APL (NARS2000), 26 characters:**

```
{' +'[1+∨/¨⍵=∘.,⍨⍳¯1+2×⍵]}

```

**Examples:**

```
      {' +'[1+∨/¨⍵=∘.,⍨⍳⍵+⍵-1]} 1
+
      {' +'[1+∨/¨⍵=∘.,⍨⍳⍵+⍵-1]} 2
 +
+++
 +
      {' +'[1+∨/¨⍵=∘.,⍨⍳⍵+⍵-1]} 3
  +
  +
+++++
  +
  +
      {' +'[1+∨/¨⍵=∘.,⍨⍳⍵+⍵-1]} 4
   +
   +
   +
+++++++
   +
   +
   +

```

**Rationale:**

Take `n = 4` as example. Objective is to generate an integer matrix as below:

```
1 1 1 2 1 1 1
1 1 1 2 1 1 1
1 1 1 2 1 1 1
2 2 2 2 2 2 2
1 1 1 2 1 1 1
1 1 1 2 1 1 1
1 1 1 2 1 1 1

```

Expression `⍵=∘.,⍨⍳⍵+⍵-1`, when given `⍵ = 4`, generates matrix of 2-tuple from integer vector `1..7`:

```
 0 0  0 0  0 0  0 1  0 0  0 0  0 0
 0 0  0 0  0 0  0 1  0 0  0 0  0 0
 0 0  0 0  0 0  0 1  0 0  0 0  0 0
 1 0  1 0  1 0  1 1  1 0  1 0  1 0
 0 0  0 0  0 0  0 1  0 0  0 0  0 0
 0 0  0 0  0 0  0 1  0 0  0 0  0 0
 0 0  0 0  0 0  0 1  0 0  0 0  0 0

```

Each cell is reduced by logical-or `∨/¨` to give boolean matrix:

```
0 0 0 1 0 0 0
0 0 0 1 0 0 0
0 0 0 1 0 0 0
1 1 1 1 1 1 1
0 0 0 1 0 0 0
0 0 0 1 0 0 0
0 0 0 1 0 0 0

```

Add 1 to this matrix and we have the desired array-indexing matrix.

# Answer
> 0 votes
# Canvas, <sup>~~8~~</sup> 7 bytes

```
+×：⤢ｎ！┼

```

Try it here!

-1 byte from hakr14.

# Answer
> 0 votes
# Batch 97 bytes

**requires windows 10 with virtual terminal support**

```
Set x=%~1&cls&@Set/a c=x*2-1
@For /L %%i in (1 1 %c%)Do @Echo(ESC[%%i;%x%H+ESC[%x%;%%iH+ESC[%x%BESC[1G

```

`ESC` is the ANSI escape character, which doesn't paste well but can be copied from the raw paste data here.
Or it can be generated by opening the command prompt and typing `>"%TEMP%\escape.chr" Echo(``ALT`+`027` then pressing `ENTER`, or output using a for loop with `Echo off`:

```
(For /F "skip=4 DELIMS=" %a in ('Echo(prompt $E^|cmd')Do Echo(%a) >"%TEMP%\escape.chr"

```

**How:**
Iterates over the width of the string `c` and outputs c`+` along the the `x` (y and x) intersection using virtual terminal sequences to move the cursor to the relevant coordinates.

# Answer
> 0 votes
# Regenerate, 38 bytes

```
(( {$~1-1}\+\n){$~1-1})\+{$~1*2-1}\n$1

```

Takes input as a command-line argument. Try it here!

### Explanation

Space is represented by underscore for better visibility.

```
(( {$~1-1}\+\n){$~1-1})\+{$~1*2-1}\n$1
(                     )                 Group 1: the section above the center line
 (            )                          Group 2: one line of that section
  _{$~1-1}                                n-1 spaces
          \+\n                            followed by + and newline
               {$~1-1}                   Repeat n-1 times
                       \+{$~1*2-1}      n*2-1 + characters
                                  \n    followed by newline
                                    $1  Contents of group 1 again

```

# Answer
> 0 votes
# \>\<\> (Fish), 94 bytes

```
1-:?!/:::?v"+"o~ \
 84*o1-70.\
>.!07$&:&v!?:-1oa/
/+1 *2:~ /
 /ao~";"93p10.
<\!?:-1o"+"
 ;"+"\

```

Try it online! Animated Version

## Explanation

The yellow loop special cases the 1 cross variant to print a `+` and exit.

The blue loop is the loops over each line. The green loop prints N spaces and the blue loop then prints a "+" at the end of each line.

The orange bypass calculates the length of the row which will have only + signs (2n + 1). Then it will enter the blue-purple loop.

The blue-purple loop prints the plus signs in the middle row. Once the count reaches 0 the mirror isn't skipped anymore so the pink segment is entered.

The pink segment replaces the mirror at 9,3 with a ;. This is the red highlighted semicolon in the picture. Then jumps back to the blue loop. However, this time instead of printing the row of `+` signs it will exit. (`;` means exit program in fish)

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


title: Tic, Tac, stub your Toe

text:
# Question
Title: Tic, Tac, stub your Toe
Find the max number of Xs you can fit onto a rectangular tic-tac-toe board of length *l* and height *h* without ever having 3 consecutive Xs in a row **diagonally**, horizontally, or vertically.

This is a challenge so shortest code wins!

## Input

A single line containing values *l* and *h*, representing the length and height of the tic-tac-toe board, separated by a space.

## Constraints

```
1 ≤ l ≤ 2,147,483,647
1 ≤ h ≤ 2,147,483,647

```

## Output

A single number representing the number of Xs that can fit on the tic-tac-toe board without three in a row

## Sample Inputs and Outputs

```
Input -> Output
2 2 -> 4
3 3 -> 6
2 3 -> 4
4 4 -> 9

```

## Explanation

4 Xs can fit on a 2x2 tic-tac-toe board without having 3 Xs in a row anywhere

6 Xs can fit on a 3x3 tic-tac-toe board without having 3 Xs in a row anywhere

4 Xs can fit on a 2x3 tic-tac-toe board without having 3 Xs in a row anywhere

9 Xs can fit on a 4x4 tic-tac-toe board without having 3 Xs in a row anywhere

## Credits

Lukas Zenick for creating the problem

## Extra Data

https://docs.google.com/spreadsheets/d/1qJvlxdGm8TocR3sh3leRIpqdzmN3bB\_z8N-VrEKSCwI/edit

# Answer
> 4 votes
# , 270 bytes

```
function(x,y,z=expand.grid(rep(list(1:0),x*y)),l=lapply(1:2^(x*y),function(i)matrix(unlist(z[i,]),x)))max(sapply(l[sapply(l,function(m,f=function(m)apply(cbind(m,2,matrix(rbind(2,m),nrow(m))),1,function(x)max((y=rle(x))$l[!!y$v])))max(f(m),f(t(m[nrow(m):1,])))<3)],sum))

```

Try it online!

Unfortunately I didn't notice the 'fastest code' tag and started working on this assuming that it was 'code golf', so this isn't very fast (and I won't golf it any further). But it at least calculates the test cases without timing-out...

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

Saved 250 bytes thanks to @py3\_and\_c\_programmer.

This was originally a challenge. Now it became a , but I'm too lazy to golf it.

```
f[m_,n_]:=Total@LinearProgramming[Table[-1,m*n],SparseArray[Flatten@MapIndexed[{#2[[1]],#}->1&,Flatten[{Table[m*i+j+k+1,{i,0,n-1},{j,0,m-3},{k,0,2}],Table[m*(i+k)+j+1,{i,0,n-3},{j,0,m-1},{k,0,2}],Table[m*(i+k)+j+k+1,{i,0,n-3},{j,0,m-3},{k,0,2}],Table[m*(i+k)+j-k+1,{i,0,n-3},{j,2,m-1},{k,0,2}]},2],{2}],{(m-2)n+m(n-2)+2(m-2)(n-2),m*n}],Table[{2,-1},(m-2)n+m(n-2)+2(m-2)(n-2)],Table[{0,1},m*n],Integers]

```

Try it online!

Using the built-in `LinearProgramming`. Gives the results from `1x1` to `9x9` in 40 seconds on TIO.

# Answer
> 2 votes
# Ruby, 311 bytes

```
->m,n{(0...1<<(m*n)).map{|z|
  k=("%0#{m*n}b"%z).scan(/#{"(.)"*n}/)
}.reject{|w|
    (w.map(&:join).grep(/111/)[0]||w.transpose.map(&:join).grep(/111/)[0])||
    w.each_cons(3).any?{|x|x.transpose.each_cons(3).any?{|z|
      k=z.join.to_i(2)
      [273,84].any?{|z|k&z==z}
  }
}}.map{|c|c.flatten.count ?1}.max}

```

Try it online!

Nothing particular, still using brute force.

# Answer
> 2 votes
# Python 3 (PyPy), ~~262~~ ~~254~~ 212 bytes

```
def f(x,y,D={}):
 R=[i for i in range(2**x)if'111'not in bin(i)]
 for _ in[0]*y:D={(a,b):bin(a).count('1')+max(D.get((b,c),0)for c in R if(a&b|a>>2&b>>1|a*4&b*2)&c<1)for a in R for b in R}
 return max(D.values())

```

Try it online!

-8 bytes thanks to 12944qwerty

Rows are encoded in binary, and `R` is the list of all possible rows.

In any given iteration `i` of the second for loop (starting from 0), `D` is a dictionary where `D[a,b]` is the largest number of Xs that can fit in an `X` by `i` board where the first two rows are `a` and `b`.

The new `D` is calculated by iterating over every possible first 2 rows `a,b`, and setting `D[a,b]` to the number of Xs in row `a` plus the maximum value of `D[b,c]` where `c` is every row that could follow `a,b`.

This algorithm takes time \\$y\cdot8^x\\$ and space \\$4^x\\$, solving 1x1 to 9x9 in 20s on TIO.

# Answer
> 2 votes
# \+ `lpSolve`, ~~202~~ ~~194~~ 149 bytes

```
function(m,n,`[`=`for`,x=outer(1:m,1:n*1i,`+`)){i[x,j[c(1,1i,1+1i,1i-1),F<-rbind(F,x%in%(0:2*j+i))]]
lpSolve::lp("max",!!x,F,"<",min(m*n,2),,seq(x))}

```

Try it online!

A golfed version of an external ILP solver-based solution, which I started working on when this was a fastest code challenge, but got closed. Works slower than Wolfram though, but still manages 8x8 on TIO.

In lieu of a proper explanation, here is an outdated, but somewhat ungolfed version:

```
library('lpSolve')

f = function(m, n, p = m*n, r = -1:1, l = {})
{
  if(p == 1) return(1) # Edge case for 1x1
  for(i in 1:m) for(j in 1:n) for(k in 1:4)
  {
    d = list(          # Directions
      cbind(i+r, j),   # Vertical
      cbind(i, j+r),   # Horizontal
      cbind(i+r, j+r), # Diagonal
      cbind(i-r, j+r)  # Antidiagonal
    )
    x = matrix(0, m, n)
    try(x[d[[k]]] <- 1)
    l = rbind(l, c(x))
  }
  lp(direction = "max", objective.in = rep(1, p), const.mat = l, const.dir = "<=", const.rhs = 2, all.bin = T)
}

```

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

Expects `(width)(height)`.

```
w=>h=>eval("for(o=0,m=1<<w*h;M=--m;o=M|(g=k=>v=k&&1+g(k&k-1))(m)<o?o:v)for(p=q=0;(v=M&2**w-1)&v/2&v/4|v&p&q|v&p/2&q/4|q&(q=p)/2&(p=v)/4?0:M>>=w;);o")

```

Try it online!

---
Tags: code-golf, binary-matrix, tic-tac-toe
---


title: What exactly was your question?

text:
# Question
Title: What exactly was your question?
### Introduction

When you are given a boring text, you just want to get it over with as quick as possible. Let's observe the following text:

```
Ens colligi timenda etc priorem judicem. De quascunque ii at contingere
repugnaret explicetur intellectu. Adjuvetis hoc fortassis suspicari opportune
obversari vix eam? Dei praemia prudens hominum iii constet requiri haberem. Ima
sane nemo modi fuit lus pro dem haud. Vestro age negare tactum hoc cui lor. Ne et
ut quod id soli soni deus. At constare innumera is occurret ea. Nia calebat seu
acquiro fraudem effingo dicimus.

```

**Note:** This text has newlines for readability, while the test cases you need to handle don't have newline characters.

One way to skim text is to find questions that the writer has put into the text. For example, there is 1 question in the text above. Namely:

```
Adjuvetis hoc fortassis suspicari opportune obversari vix eam?

```

This can be done by splitting the text into sentences. A sentence will *always* end with one of the following punctuation symbols: `.?!` (others don't have to be handled). Other symbols than these are part of the sentence.

---

### The Task

Given a line of text consisting of only

* **letters (A-Za-z)**
* **numbers (0-9)**
* **spaces**
* **punctuation (`,.;:?!`)** (a sentence cannot start with one of these).

Output the questions that are in the text in any reasonable format. You may assume that the text will always have **at least 1 question**. Outputting *trailing* and *leading* spaces before and after a question is allowed.

**Important**: Next to a *punctuation* symbol, there will **never** be another punctuation symbol (e.g. `??` is invalid and will not be required to handle).

---

### Test cases

In the format:

```
Input
Output(s)

```

The test cases:

```
Huh? I haven't heard what you just said. Could you repeat that please?
Huh?
Could you repeat that please?

plz can i haz cheesburgr? i am cat pls.
plz can i haz cheesburgr?

This is a badly formatted question.Can u please help me,or my friends,with formatting this question    ?thankyou.
Can u please help me,or my friends,with formatting this question    ?

a.b.c.d?
d?

Does this question have a question mark? yes
Does this question have a question mark?

Why example.com resolves to 127.0.0.1 in 99.9 percent of cases?
9 percent of cases?

A? b? c? d!
A?
b?
c?

```

---

This is , so the submission with the lowest number of bytes wins!

# Answer
## Retina, ~~13~~ 11 bytes

```
!`[^.?!]*\?

```

Try it online!

```
!`       print all matches
[^.?!]*  any number of non-ending-punctuation symbols
\?       followed by a question mark

```

Thanks to @MartinEnder for 2 bytes!
> 9 votes

# Answer
# Python, 46 Bytes

```
import re
f=lambda s:re.findall("[^!?.]*\?",s)

```

Call with:

```
f("your string here")

```

output on tests:

```
['Can u please help me,or my friends,with formatting this question    ?', 'Can u please help me,or my friends,with formatting this question    ?', ' Huh?', ' Could you repeat that please?', ' plz can i haz cheesburgr?', 'd?', 'Does this question have a question mark?', '9 percent of cases?', 'A?', ' b?', ' c?']

```

another idea, 77 bytes (in python3 you'd need a list around filter):

```
import re
f=lambda s:filter(lambda x:x[-1]=="?",re.split("(?<=[\.\?!]).",s)))

```

I'm new to this so this, so this could probably be much shorter.

*-17 (!) bytes thanks to Martin*

*-2 bytes by matching anything that is not "!","?" or "." (Getting close to the shell solutions, but I doubt I could save much more)*
> 5 votes

# Answer
## JavaScript, ~~35~~ 24 bytes

```
a=>a.match(/[^.?!]*\?/g)

```

Returns all substrings that start after a `.`, `?`, or `!` (or the beginning of the text) and end in a `?`.
> 4 votes

# Answer
# , 12 bytes

```
Í[^.!?]*[.!]

```

Try it online!

A very straightforward answer.

```
Í             "Remove every occurrence, on every line
 [^.!?]       "Of any character that isn't '.', '!', or '?'
       *      "Repeated any number of times
        [.!]  "Followed by a a '.' or a '!'

```

Thankfully, handling newlines, or verifying all test-cases does not add any bytes.
> 3 votes

# Answer
# Shell utilities, ~~43~~ 38 bytes

Thanks to rexkogitans for trimming 5 bytes!

```
tr ? "\n"|sed "s/.*[\.!]//;s/.\+/&?/"

```

Pipe input in, like this:

```
echo Huh? I haven't heard what you just said. Could you repeat that please?|tr ? "\n"|sed "s/.*[\.!]//;s/.\+/&?/"

```

If if matters, I'm using:

- GNU `tr` 5.3.0
- GNU `sed` 4.2.1
- Microsoft's `cmd.exe`, shipped with Windows 5.1.2600
> 3 votes

# Answer
# Jelly, 16 bytes

```
f€“.?!”0;œṗfÐf”?

```

Try it online! or verify all test cases
> 3 votes

# Answer
## Perl 5.10, ~~21~~ 18 bytes (with *-n* flag)

```
say m/[^?.!]+\?/g

```

Straightforward implementation of the question.

Try it here!
> 2 votes

# Answer
# Ruby 1.9, 17 bytes

```
$_=$F

```

A 5 bytes program that must be invoked with the following command line options:

```
paF[^?]*[.!]

```
> 2 votes

# Answer
## Batch, 174 bytes

```
@echo off
set/ps=
set t=
:l
set c=%s:~0,1%
set t=%t%%c%
if "%c%"=="?" echo %t%&set t=
if "%c%"=="!" set t=
if "%c%"=="." set t=
set s=%s~1%
if not "%s%"=="" goto l

```

Reading a line from STDIN is a byte shorter than using `set s=%*`.
> 1 votes

# Answer
## PowerShell v4+, 43 bytes

```
([regex]::Matches($args,'[^?!.]*\?')).Value

```

Really straightforward. Takes input `$args` and feeds that in as the first parameter to a .NET `[regex]::Matches(...)` static function. The regex we're matching is `[^?!.]*\?` -- that is, any number of non-sentence-ending characters that are followed by a question mark. The static function returns an array of objects detailing what capture group, index, etc., but we only want the `.Value`s, so the return is encapsulated in parens and we call that property. This is where the v4+ requirement comes into play, as in prior versions you'd need to instead do something like a loop `|%{$_.Value}` or `|Select Value` to get the appropriate properties.

**Example without the parens and `.Value`**

```
PS C:\Tools\Scripts\golfing> .\what-exactly-was-your-question.ps1 "Huh? I haven't heard what you just said! Could you repeat that please?"

Groups   : {Huh?}
Success  : True
Captures : {Huh?}
Index    : 0
Length   : 4
Value    : Huh?

Groups   : { Could you repeat that please?}
Success  : True
Captures : { Could you repeat that please?}
Index    : 40
Length   : 30
Value    :  Could you repeat that please?

```

**Example with the parens and `.Value`**

```
PS C:\Tools\Scripts\golfing> .\what-exactly-was-your-question.ps1 "Huh? I haven't heard what you just said! Could you repeat that please?"
Huh?
 Could you repeat that please?

```
> 1 votes

# Answer
## Python 3, 91 bytes

```
def f(x,a=0):
 for n in range(len(x)):
  if x[n]in".!":a=n+1
  if x[n]is"?":print(x[a:n+1])

```

**Saves 1 byte in Python 2:**

```
def f(x,a=0):
 for n in range(len(x)):
  if x[n]in".!":a=n+1
  if x[n]is"?":print x[a:n+1]

```
> 1 votes

# Answer
# \>\<\> (Fish), ~~72~~ 69 bytes

```
>i:0(?^:"?"=?v\"!."@=?v=?v
^>l?v00. > ovr:    .12<  <
 ^ ~< ;!0^?l<<:

```

Animated Version

## Explanation

The top row reads a character, pushes it onto the stack, and checks if it is `.`, `!` or `?`.

If it's a `!` or a `.`, we jump to 2,1 where there is a loop to clear the stack.

If it's a `?` there is a similar loop, futher to the right. Instead of discarding elements we reverse the stack first and print items instead of just discarding them. We then enter the same green loop but the stack is already empty so we will soon exit it. We push a 0 to the stack so the program doesn't crash here.
> 0 votes

# Answer
# Japt, 11 bytes

Using `replace` rather than `match`. Works out at the same byte count.

```
r"[^?]*[.!]

```

Try it
> 0 votes

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


title: Compute the first N digits of e

text:
# Question
Title: Compute the first N digits of e
## Challenge

Write a program to compute the the first N (\<= 10^3) digits of .

Your program should take an integer **N** as input.

**Input:**

```
100

```

**Output:**

```
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427

```

**Input:**

```
7

```

**Output:**

```
2.718282

```

**Input:**

```
1000

```

**Output:**

```
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427427466391932003059921817413596629043572900334295260595630738132328627943490763233829880753195251019011573834187930702154089149934884167509244761460668082264800168477411853742345442437107539077744992069551702761838606261331384583000752044933826560297606737113200709328709127443747047230696977209310141692836819025515108657463772111252389784425056953696770785449969967946864454905987931636889230098793127736178215424999229576351482208269895193668033182528869398496465105820939239829488793320362509443117301238197068416140397019837679320683282376464804295311802328782509819455815301756717361332069811250996181881593041690351598888519345807273866738589422879228499892086805825749279610484198444363463244968487560233624827041978623209002160990235304369941849146314093431738143640546253152096183690888707016768396424378140592714563549061303107208510383750510115747704171898610687396965521267154688957035035

```

**Shortest solution wins!**

# Answer
## Mathematica (12 bytes)

```
N[E,Input[]]

```
> 9 votes

# Answer
## Python, 69

```
e=f=n=1;N=input()+2;exec"e+=10**N/f;f*=n;n+=1;"*N;print'2.'+`e`[1:-4]
```

Computes N+2 iterations of the standard power series for e.
> 9 votes

# Answer
# Python, 67

```
import decimal as d
d.getcontext().prec=input()
print d._One.exp()

```
> 7 votes

# Answer
# J, 20...ish.

Computational, but... Very inefficient. With n defined (20):

```
(0 j.<:n)":+/%!i.x:n+9

```

As a monadic function (32):

```
ge =. 3 : '(0 j.<:y)":+/%!i.x:y+9'

```

As a tacit function (33, fixed):

```
(0 j.<:)":(+/)&:(%&!&i.&x:&(9&+))

```
> 6 votes

# Answer
# 05AB1E, 4 3 2 bytes

Crossed out 4 is still regular 4 ;(

Thanks to @Adnan for a byte.

```
žt

```

Uses **CP-1252** encoding.

Explanation:

```
žt - Push input. Pop a, push e to a places (up to 10000).

```

**Update:**

Remove `I`, as `žt` takes input anyway if none is on the stack.
> 3 votes

# Answer
# Ruby, 68

```
require 'bigdecimal/math';include BigMath;puts E(gets.to_i).to_s 'F'

```
> 1 votes

# Answer
# GolfScript 43 41

```
~10\?1:b 461,{)b*:b@+\}460*;*b/`);(;'2.'\

```

Edit: I might as well replace the 0 with the leftover 1 from initializing b, the resulting difference is far too small to make it to the output.

I left the old version as that is what I have documented below.

```
~10\?1:b;0 461,{)b*:b@+\}460*;*b/`);(;'2.'\

```

`~10\?` Take input and calculate 10^input, leave the result on the stack.
`1:b;` Store 1 in b.
`0 461,` Put 0 on the stack, put the array \[0 1 ... 459 460\] on the stack.
`{ }460*` Execute function 460 times.
`)b*:b` Take the last element of the array, multiply it by b, store result in b and leave the result on the stack.
`@+\` Switch the 0 (which is only a zero at the first iteration) to the top of the stack, add it to the leftover b value, and switch the result back again.
`;` Remove the rest of the array (only \[0\] is left).
The number that was initialized to 0 now hold the value e\*460! and b hold 460!
`*` Multiply 10^input by e\*460! (they are at this point the only 2 elements left on the stack).
`b/` Divide the result by b.
The stack now hold the value e\*10^input which when converted to a string will hold all the decimals, but not the dot.
``);(;'2.'\` A bunch of string operations to fit in the dot.

e\*460! is calculated as 1 + 460 + 460\*459 + 460\*459\*458 etc.
> 1 votes

# Answer
# bc, 17 chars

```
scale=read()
e(1)

```
> 1 votes

# Answer
# Vyxal, 2 bytes

```
∆Ė

```

Try it Online!

Built in solution.
> 1 votes

# Answer
**J, 17**

```
(":&(x:^1)@*&0j1)

```

Example:

```
(":&(x:^1)@*&0j1) 50
2.71828182845891281655718620537435347047040502245993

```

Uses built in exponential verb - so, "compute" is on shaky grounds. Basically:

```
^1 - computes e**1
x: - does extended precision
0jy ": - formats the number to y digit

```
> 0 votes

# Answer
## Mathcad, \[tbd\] bytes

Uses a spigot algorithm - http://comjnl.oxfordjournals.org/content/11/2/229.full.pdf+html.

---

Byte count not given as Mathcad byte count equivalence is yet to be determined. However, using a symbol equivalence it is roughly 121 bytes ... and not going to win any brevity prizes no matter how the equivalence is determined.
> 0 votes

# Answer
# Mathematica, 7 bytes

```
N[E,#]&

```

My answer is a further golfing of this answer.

Try it online!

For some reason, the output over at TIO looks funny but I tested it on my machine and the code works just fine.
> 0 votes

# Answer
## GTB, 14

```
eS?`AS;_,1,A+1

```

**Explanation**

`e` \- Put `e` as the last calculated value

`S?` \- Convert `e` to string `_`

``A` \- Input A

`S;_,1,A+1` Display the first `A` digits of `e`
> -1 votes

# Answer
# Perl 5 `-Mbignum=bexp -p`, 12 bytes

```
$_=bexp 1,$_

```

Try it online!
> -1 votes

---
Tags: code-golf, math
---


title: Nth Differences

text:
# Question
Title: Nth Differences
In math, one way to figure out what the type of a given relation (linear, quadratic, etc) is to calculate the differences. To do so you take a list of y values for which the gap between the correspondent x values is the same, and subtract each one from the number above it, creating a list of numbers one shorter then the previous list. If the resultant list is completely composed of identical numbers, then the relation has a difference of 1 (it is linear). If they are not identical, then you repeat the process on the new list. If they are now identical, the relation has a difference of 2 (it is quadratic). If they are not identical, you simply continue this process until they are. For example, if you have the list of y values `[1,6,15,28,45,66]` for incrementally increasing x values:

```
First Differences:

1
6   1-6  =-5
15  6-15 =-9
28  15-28=-13
45  28-45=-17
66  45-66=-21

Second differences:

-5
-9  -5+9  =4
-13 -9+13 =4
-17 -13+17=4
-21 -17+21=4

As these results are identical, this relation has a difference of 2

```

## Your Task

Write a program or function that, when given an array of integers as input, returns the difference of the relation described by the array, as explained above.

## Input

An array of integers, which may be of any length\>1.

## Output

An integer representing the difference of the relation described by the input.

## Test Cases

```
Input                            => Output
[1,2,3,4,5,6,7,8,9,10]           => 1
[1,4,9,16,25,36]                 => 2
[1,2,1]                          => 2 (when there is only one value left, all values are automatically identical, so the largest difference an array can have is equal to the length of the array-1)
"Hello World"                    => undefined behavior (invalid input)
[1,1,1,1,1,1,1,1,1]              => 0 (all elements are already identical)
[1, 3, 9, 26, 66, 150, 313, 610] => 6

```

## Scoring

This is , lowest score in bytes in each language wins for that language. Lowest score overall gets the green checkmark.

# Answer
> 10 votes
# Husk, 6 bytes

Thanks Leo for letting me use his version that works for `[1,1,1,1,1,1]`

```
←VE¡Ẋ-

```

Try it online!

### Explanation

```
   ¡     Repeatedly apply function, collecting results in a list
    Ẋ-     Differences
 VE      Get the index of the first place in the list where all the elements are equal
←        Decrement

```

# Answer
> 8 votes
# JavaScript (ES6), 47 bytes

```
f=a=>-a.every(x=>i=!x)||1+f(a.map(n=>n-a[++i]))

```

### Test cases

```
f=a=>-a.every(x=>i=!x)||1+f(a.map(n=>n-a[++i]))

console.log(f([1,2,3,4,5,6,7,8,9,10]))    // 1
console.log(f([1,4,9,16,25,36]))          // 2
console.log(f([1,2,1]))                   // 2
console.log(f([1,1,1,1,1,1,1,1,1]))       // 0
console.log(f([1,3,9,26,66,150,313,610])) // 6
```

# Answer
> 7 votes
# MATL, 8 bytes

```
`dta}x@q

```

Try it online! Or verify all test cases.

### Explanation

This compuntes consecutive differences iteratively until the result is all zeros or empty. The output is the required number of iterations minus 1.

```
`      % Do... while
  d    %   Consecutive diffferences. Takes input (implicitly) the first time
  t    %   Duplicate
  a    %   True if any element is nonzero. This is the loop condition
}      % Finally (execute before exiting the loop)
  x    %   Delete. This removes the array of all zeros
  @    %   Push iteration index
  q    %   Subtract 1. Implicitly display
       % End (implicit). Proceed with next iteration if top of the stack is true

```

# Answer
> 7 votes
# , ~~50~~ 44 bytes

```
function(l){while(any(l<-diff(l)))F=F+1
F*1}

```

Try it online!

Takes a `diff` of `l`, sets it to `l`, and checks if the result contains any nonzero values. If it does, increment `F` (initialized as `FALSE` implicitly), and returns `F*1` to convert `FALSE` to `0` in the event that all of `l` is identical already.

# Answer
> 5 votes
# Mathematica, 49 bytes

```
(s=#;t=0;While[!SameQ@@s,s=Differences@s;t++];t)&

```

*thanx @alephalpa for -6 bytes and @hftf -1 byte*

and here is another approach from @hftf

# Mathematica, 49 bytes

```
Length@NestWhileList[Differences,#,!SameQ@@#&]-1&

```

# Answer
> 5 votes
# Perl 6, 37 bytes

```
{($_,{@(.[] Z- .[1..*])}...*.none)-2}

```

Try it online!

**Explanation:** The function takes the input as one list. It then builds a recursive sequence like this: the first element is the original list (`$_`), the next elements are returned by `{@(@$_ Z- .[1..*])}` being called on the previous element, and that is iterated until the condition `*.none` is true, which happens only when the list is either empty or contains only zeroes (or, technically, other falsey values). We then grab the list and subtract 2 from it, which forces it first to the numerical context (and lists in numerical context are equal to the number of their elements) and, at the end, returns 2 less than the number of elements in the list.

The weird block `{@(@$_ Z- .[1..*])}` just takes the given list (`.[]` — so called *Zen slice* — indexing with empty brackets yields the whole list), zips it using the minus operator (`Z-`) with the same list without the first element (`.[1..*]`) and forces it to a list (`@(...)` — we need that because zip returns only a Seq, which is basically an one-way list that can be iterated only once. Which is something we don't like.) And that's it.

# Answer
> 4 votes
# Jelly, 7 bytes

```
-Iß$E?‘

```

Try it online!

## Explanation

```
-Iß$E?‘  Input: array A
     ?   If
    E    All elements are equal
         Then
-          Constant -1
         Else
   $       Monadic chain
 I           Increments
  ß          Recurse
      ‘  Increment

```

# Answer
> 4 votes
# Japt, ~~10~~ 7 bytes

```
è@=ä-)d

```

Try it online!

Relies on the fact that the result is guaranteed to be within the length of the input array.

## Explanation

```
è@=ä-)d     Implcit input of array U
 @          For each value in U...
  =ä-)      Update U to be equal to its subsections, each reduced by subtraction
      d     Check if any values in that are truthy
è           Count how many items in that mapping are true

```

By the end, this will map the array
`[1, 3, 9, 26, 66, 150, 313, 610]` to `[true, true, true, true, true, true, false, false]`,
which contains `6` `true`s.

## Previous 10 byte version

```
@=ä-)e¥0}a

```

Try it online!

# Answer
> 4 votes
# Java 8, ~~191 + 58 = 249~~ ~~198~~ 140 bytes.

Thanks PunPun1000 for 51 bytes.
Thanks Nevay for 58 bytes.

```
int f(int[]a){int x=a.length-1,b[]=new int[x];for(;x-->0;)b[x]=a[x+1]-a[x];return java.util.Arrays.stream(a).distinct().count()<2?0:1+f(b);}

```

Try it Online!

Try it Online (198 byte version)

So, this is my first time posting here in PPCG (and the first time ever doing a code golf challenge). Any constructive criticism is welcome and appreciated. I tried to follow the guidelines for posting, if anything's not right feel free to point it out.

Beautified version:

```
int f(int[] a) {
    int x = a.length - 1, b[] = new int[x];
    for (; x-- > 0;) {
        b[x] = a[x + 1] - a[x];
    }
    return java.util.Arrays.stream(a).distinct().count() < 2 ? 0 : 1 + f(b);
}

```

# Answer
> 3 votes
# APL (Dyalog Classic), ~~22~~ 17 bytes

```
{1=≢∪⍵:0⋄1+∇2-/⍵}

```

Try it online!

Thanks to @ngn for -5 bytes!

## How?

* `{ ... }`, the function
* `1=≢∪⍵:0`, if every element is equal in the argument, return `0`
* `1+∇2-/⍵`, otherwise, return 1 + `n` of the differences (which is `n-1`, thus adding one to it gives `n`)

# Answer
> 3 votes
# Haskell, 46 bytes

```
g l|all(==l!!0)l=0|0<1=1+g(zipWith(-)l$tail l)

```

this simply recurses - `zipWith(-)l$last l` is the difference list of `l`. and `g` is the function that answers the question.

# Answer
> 3 votes
# Java (OpenJDK 8), ~~98~~ 94 bytes

```
a->{int o=0,i,z=1;for(;z!=0;o++)for(i=a.length-1,z=0;i>o;a[i]-=a[--i])z|=a[o]^a[i];return~-o;}

```

Try it online!

# Answer
> 3 votes
# Kotlin, 77 bytes

first post, tried to edit last answer on kotlin 2 times ;D

```
{var z=it;while(z.any{it!=z[0]})z=z.zip(z.drop(1),{a,b->a-b});it.size-z.size}

```

took testing part from @jrtapsell

TryItOnline

# Answer
> 2 votes
# Jelly, 7 bytes

```
IÐĿEÐḟL

```

Try it online!

# Explanation

```
IÐĿEÐḟL  Main link
 ÐĿ      While results are unique (which is never so it stops at [])
I        Take the increments, collecting intermediate values # this computes all n-th differences
    Ðḟ   Filter out
   E     Lists that have all values equal (the first n-th difference list that is all equal will be removed and all difference lists after will be all 0s)
      L  Take the length (this is the number of iterations required before the differences become equal)

```

-1 byte thanks to Jonathan Allan

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

```
f=a=>+(b=a.slice(1).map((e,i)=>e-a[i])).some(e=>e)&&1+f(b)

```

# Answer
> 2 votes
# Python 2, 65 bytes

*-7 bytes thanks to Jonathan Allan.*

```
f=lambda l,c=1:any(l)and f([j-i for i,j in zip(l,l[1:])],c-1)or-c

```

Try it online!

# Answer
> 2 votes
# 05AB1E, 7 bytes

```
[DË#¥]N

```

Try it online!

**Explanation**

```
[         # start loop
 D        # duplicate current list
  Ë       # are all elements equal?
   #      # if so, break
    ¥     # calculate delta's
     ]    # end loop
      N   # push iteration counter

```

# Answer
> 2 votes
# Haskell, ~~66~~ ~~61~~ 60 bytes

```
z=(=<<tail).zipWith
f=length.takeWhile(or.z(/=)).iterate(z(-))

```

Try it online!

*Saved 5 bytes thanks to Christian Sievers*

*Saved 1 byte thanks to proud-haskeller*

`iterate(z(-))` computes the differences lists.

`or.z(/=)` tests if there are non equal elements in those lists.

`length.takeWhile` counts the differences lists with non equal elements.

# Answer
> 2 votes
# Dyalog APL, 19 bytes

```
≢-1+(≢2-/⍣{1=≢∪⍵}⊢)

```

Explanation:

```
≢                      length of input
 -1+(             )    minus 1+
     ≢                 length of
      2-/              differences between elements
         ⍣             while
          {1=≢∪⍵}      there is more than 1 unique element
                 ⊢     starting with the input

```

# Answer
> 2 votes
# , 21 bytes

```
#1_(~&/1_=':)(1_-':)\

```

This works in k, but not in oK, because oK's while loop runs before checking the condition (as opposed to first checking the condition, and then running the code). Therefore, in oK, the `1 1 1 1 1` example will not work properly.

Try oK online!

Explanation:

```
   (        )       \ /while(
    ~&/               /      not(min(
       1_=':          /              check equality of all pairs))) {
             (1_-':)  /    generate difference list
                      /    append to output }
#1_                   /(length of output) - 1

```

# Answer
> 2 votes
# Japt, 7 bytes

Same approach (but independently derived) as Justin with a different implementation.

```
£=äaÃèx

```

Test it

---

## Explanation

Implicit input of array `U`.

```
£   Ã

```

Map over each element.

```
äa

```

Take each sequential pair (`ä`) of elements in `U` and reduce it by absolute difference (`a`).

```
=

```

Reassign that array to `U`.

```
èx

```

Count (`è`) the number of sub-arrays that return truthy (i.e., non-zero) when reduced by addition.

# Answer
> 1 votes
# TI-Basic, 19 bytes

```
While max(abs(ΔList(Ans
ΔList(Ans
IS>(A,9
End
A

```

By default, variables start at zero. Also, never thought I'd be using `IS>(` for anything useful.

# Answer
> 1 votes
# Pyth, 15 bytes

```
W.E.+Q=.+Q=hZ)Z

```

**Verify all the test cases.**

# How?

### Explanation #1

```
W.E.+Q=hZ=.+Q)Z   ~ Full program.

W                 ~ While...
 .E.+Q            ~ ... The deltas of Q contain a truthy element.
      =hZ         ~ Increment a variable Z, which has the initial value of 0.
         =        ~ Transform the variable to the result of a function applied to itself...
          .+Q     ~ ... Operate on the current list and deltas.
             )Z   ~ Close the loop and output Z.

```

# Answer
> 1 votes
# C# (.NET Core), ~~70~~ 69 + 18 bytes

*-1 byte thanks to Kevin Cruijssen*

```
g=a=>i=>a.Distinct().Count()>1?g(a.Zip(a.Skip(1),(y,z)=>y-z))(i+1):i;

```

Must be given 0 when calling to operate correctly. Also included in byte count:

```
using System.Linq;

```

Try it online!

Explanation:

```
g = a => i =>                      // Function taking two arguments (collection of ints and an int)
    a.Distinct()                   // Filter to unique elements
    .Count() > 1 ?                 // If there's more than one element
        g(                         //     Then recursively call the function with
            a.Zip(                 //     Take the collection and perform an action on corresponding elements with another one
                a.Skip(1),         //         Take our collection starting at second element
                (y, z) => y - z    //         Perform the subtraction
            )
        )(i + 1)                   //     With added counter
        : i;                       // Otherwise return counter

```

Iterative version 84 + 18 bytes:

```
a=>{int i=0;for(;a.Distinct().Count()>1;i++)a=a.Zip(a.Skip(1),(y,z)=>y-z);return i;}

```

Try it online!

# Answer
> 1 votes
## Clojure, 62 bytes

```
#(loop[c % i 0](if(apply = c)i(recur(map -(rest c)c)(inc i))))

```

Nicely `=` can take any number of arguments, and a single argument is identical to "itself". `(apply = [1 2 3])` gets executed as `(= 1 2 3)`.

# Answer
> 1 votes
# Vyxal, 6 bytes

```
⁽¯İ~aL

```

Try it online!

Explanation:

```
⁽¯      # Single element lambda that gets the differences
  İ     # Apply that and collect results until no change
   ~    # Filter by:
    a   #   Any truthy?
     L  # Get the length of those

```

# Answer
> 1 votes
# , 21 18 bytes

```
2#@(}.~.)2-/\^:a:]

```

Try it online!

*-3 thanks to rdm!*

# Answer
> 0 votes
# Perl 5, 83 + 1 (-a) = 84 bytes

```
sub c{$r=0;$r||=$_-$F[0]for@F;$r}for(;c;$i=0){$_-=$F[++$i]for@F;$#F--}say y/ //-$#F

```

Try it online!

Input as a list of numbers separated by one space.

# Answer
> 0 votes
# Pyke, 11 bytes

```
W$D}ltoK)Ko

```

Try it here!

# Answer
> 0 votes
# Kotlin, 83 bytes

```
{var z=it
var c=0
while(z.any{it!=z[0]}){c++
z=(0..z.size-2).map{z[it+1]-z[it]}}
c}

```

## Beautified

```
{
    // Make input mutable
    var z=it
    // Count for returning
    var c=0
    // While the array is not identical
    while (z.any { it != z[0] }) {
        // Increment count
        c++
        // Update list to differences
        z = (0..z.size-2).map { z[it+1] - z[it] }
    }
    // Return count
    c
}

```

## Test

```
var n:(List<Int>)->Int =
{var z=it
var c=0
while(z.any{it!=z[0]}){c++
z=(0..z.size-2).map{z[it+1]-z[it]}}
c}

data class TestData(var input: List<Int>, var output: Int)

fun main(args: Array<String>) {
    val items = listOf(
        TestData(listOf(1,2,3,4,5,6,7,8,9,10), 1),
        TestData(listOf(1,4,9,16,25,36), 2),
        TestData(listOf(1,2,1), 2),
        TestData(listOf(1,1,1,1,1,1,1,1,1), 0),
        TestData(listOf(1, 3, 9, 26, 66, 150, 313, 610), 6)
    )

    val fails = items.map { it to n(it.input) }.filter { it.first.output != it.second }

    if (fails.isEmpty()) {
        println("Test passed")
    } else {
        fails.forEach {println("FAILED: $it")}
    }
}

```

TryItOnline

# Answer
> 0 votes
# Pyth, 10 bytes

```
tf!t{.+FQt

```

If we can index from 1, we can save a byte by removing the leading `t`.

Try it Online

Explanation

```
tf!t{.+FQt
 f        T  Find the first (1-indexed) value T...
     .+FQt   ... such that taking the difference T - 1 times...
  !t{        ... gives a set with more than one value in it.
t            0-index.

```

# Answer
> 0 votes
# Swift 4, 90 bytes

```
func f(_ a:[Int])->Int{return a.contains{$0 != a[0]} ?f(zip(a, a.dropFirst()).map(-))+1:0}

```

Alternative, closure-based implementation:

```
var f: ((_ input: [Int]) -> Int)!
f = {a in a.contains{$0 != a[0]} ?f(zip(a, a.dropFirst()).map(-))+1:0}

```

test cases:

```
let testcases: [(input: [Int], expected: Int)] = [
    (input: [1,2,3,4,5,6,7,8,9,10],           expected: 1),
    (input: [1,4,9,16,25,36],                 expected: 2),
    (input: [1,2,1],                          expected: 2),
    (input: [1,1,1,1,1,1,1,1,1],              expected: 0),
    (input: [1, 3, 9, 26, 66, 150, 313, 610], expected: 6),
]

for (caseNumber, testcase) in testcases.enumerated() {
    let actual = f(testcase.input)
    assert(actual == testcase.expected,
        "Testcase #\(caseNumber) \(testcase.input) failed. Got \(actual), but expected \(testcase.expected)!")
    print("Testcase #\(caseNumber) passed!")
}

```

# Answer
> 0 votes
# Factor, 58 bytes

```
[ 0 swap [ tuck all-eq? ] [ 1 + swap differences ] until ]

```

Try it online!

# Answer
> 0 votes
# Ruby, 55 bytes

```
F=->a,i=0{a.uniq[1]?F[a.each_cons(2).map{_2-_1},i+1]:i}

```

Attempt This Online!

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