title: Significant Whitespace: Robbers

text:
# Question
Title: Significant Whitespace: Robbers
**This is part of a Cops and Robbers challenge. Go here for the cops' part.**

For the purpose of this challenge, we'll define **whitespace** as *only* linefeeds (0x0A) and spaces (0x20). Note that most languages and regex flavours consider many other characters as whitespace as well, both inside and outside the ASCII range so you might not be able to make use of the corresponding built-ins.

## The Robbers' Challenge

A cop's answer can be cracked by transforming it into a valid program or function (in the chosen language), which performs the task of removing whitespace from an input string, by inserting whitespace into the code. For example if you received the following input:

```
H e l l o,
 W o r l  d!

```

The program should output

```
Hello,World!

```

After inserting whitespace, the byte count of the solution must not exceed the byte count stated in the cop's answer. You don't have to find the exact same solution as the cop intended, as long as yours is valid by the above constraints.

If you manage this, post an answer with the solution, linking to the cop's answer, and leave a comment on the cop's answer linking back to yours.

The robber who cracks the most cop answers wins. Ties are broken by the sum of sizes of the cracked cop answers (in favour of the robber who cracks longer submissions).

Each cop answer can only be cracked once, and of course, you're not allowed to crack your own answer. If the cop's answer turns out to be invalid before or after being cracked, it is not counted towards the robber's score.

# Answer
## Haskell, 100 bytes, by Laikoni

```
main=interact$id doid lines id words
doid oi d o id=do
 iddoid<-do oi id
 oid<-do o iddoid
 do d oid

```
> 8 votes

# Answer
# \>\<\>, 40 bytes, by DanTheMan

```
v <<
i/\
:=
:
:a?
0/>/
1?o
-=
="
?
;"
>^

```

Really fun to work out.

Try it on \>\<\>language
> 7 votes

# Answer
# JavaScript ES6, 199 bytes by Arnauld

```
s=>eval(atob`ISYgJiAtOkI8Qk97BRBeaxZFShoUZSsiOGkMenNy`.replace(/./g,(c,i)=>String.fromCharCode(c.charCodeAt()^(k+="     S    e c  r   e t     C    o   d  e   ".split(/\w/)[i%11].length)),k=0)).join``

```

I realized the splitting `"SecretCode"` meant I was looking for 11 numbers that summed to (I assumed) 33. This is a stars and bars problem where the number of spaces are the stars and the letters in `"SecretCode"` were the bars. I did the math to see how many combintations there were to try (1,917,334,783 combinations) and decided to just brute force it, took all day.

There's probably a smarter way to have gone about it, for instance noticing that `k` has to be `33` and `66` for index 10 and 21 respectively, but I'm lazy.
> 7 votes

# Answer
# C, 475 bytes by rexroni

```
#include<unistd.h>
#define a char
#define b *
#define c write
#define d stdin
#define e stdout
#define f read
#define g (
#define h )
#define i while
#define j if
#define k 0
#define l &
#define m ,
#define n =
#define o ;
#define p 1
#define gpml ml h
#define abo
#define ml d m p
#define jg d o abo
#define lb abo d
#define gf h abo c
#define jgm b e n
#define pml f g
#define gpm lb
int main(){a jg a jgm l jg i g pml k m l gpml h j g d!=' '&&gpm!='\n'gf g p m l gpml o}

```

I might start using some of these defines :)

After the pre-processor the code looks something like this:

```
int main(){
    char stdin;
    char *stdout = &stdin;
    while(read(0, &stdin, 1))
        if(stdin !='' && stdin!='\n')
            write(1, &stdin, 1);
}

```
> 6 votes

# Answer
## Ruby, 86 bytes + 1 flag = 87 by histocrat

```
eval"( T $ }{(! // ; : 67 8 ? 32. && )".gsub(/ |(.)/){$1&&$&.ord.^($'.count(' ')).chr}

```

This was really fun, each character in the string passed to `eval` is replaced with the character code (`ord`) XORed `^(...)` against the number of remaining spaces in the string. The resultant code is:

```
$_.tr!(''<<32<<10,'')

```
> 5 votes

# Answer
# RprogN, by Ataco

This appears to do the trick

```
' ' ` R
"
" ` R

```
> 4 votes

# Answer
# V, 37 bytes, by DJMcMayhem

```
O     VrS200@"kIi|D@"A üî|D@"

```

Unprintables:

```
O     <esc>Vr<C-a>S200<esc>@"kIi<C-v><C-v><esc>|D@"<esc>A üî<esc>|D@"

```

TryItOnline

The `ü` really threw me for a loop, I kept expecting both it and `î` to be commands.

```
O                 # Insert 5 spaces above this line
Vr<C-a>           # Change them all to <C-a>
S200<esc>         # Replace the line with 200
@"                # Play back the 5 <C-a>'s, 200 -> 205
k                 # ????
Ii<C-v><C-v><esc> # insert "i<C-v>" so our line is now "i<C-v>205"
|D@"<esc>         # Delete the line and then run it, which inserts "Í" (ASCII 205)
A üî<esc>         # Append " üî" so our line is "Í üî"
|D@"              # Delete the line and run it

```

`Í üî` in V translates to `:%s/ \|\n//g` in vim, which globally removes all whitespace. The `Í` command is on the wiki, and the `ü` and `î` are `|` and `n` respectively with their high bit set
> 4 votes

# Answer
# C, 140 bytes by betseg

```
#include<stdio.h>
int main(){int a=getchar();while(a!=EOF){//\a=getchar();
if(a!=10&&a!=32)//\\putchar(a^10^32);
putchar(a);a=getchar();}}

```

(I also hope I'm doing this right.)
> 3 votes

# Answer
# MATL, 22 bytes by Luis Mendo

Though I can't be sure why, this seems to work

```
t' @ * 'dm1e5%M
dw%Y
(

```

I'll have to see if I can work out what it's doing. I figured that the comments had to have line feeds after them and then it was just a matter of getting the spaces in the correct spots.
> 3 votes

# Answer
# MATL, ~~22~~ 21 bytes by Luis Mendo.

Finally... MickyT cracked it while I was writing an explanation, so his answer is the "valid" one. I posted this anyway, in accordance with this meta post.

---

`M` and `Y` are unnecessary and are commented out. It's enough to add 4 whitespace characters, not 5.

```
t' @ *'dm1e5%M
dw%Y
(

```

This is equivalent to the more compact:

```
t' @ *'dm7dw(

```

**Partial explanation:**

```
         % Implicit input
t        % Duplicate input
' @ *'   % String with ASCII-values [32   64   32   42]
d        % diff, giving [32  -32   10], 32 is space, 10 is newline
m        % ismember, checking if the character is 32 or 10
1e5      % 10000, but could just as well be 7
d        % Taking the diff of the scalar 1e5, returning an empty matrix []
w        % Swap stack in order to use ( below
(        % Equivalent to x(y)=[], where x is the input string, and y is the logical
         % vector found using ismember (m)
         % Implicit output

```
> 3 votes

# Answer
# Whitespace, 68 bytes, by Ephphatha

* 68 bytes, 21 tabs: `LSSLSSTLSLSTLTSTTTSSSTSTSLTSSTSLSLTSLSSSTSTTSLTSSTLTSLSSLTTTTLSSLSLL`
* 71 bytes, 21 tabs: `LSSLSSLTLTSSSLTTTSSSTSTSLTSSTLTSLSSLTTTSSSTSSSSSLTSSTLTSLSSLTTTTLSSLSLL`
* 72 bytes, 21 tabs: `LSSLSSSTTTTTTLSLSTLTSTTTSLSSSSTSTSLTSSTLTSLSLSSSSTSSSSSLTSSTLTSLTLSSLSLL`
* 65 bytes, 15 tabs (too short): `LSSLSSLSLSTLTSTTTSLSSSSTSTSLTSSTLTSLSLSSSSTSSSSSLTSSTLTSLTLSSLSLL`

Since Whitespace only consists of space, tab, and LF characters (here annotated as `S`, `T`, and `L`), the entire program needs to be reconstructed, with the only constraint being that it have exactly 21 tabs to match the cops submission.

I start with a working program, but it's too short and needs 6 more tabs. It beats the target by 9 bytes, so I could have submitted this as another cop program, but I don't think it's interesting enough to warrant a second Whitespace answer.

```
# 65 bytes, 15 tabs
loop:                        # LSSL
    0 dup readc retrieve     # SSL SLS TLTS TTT
    dup 10 - jz loop         # SLS SSSTSTSL TSST LTSL
    dup 32 - jz loop         # SLS SSSTSSSSSL TSST LTSL
    printc                   # TLSS
    jmp loop                 # LSLL

```

The simplest way to add more tabs would be to use 63 (STTTTTT) as the address for reading characters instead of 0 (empty).

```
# 72 bytes, 21 tabs
loop:                        # LSSL
    63 dup readc retrieve    # SSSTTTTTTL SLS TLTS TTT
    …

```

That only adds bytes, though. If we `retrieve` before every usage, we can eliminate three `dup`s, which have no tabs (SLS). (This is also the only of these versions without a stack memory leak.)

```
# 71 bytes, 21 tabs
loop:                        # LSSL
    0 readc                  # SSL TLTS
    0 retrieve 10 - jz loop  # SSL TTT SSSTSTSL TSST LTSL
    0 retrieve 32 - jz loop  # SSL TTT SSSTSSSSSL TSST LTSL
    0 retrieve printc        # SSL TTT TLSS
    jmp loop                 # LSLL

```

We can do better. If we compound the subtractions, 32 (STSSSSS) can be replaced with 22 (STSTTS), which gains 2 tabs and saves 1 byte. Then, the second branch doesn't `dup` and the print would obtain an unmodified value with `0 retrieve`, which gains 3 tabs and adds 3 bytes. For the last tab, a negative sign is added to one of the zeros.

```
# 68 bytes, 21 tabs
loop:                        # LSSL
    -0 dup readc retrieve    # SSTL SLS TLTS TTT
    10 - dup jz loop         # SSSTSTSL TSST SLS LTSL
    22 - jz loop             # SSSTSTTSL TSST LTSL
    0 retrieve printc        # SSL TTT TLSS
    jmp loop                 # LSLL

```

These programs require an implementation, that allows the sign to be omitted for zero, so will not work with the reference interpreter, which TIO uses.

For this solution and others in Whitespace, see ws-challenges.
> 3 votes

# Answer
## C#6, 201 bytes, by milk

```
using System.Linq;
_=>string./**/
#if trueJoin
(/*"*//*/""/**//*/"*/",
#else
Concat(//*/,
#endif
from m in" "let p=$@"{@"
"[1]}"from i in(_.Replace(p,@""))where!new[]{p[0]^32^10}.Contains(i)select@i);

```

repl.it demo

`trueJoin` is not defined, so only `string.Concat()` remains.
`p` is `"\n"`. `p[0]^32^10` is space. It would have been (a bit) more difficult if it's `p[0]^42` or other similar constants.
> 2 votes

# Answer
# Befunge-98, 65 bytes by ninjalj

```
~v       >#@
 >::':'0--\'[';--!8v1+!
*1+j  !j,v         >#@

```

Try it online!

This was a lot of fun. I deduced that since there are few direction-changing commands and no `^<[]?x` or similar, it has to use wrapping. I then wrote a Python script to help with getting the spacing right for the `j`'s.

The code works by taking input (`~`) and duplicating it twice (`::`). It then subtracts 10 (`':'0` or `ord(':') - ord('0')`) and 32 (`'[';` or `ord('[') - ord(';')`). Then, the second result is logically negated (1 if was space, 0 otherwise) and an 8 is pushed.

Now comes the part that needed figuring out what to skip. The `1+!` is skipped by continuing to the next line. `#` skips the `@`. The logically negated result (0 or 1) is multiplied by the 8, and 1 is added.

The code then jumps that many (i.e. 1 or 9) spaces plus one extra as the IP moves. If the character wasn't a space it ends up at the `!`. The character code minus 10 is logically negated (1 if was newline, 0 otherwise). `j` then skips nothing, and the print (`,`) is called and the loop resumes by wrapping vertically.

If the character was a space, the bottom line loops again with `32, 22` as the bottom of stack. The first `j` jumps 705 spaces. Then the line loops a third time. If there are more than two 10's left on the stack (the code only leaves those), the first `j` jumps 100 spaces and the loop repeats. Otherwise, the first `j` jumps to the `!`, a zero is negated, the second `j` jumps over the print and the program continues.

I managed to golf it down to 59 bytes.
> 2 votes

# Answer
# reticular, 43 bytes, by Conor O'Brien

```
ISBqv<>>$$4j
E :d/v$v?
c+91d/ v?E
;!?l$/o $

```

Try it online!

This was more difficult for me than it should have been because I was too stupid to find the documentation and ended up having to guess how some of the commands worked. So some of this explanation may not be entirely accurate, but this was my basic understanding of the code.

```
I               Push all the input on to the stack as a string
 S              Convert it into a character array.
  B             Turns that array into individual characters on the stack.
   q            Reverse the stack so the first letter is on top.
    v           Move down...
    /           ...and turn left.
E :d            Duplicate the value and test if equal to space.

       v?       If it is a space we move down until we wrap to the top.
       >$$      Drop the test result and the space.
          4j    Jump over the next 4 commands (having wrapped to the start).
    v           Bringing us back to the first down arrow, ready to test the next char.

     v$         If it wasn't a space, drop the test result and move down.
c+91d/          Turn left and push a newline (char 10) on to the stack.
       v?E      If equal, we go down, following the same path as with the space.

     /          If not equal, turn down.
   l$/          Then turn left, drop the test result, and push the stack size.
;!?             If zero (the stack is empty) we terminate.
        o$      Otherwise wrap around, drop the stack size, and output the char.
     /          Then turn down wrapping around to the top of the program.
    v<          Then turn left and down to start the process from the beginning again.

```
> 2 votes

# Answer
# Vyxal, 18 bytes cracks emanresu

```
#ȧ
‛  (#
FṘ₴#
Ṙ‛

```

Try it Online!
> 2 votes

# Answer
# Vyxal 3, 12 bytes cracks Alan Breadel

```
#?“" "₉r""₉r

```

Try it Online! Alan didn’t say how much white space was needed, so I took a wild guess and added one to the string literal and it worked
> 2 votes

# Answer
# C#, 159 bytes by LethalCoder

```
using System.Linq;s=>string.Join("",string.Join("",s.Split(@"
".Replace(new string((char)0x0D,1),"").ToCharArray())).Select(c=>c+""!=""?c+"":"").ToArray());

```

repl.it

The string at the end of line 1 is `" \n"` (space+newline).

```
/*Func<string, string> Lambda =*/ s =>
    string.Join("",                                                           // No-op
    string.Join("",                                                           // Join (without whitespace)
        s.Split(@" \n".Replace(new string((char)0x0D,1),"").ToCharArray())    // Split on whitespace
    ).Select(c=>c+""!=""?c+"":"").ToArray());                                 // No-op

```
> 1 votes

# Answer
# Minkolang v0.15, 88 bytes by Kritixi Lithos

```
$oI[dd" "=$r'10'=1J,? 1R]r$O3.14
$$$
Cdollars             >
$$$
Ceverywhere           >x

```

Explanation

```
                               # Layer 1
$o                             # input chars onto stack
  I                            # stack length pushed to stack
   [                    ]      # loop popped TOS times (length of string)
    dd                         # duplicate, duplicate
      " "                      # push space to stack
         =                     # equality check
          $r                   # swap
            '10'               # number 10 to stack (LF char)
                =              # equality
                 1J            # or
                   ,           # not
                    ?          # if true jump next
                               # drop to layer 2
                      1R       # rotates the stack 1 time
                         r     # reverse the stack
                          $O   # output the stack
                             . # stop
$$$                            # Layer 2
                     >         # shift right and then drop to layer 3
$$$                            # Layer 3
                      >x       # shift right, pop char off stack and drop to Layer 1 (end loop)

```
> 1 votes

---
Tags: string, cops-and-robbers, whitespace
---


title: Is it a valid ARM immediate value?

text:
# Question
Title: Is it a valid ARM immediate value?
## Exposition

In this challenge, I am talking about ARM assembly language. ARM is a 32-bit RISC processor; I'll use instruction set up to architecture v6.

To load a constant ("immediate") value into a register, use the `MOV` instruction:

```
MOV r8, #42

```

To load negative values, use the `MVN` instruction, with a bit-complement of the operand:

```
MVN r8, #41

```

You can't load any 32-bit value with this instruction. Acceptable values are:

* Any 8-bit value: 0...255
* Any 8-bit value, rotated right by an even number of bits, 2...30
* A bit-complement of any value as described above (a good assembler will accept such operands and turn `MOV` into `MVN`)

## Challenge

Make code which determines if the given input is a valid operand for a `MOV` instruction.

### Input

A number in the range 0...232-1 or -231...231-1, whatever is easier.

If you represent the number as a string, use decimal notation.

### Output

True or false, as usual.

### Examples

(some of them taken from this nice site with explanations).

True:

```
0x000000FF
0xffffd63f
0xFF000000
0b1010101100000000 (8 arbitrary bits, followed by even number of zeros)
0b11110000000000000000000000001111 (11111111 rotated right by 4 bits)

```

False:

```
0x000001FE
0xF000F000
0x55550000
0xfffffe01
0b10101011000000000 (8 bits but followed by odd number of zeros)
0b11110000000000000010000000001111 (too many spread-out 1-bits)

```

# Answer
# Rust, ~~52~~ 49 bytes

```
|n|(0..16).any(|i|(n<<33^n<<32^n*2^n)<<i*2>>41<1)

```

Attempt This Online!

A closure that takes an unsigned 32-bit value of type `u64` and returns a bool. -3 thanks to corvus\_192.

* A 32-bit value `n` is acceptable
* \\$\Leftrightarrow\\$ `n` has a run of 24 equal bits at an even offset, when viewed cyclically
* \\$\Leftrightarrow\\$ `n | n << 32` has a run of 24 equal bits at an even offset, between 0 and 30 inclusive
* \\$\Leftrightarrow\\$ `(n | n << 32) ^ ((n | n << 32) << 1)` has a run of 23 zero bits at an even offset between 0 and 30 inclusive, counting from the high end
* \\$\Leftrightarrow\\$ `n<<33^n<<32^n<<1^n` has a run of 23 zero bits at an even offset between 0 and 30 inclusive, counting from the high end
* \\$\Leftrightarrow\\$ `(n<<33^n<<32^n<<1^n)<<i>>41` is zero for some even `i` between 0 and 30 inclusive
> 12 votes

# Answer
# Charcoal, 21 bytes

```
Ｎθ⊙ 3№×²◧⍘θ 123¹⁶×¹²ι

```

Attempt This Online! Will accept input in decimal by default, but also hex with `0x` prefix and binary with `0b` prefix. Outputs a Charcoal boolean, i.e. `-` for valid, nothing if not. Explanation:

```
Ｎθ                      First input as a number
    3                   Literal string ` 3`
  ⊙                     Any character satisfies
          θ             Input number
         ⍘              Converted to custom base
            123         Literal string ` 123`
        ◧               (Left) Padded to length
               ¹⁶      Literal integer `16`
      ×                 Repeated by
       ²                Literal integer `2`
     №                  Contains
                    ι   Current character
                 ×      Repeated by
                  ¹²    Literal integer `12`

```
> 6 votes

# Answer
# Go, ~~157~~ 147 bytes

```
import."math/bits"
func f(n uint32)(r bool){F:=uint32(0xFF)
for k:=2;k<31;k+=2{j:=RotateLeft32(n,k)
if r=j<=F||^j<=F;r{return}}
return n<=F||^n<=F}

```

Attempt This Online!

Input is an unsigned 32-bit integer.

* -10 bytes: use a comparison rather than an equality and bitwise-and.

### Explanation

```
import."math/bits"
func f(n uint32)(r bool){
F:=uint32(0xFF)
for k:=2;k<31;k+=2{          // rotation check
j:=RotateLeft32(n,k)         // rotate left an even number of times
if r=j<=F||^j<=&F;r{return}} // if 8-bit or its complement is 8-bit, return true
return n<=F||^n<=F}          // return if 8-bit or its complement is 8-bit

```

## Go, 121 bytes

```
func f(n,k uint32)int{F:=uint32(0xFF)
if n&^F>0{k--
if k<1{return 0}
j:=n*4|n>>30
if k&1>0{j=^n}
return f(j,k)}
return 1}

```

Attempt This Online!

A direct port of @Arnauld's JS answer.
> 4 votes

# Answer
# Python, 52 bytes

```
f=lambda n:n>4**32or 0<n%~-4**16>>8<8**8-1and f(n*4)

```

Attempt This Online!

Returns False for True and True for False.

## How?

Uses `mod 0xffffffff` to get from a linear left shift to a cyclic left shift. Advantages of linear being 1) Python actually has it. 2) easier stopping criterion.
> 4 votes

# Answer
# ARMv2, ~~32~~ 28 bytes

Input is in `R0`, output is in `R1` which is zero if the input is an invalid constant. `CMN` trick stolen from Notlikethat's answer to the Stack Overflow question linked by @PeterCordes.

```
VALID:  MOV R1, #-16
LOOP:   MOV R0, R0, ROR#2
        CMP R0, #256
        CMNCC R0, #256        @ compare with -256, predicated on Carry Clear
        ADDSCC R1, R1, #1     @ Add and Set flags if Carry Clear
        BCC LOOP
        MOVS R15, R14         @ return

```

This is ARM mode so each instruction is 4 bytes, unlike Thumb or Thumb 2.
`movs r15, r14` copies the return address to the program counter, `mov pc, lr`, returning from the function like `bx lr` in modern ARM code.

Alternative version using @Bubbler's trick of XORing the input with itself rotated left one bit, which still works with `CMP` (but not my original 32-byte `TST` version, which is why I didn't use that approach at the time). Input is in `R0`, output is in `ZF` which is set or `R0` which is zero if the input is an invalid constant.

```
VALID:  EOR R1, R0, R0, ROR#31
        MOV R0, #-16
LOOP:   MOV R1, R1, ROR#2
        CMP R1, #512
        ADDSCC R0, R0, #1     @ Add and Set flags if Carry Clear
        BCC LOOP
        MOV R15, R14          @ return

```
> 4 votes

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

```
f=n=>++i&31&&n>>8==n>>31|f(n>>>2|n<<30);i=0

```

Try it online!

Note: This function will not be reusable after about 248 invokes. I would argue that should be fine according to the spirit of code-golf though. And fix the limit may cost 2 more bytes.
> 2 votes

# Answer
# Retina, 101 bytes

```
.+
$.(23283064365386962890625**
16{`.+$
$.(4**
)r`(.?)(.{1,32})$
$.($1*)¶$2
A`$
¶

$
$`
0`0{12}|3{12}

```

Try it online! Link includes test cases. Outputs `1` for valid, `0` for invalid. Explanation:

```
.+
$.(23283064365386962890625**
16{`.+$
$.(4**
)r`(.?)(.{1,32})$
$.($1*)¶$2
A`$

```

Convert the input to 16 base `4` digits. (This method is required for very large integers or even for large integers where the traditional method would cause the process to run out of memory.)

```
¶

$
$`

```

Join the digits together and then duplicate the string.

```
0`0{12}|3{12}

```

Check for 12 repeated `0`s or `3`s. (If any non-zero output is acceptable, the `0`` can be removed to save two bytes.)
> 2 votes

# Answer
# 05AB1E, 17 bytes

```
4B16°+¦2×30S12×åà

```

Port of *@Neil*'s Charcoal answer, so make sure to upvote that answer as well.

Input as an integer.

Try it online or verify all test cases.

**Explanation:**

```
4B                # Convert the (implicit) input-integer to base-4
  16°             # Push 10**16
     +            # Add it to the base-4 number (as base-10 addition)
      ¦           # Remove the leading 1
       2×         # Repeat this string two times
         30S      # Push [3,0]
            12×   # Repeat both 12 times
               å  # Check if the earlier string contains a substring of 12 3s or 0s
                à # Check if either of the two is truthy
                  # (after which the result is output implicitly)

```
> 2 votes

# Answer
# Ada/GNAT, 152 bytes

```
type T is mod 2**32;function G(X:T;C:T:=0) return Boolean is (C<30 and then ((((X and 255)=X or (X or not 255)=X) or else G((X mod 4)*2**30+X/4,C+1))));

```

G is a recursive function that:

1. Takes a type T, which is a mod. Mod types are like Integers, except they wrap around when they overflow and you can do bitwise operations on them.
2. Defaults C to 0 and uses it to check for too many recursions. This was way fewer bytes than writing a loop structure, not just because of the verbose loop syntax in Ada but also because the inline subprogram syntax couldn't be usable with a loop. I picked 30 because it was no more bytes than more sensible values like 15 or 16 that I'd have to do more testing on.
3. Does bitwise logic between the input X and 255/not 255. I honestly didn't expect "not 255" to work, but as it turns out, this does a logical inverse as if it were a variable. These two comparisons basically enforce the rule that all the meaningful data must be within a range of eight contiguous bits. 255 being 00000000000000000000000011111111, and not 255 being 11111111111111111111111100000000.
4. Does the arithmetic equivalent of rotating by 2 and uses this with an incremented C to call its next iteration. There is a builtin for rotations, but using it required a with and a function call, so doing this turned out to be less verbose.
> 2 votes

# Answer
# JavaScript (ES6), 47 bytes

Returns **0** or **1**.

```
f=(n,m=~255)=>n&m&&~n&m?m%96&&f(n,m*4|m>>>30):1

```

Try it online!

### Commented

```
f = (          // f is a recursive function taking:
  n,           //   n = input
  m = ~255     //   m = mask, initialized to ~255 (note that this gives
               //   the signed value -256 rather than 0xFFFFFF00, which
               //   is important for the modulo 96 test)
) =>           //
n & m &&       // if n & m is not 0
~n & m ?       // and ~n & m is not 0:
  m % 96 &&    //   if m is not equal to 0x3FFFFFC0 (the last rotation
               //   which is the only one to be a multiple of 96):
    f(         //     do a recursive call:
      n,       //       pass n unchanged
      m * 4 |  //       rotate m by 2 positions to the left
      m >>> 30 //       (the result is still signed)
    )          //     end of recursive call
:              // else:
  1            //   success: return 1

```
> 1 votes

# Answer
# ARMv6M (Cortex-M0), 38 bytes

```
;@ Pre-UAL syntax
;@ bool isValidARMImm(int _X);
_isValidARMImm:
            TST R0,R0           ;@ test negative
            BPL 1f
                NEG R0,R0       ;@ convert to positive
1:
            TST R0,R0           ;@ test zero
            BEQ 3f              ;@ branch to true if zero
            MOV R1,R0           ;@ copy to work register
            MOV R2,#0x00        ;@ set shifted bit count to 0
2:
                LSR R1,#1       ;@ remove following 0 bits
                BCS 1f          ;@ end if 1 bit shifted in carry flag
                ADD R2,#0x01    ;@ count following 0 bits
                B 2b            ;@ loop
1:
            LSR R0,R2           ;@ shift out 0 bits
            UXTB R1,R0          ;@ unsigned byte extend
            CMP R0,R1           ;@ test (int)R0 == (byte)R1
            BEQ 3f              ;@ branch to true case if equal
                MOV R0,#0x00    ;@ false
                BX LR
3:
            MOV R0,#0x01        ;@ true
            BX LR

```

8 bytes can be saved by returning the result in the zero flag instead of R0.

```
_isValidARMImm_ZeroFlag:
            TST R0,R0           ;@ test negative
            BPL 1f
                MVN R0,R0       ;@ convert to positive
1:
            TST R0,R0           ;@ test zero
            BEQ 3f              ;@ branch to true if zero
            MOV R1,R0           ;@ copy to work register
            MOV R2,#0x00        ;@ set shifted bit count to 0
2:
                LSR R1,#1       ;@ remove following 0 bits
                BCS 3f          ;@ end if 1 bit shifted in carry flag
                ADD R2,#0x01    ;@ count following 0 bits
                B 2b            ;@ loop
3:
            LSR R0,R2           ;@ shift out 0 bits
            UXTB R1,R0          ;@ unsigned byte extend
            CMP R0,R1           ;@ test (int)R0 == (byte)R1
            BX LR

```
> 1 votes

# Answer
# Jelly, 17 bytes

```
+Ø%BḊṙ⁴ḶḤ¤;¬$ḄṂ<⁹

```

Try it online!

A monadic link taking an integer and returning 1 for valid and two for invalid.

## Explanation

```
+Ø%               | Add 2**32
   B              | Convert to binary
    Ḋ             | Remove first digit
     ṙ⁴ḶḤ¤        | Rotate left by each of (0 to 15 doubled)
          ;¬$     | Concatenate to binary not of this
             Ḅ    | Unbinary
              Ṃ   | Max
               <⁹ | < 256

```
> 1 votes

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


title: Different Way Forward

text:
# Question
Title: Different Way Forward
Given a list of integers produce a Forward Difference at a specified order/depth.

For the list of integers:

```
(10, 18, -12, 4, 8, -3, -5, 67, 9, 14)

```

The Forward Differences at the various orders/depths are:

```
0   10,   18,  -12,    4,    8,   -3,   -5,  67,  9,  14
1      8,  -30,   16,    4,  -11,   -2,   72, -58,  5
2       -38,   46,  -12,  -15,    9,   74, -130, 63
3           84,  -58,   -3,   24,   65, -204, 193
4            -142,   55,   27,   41, -269, 397
5               197,  -28,   14, -310, 666
6                 -225,   42, -324, 976
7                    267, -366, 1300
8                      -633, 1666
9                         2299

```

So with the input of

```
4, (10, 18, -12, 4, 8, -3, -5, 67, 9, 14)

```

You would return the list

```
(-142,   55,   27,   41, -269, 397)

```

## Input

The input can be via STDIN or function parameters.

An integer specifying the depth to return. This will be 0 to the length of the list minus 1

A list of integers to calculate the forward difference for

## Output

The output can be via STDOUT or returned by the function.

The forward differences for the specified depth as a list of integers

## Rules

Built in and 3rd Party functions that do this directly are not allowed.

Standard loophole restrictions apply.

Shortest code wins

# Answer
> 21 votes
## J, ~~15~~ ~~9~~ 7 bytes

Very easy. Takes depth and list as left and right arguments.

```
-~/\~&2

```

As an explicit definition without all the adverbial trickery, this reduces to

```
4 : '(2 -~/\ ])^:x y'

```
* `-~/\~&2 y` – The forwards difference of `y`.
* `x -~/\~&2 y` – The `x`-th forwards difference of `y`.

If I were to make a *serious* (i. e. non-golfed) definition of this function, I would probably do something like this:

```
(}. - }:) : ($:@[&0)

```

The monadic case computes the forward difference whereas the dyadic case computes the `x`-th forward difference.

Even simpler, but not exactly equal:

```
+/\inv

```

`+/\` yields a vector of the sums of the prefixes of the argument. `inv` (defined as `^:_1`) is a conjunction that inverses a verb. This works wherever J knows how to inverse a verb and for the case of `+/\`, J knows how to.

# Answer
> 15 votes
# Python, ~~61~~ 59 bytes

```
f=lambda n,L:n and f(n-1,[x-y for x,y in zip(L[1:],L)])or L

```

Here we perform the subtraction by zipping all but the last of the list with all but the first of the list. `zip(L[1:],L)` is equivalent to `zip(L[1:],L[:-1])`, due to `zip`'s nature of taking the minimum length of the two lists:

```
>>> zip([1,2,3],[4,5])
[(1, 4), (2, 5)]

```

---

An alternative that's just as long (Python 2 only):

```
f=lambda n,L:n and f(n-1,map(int.__sub__,L[1:],L[:-1]))or L

```

Unfortunately Python 2 doesn't cut off the end of the list, so I can't do `map(int.__sub__,L,L[1:])`. Annoyingly, Python 3 *does*, but `map` no longer returns a list so this ends up being a byte more (60 bytes):

```
f=lambda n,L:n and f(n-1,list(map(int.__sub__,L[1:],L)))or L

```

However, if we allow the input to be the depth followed by the list like `f(3, 2, 5, 6, 7, 5, 10, 25)` (i.e. depth 3 and list `[2, 5, 6, 7, 5, 10, 25]`), then this is **56 bytes**:

```
f=lambda n,*T:n and f(n-1,*map(int.__sub__,T[1:],T))or T

```

---

Here's another alternative that would really annoy anyone who saw this in production code (this one destroys the original list):

```
f=lambda n,L:n and f(n-1,[L[1]-L.pop(0)for _ in L[1:]])or L

```

# Answer
> 9 votes
# Mathematica ~~23 57~~ 23 bytes

Martin Büttner's suggestion, exploiting the listability of subtraction.

```
 Rest@#-Most@#&~Nest~##&

```

e.g.

```
Rest@# - Most@# &~Nest~## & @@ {{10, 18, -12, 4, 8, -3, -5, 67, 9, 14}, 4}

```

> {-142, 55, 27, 41, -269, 397}

---

`Rest@#-Most@#` carries out the subtraction that yields differences.

Nest performs said operation the specified number of times, operating always on the most recent list.

# Answer
> 7 votes
# Haskell, 40 34 bytes

```
n#l=iterate(zipWith(-)=<<tail)l!!n

```

Usage example: `4 # [10,18,-12,4,8,-3,-5,67,9,14]` which outputs `[-142,55,27,41,-269,397]`.

How it works: repeatedly calculate the difference between neighbor elements and store the intermediate results in a list. Take the `n`th element from this list.

Edit: @Zgarb found 6 bytes to save. Awesome!

# Answer
> 7 votes
# JavaScript (ES6), ~~52~~ 49 bytes

Simple recursive function, using `map` to scan the array and `slice` to drop the first element on each recursive call.

**Edit** 3 bytes saved, thanks @DocMax, really smart suggestion

```
F=(n,l)=>n?F(n-1,l.slice(1).map((a,k)=>a-l[k])):l

```

**Test** In Firefox/FireBug console

```
for(i=0;i<10;i++)console.log(F(i,[10, 18, -12, 4, 8, -3, -5, 67, 9, 14]))

```

> \[10, 18, -12, 4, 8, -3, -5, 67, 9, 14\]
> \[8, -30, 16, 4, -11, -2, 72, -58, 5\]
> \[-38, 46, -12, -15, 9, 74, -130, 63\]
> \[84, -58, -3, 24, 65, -204, 193\]
> \[-142, 55, 27, 41, -269, 397\]
> \[197, -28, 14, -310, 666\]
> \[-225, 42, -324, 976\]
> \[267, -366, 1300\]
> \[-633, 1666\]
> \[2299\]

# Answer
> 6 votes
# CJam, 15 bytes

```
l~{{_@-\}*;]}*p

```

Takes input as a CJam-style array and then the depth:

```
[10 18 -12 4 8 -3 -5 67 9 14] 4

```

and prints the result as a CJam-style array.

Test it here.

## Explanation

```
l~              "Read and eval input.";
  {         }*  "Repeat this block N times, which computes the forward differences.";
   {    }*      "Fold this block onto the list - this is quite an abuse of folding semantics.";
    _           "Duplicate the current element (for the use in the next difference).";
     @          "Pull up the other copy of the last element.";
      -         "Subtract.";
       \        "Swap the difference and the other copy of the current element.";
          ;     "Discard the last element.";
           ]    "Wrap everything in an array again.";

```

# Answer
> 5 votes
# Java, ~~122~~ 119 bytes

```
int[]a(int[]a,int b){if(b<1)return a;int e=a.length-1,c[]=new int[e],i=e;for(;i-->0;)c[i]=a[i+1]-a[i];return a(c,b-1);}

```

Example Usage: http://ideone.com/ALgYez

3 bytes thanks to Geobits :v )\>

# Answer
> 5 votes
## Python, ~~70~~ ~~68~~ ~~67~~ 59 bytes

```
f=lambda x,n:n and f([x[1]-x.pop(0)for i in x[1:]],n-1)or x

```

Non-golfed version before I went recursive:

```
def f(x,n):
    for j in range(n):
        for i in range(len(x)-1):
            x[i]=x[i+1]-x[i]
    return x[:-n]

```

# Answer
> 5 votes
## \>\<\>  ~~53~~  50 bytes

```
l:[2-&\~~]r1-:?!vr
&}-@:$/!?&:-1
:;!? &&  lo*84n~<

```

Usage: Prepopulate the stack (-v in python interpreter) with depth first, followed by the integers.

For example:

```
forward.fish -v 3 2 5 6 7 5 10 25

```

Returns

```
2 -3 10 3

```

Thanks to Sp3000 for the help.

# Answer
> 5 votes
# Prelude, ~~95~~ ~~92~~ ~~79~~ 78 bytes

```
?    (1-vv- # ) v  !
  ?     #   ^   #
?(1-)   1  (#)  1)(#)
  1   #(# ) 1  (#

```

Input format is

```
N
M
n_1
n_2
...
n_M

```

where `N` is the depth of the differences and `M` is the number of integers in the input. Adding `M` was necessary, because there's no way for Prelude to distinguish a `0` from the end of the input. Output is also as a newline separated list of integers. I had to assume the slightly adjusted Prelude spec we devised for this challenge, because standard Prelude reads integers as byte values, which makes it impossible to enter negative numbers. Essentially, this is the Python interpreter with an additional `NUMERIC_INPUT` flag.

For reference there are only ~~48~~ ~~38~~ 37 non-space characters - the rest was merely needed to align the code correctly.

## Explanation

In Prelude, each line is a separate "voice" that operates on its own stack. The program is executed column by column, where the separate voices are taken to operate "in parallel". All commands are single characters, and parentheses are Brainfuck-like loops (which are entered and repeated whenever the top of the stack is non-zero). Note that the vertical position of the closing parenthesis is irrelevant - putting it in a different voice still counts as matching with the most recent opening parenthesis, and the stack that is checked for the loop condition is always the voice where the `(` appeared. Now on to this program...

The program can basically be separated in into two parts. The bottom two lines are merely used for most of the loops in the program (except the main loop over `N`), passing `1`s back and forth. The top two lines contain the main loop and actual differencing. The following annotation has the code transposed, so I can annotate the individual columns:

```
? ?   # Read two integers. Read instructions are processed top to bottom, so the first voice
      # reads N and the third voice reads M.
  (   # Start a loop on the third voice. This loop will execute M times, reading the input list
      # and pushing M 1s onto the fourth voice - i.e. a unary representation of M.
 ?11  # Read an integer onto the second voice, push 1s onto the third and fourth voice.
  -   # Subtract the 1 from the third voice, decrementing M down to 0.
  )   # End of loop, if the third voice is not 0 yet, to back two columns.
(     # Start a loop on the first voice. This is the main loop and will execute N times. Each
      # iteration will compute the forward differences once and thereby shorten the list by one
      # element and also reduce the stack of 1s on the bottom voice by one.
1  #  # Push a 1 onto the first voice and pop a 1 from the last. Together with the next column,
      # this decrements both N and (the unary) M.
-  (  # Subtract the 1 from the first voice (decrementing N), and start a loop on the fourth
      # voice over whatever is left of M (the length of the resulting difference list). Note
      # that this column is *not* part of the loop, so the - on the first voice will only be
      # executed once. This loop builds the differences in reverse order on the first voice.
v#1#  # Pop a 1 from the fourth voice and push a 1 onto the third. This loops over M while
      # shifting its unary representation to the other stack. In addition, shift the top stack
      # element from the second to the first voice.
v     # Copy the next element from the second voice to the first, without popping.
-  )  # Subtract the two elements on the first voice and end the loop if the fourth voice is
      # empty. Note that his column *is* part of the loop.
  (   # Start a loop on the third voice. This is another loop over M, shifting the stack of 1s
      # back to the fourth voice, and reversing the differences by shifting them onto the
      # second.
#^#1  # As stated above, shift an element from the first to the second voice, a 1 from the
      # third to the fourth.
  )   # End the loop. After this point, we're back to the original situation, except that the
      # second voice has been replaced by its differences. The bottom stack element the
      # previous list is also still on that stack, but the decreasing loop lengths on the third
      # and fourth voices ensures that this element is never touched again.
)     # End the main loop when N has been reduced to 0.
   (  # Start another loop over the remaining list length, shifting and reversing the result.
v#1#  # Shift a 1 back to the third voice and an element from the second to the first voice.
  )   # End the loop. Note that this parenthesis is not on the same voice as the corresponding
      # opening parenthesis, but its exact position is irrelevant. Moving it to this voice
      # saves a byte.
  (   # Start one last loop over the length of the result.
! #   # Pop a 1 from the third voice while printing (and popping) one element of the result.
  )   # End the loop.

```

# Answer
> 5 votes
# R, ~~48 39 46~~ 44 bytes

Recursion!

```
function(x,y)if(x)Recall(x-1,diff(y)) else y

```
* `x` is the number of iterations to perform, and `y` is a vector of integers.
* `if(x)` is true as long as `x>0`.
* `Recall` calls the current function but with new arguments.
* `Diff` outputs the differences between consecutive list/vector elements.

Previous versions:

```
#does not work for x=0:
function(x,y){for(i in 1:x)y=diff(y);y}

#does not use diff function:
function(x,y){for(i in 1:x)y=y[-1]-head(y,-1);y}

y[-1]       is a list minus its first element
head(y,-1)  is a list minus its last element

```

# Answer
> 3 votes
# Python, ~~92~~ ~~87~~ 86 bytes

```
def a(b,c):
 if c<1:return b
 d=[];e=b[0]
 for f in b[1:]:d+=f-e,;e=f
 return a(d,c-1)

```

This is my first Python golf. Any suggestions will be appreciated :)

~~5~~ 6 bytes thanks to Sp3000 :D

# Answer
> 3 votes
# c, 68 55 bytes

```
f(int *l){for(--l[-1]?f(l):0;*l;l++)*l=l[1]-*l;*--l=0;}

```

This might be taking liberties with the input spec a bit. An int array is constructed such that element 0 is the depth and elements 1 to (n+1) are the input list elements 0 to n. Then the address of element 1 is passed to the function.

The array must be zero terminated. The array is edited in place.

E.g:

```
#include <stdio.h>

f(int *l){for(--l[-1]?f(l):0;*l;l++)*l=l[1]-*l;*--l=0;}

int main (int argc, char **argv)
{
  int list[] = {4, 10, 18, -12, 4, 8, -3, -5, 67, 9, 14, 0};
  int *elem;

  f(list + 1);

  for (elem = list + 1; *elem; elem++) {
    printf("%d, ", *elem);
  }
}

```

http://ideone.com/m5PDgF

# Answer
> 3 votes
# T-SQL, Too Many :)

When I first saw this problem, I wondered if there was a way to do this in a query. While trivial for most languages, it's not so much for SQL query.

The input goes into variables @ (for depth) and @L for the integer list. @L is a user defined table type

```
CREATE TYPE L AS TABLE(n INT IDENTITY(0,1),v INT)

```

Input setup

```
DECLARE @L L,@ INT=4
INSERT @L(v)values(10),(18),(-12),(4),(8),(-3),(-5),(67),(9),(14)

```

The query with some comments

```
WITH R AS(
    -- Recursive query to calculate the level of a pascal triangle with alternating negatives
    -- For 4 this is 1 -4  6 -4  1
    SELECT 1c,0g UNION ALL SELECT-c*(@-g)/(g+1),g+1FROM r WHERE g<@
    ),
    O AS(
    --Multiple N values of list by reversed pascal triangle values
    --shifting the start for each iteration (list length) - N
    SELECT c*v v,F
    FROM @L L
        CROSS APPLY(
            SELECT TOP((SELECT COUNT(*)FROM @L)-@)ROW_NUMBER()OVER(ORDER BY(SELECT\))-1F FROM sys.all_views a,sys.all_views b)c
        JOIN R ON N=F+@-G
    )
-- Sum the multiplied values
SELECT SUM(V)FROM o GROUP BY F ORDER BY F

```

Result

```
-142
55
27
41
-269
397

```

# Answer
> 3 votes
# Factor, 25 bytes

```
[ [ differences ] times ]

```

Try it online!

* `times` Call a quotation a certain number of times.
* `differences` Calculate the first-order differences of a number sequence.
* E.g. `{ 1 4 2 } -> { 3 -2 }`

# Answer
> 2 votes
# Powershell ~~115~~ 111 bytes

```
$p={param($a, $b)0..($a-1)|%{$b=@($l=$b.length;for($i=0;$i-lt$l;$i++){$b[$i+1]-$b[$i]})[0..($l-2)]};$b-join','}

```

Execute as such:

```
.$p 4 @(10,18,-12,4,8,-3,-5,67,9,14)

```

Output:

```
-142,55,27,41,-269,397

```

Moving a curly brace to a different spot allows this to display every step to the answer.

```
8,-30,16,4,-11,-2,72,-58,5
-38,46,-12,-15,9,74,-130,63
84,-58,-3,24,65,-204,193
-142,55,27,41,-269,397

```

# Answer
> 2 votes
## STATA, 126 bytes

```
di _r(a)_r(b)
token $b
gl $c=wordcount($b)
forv x=1/$a{
gl $c--
forv y=1/$c{
loc `y'=``y'+1'-``y''
}
}
forv z=1/$c{
di ``z''
}

```

Expects input as an integer representing the depth, followed by a space separated list of integers, both given via the standard prompt. Output is newline separated list of integers.

First it converts the list of integers (which it views as 1 long string) into a list of local variables whose names are 1,2,3,... Then it computes forward differences by setting the value of the yth local variable to be the value of the y+1th local variable minus the value of the yth local variable (i.e. 18-10=8), which overwrites existing values only after use. It does this $a (value of global variable a) times. Then it displays the value of each local variable, 1 at a time.

# Answer
> 2 votes
# Japt `-h`, ~~17~~ 5 bytes

*12 bytes saved thanks to @Shaggy*

```
VÆ=än

```

Try it online!

# Answer
> 2 votes
# K (ngn/k), 8 bytes

```
(1_-':)/

```

Try it online!

Sets up a do-over, running the code in parenthesis `depth` times, seeded with `initial values`. Results from one iteration are passed into the next.

* `-':` take the deltas of the input
* `1_` drop the first delta (which is just the first value in `x`)

# Answer
> 2 votes
# Vyxal, 3 bytes

```
(¯N

```

Try it Online!

Takes input like `n, [list]`

# Answer
> 2 votes
# Thunno 2, 2 bytes

```
{Ṣ

```

Try it online!

#### Explanation

```
{Ṣ  # Implicit input
{   # Input number of times:
 Ṣ  #  Deltas
    # Implicit output

```

# Answer
> 2 votes
# Swift, 51 bytes

```
{for _ in 0..<$0{$1=zip($1.dropFirst(),$1).map(-)}}

```

Takes `(depth, &arr)` and modifies the input array to contain the result.

Try it on SwiftFiddle!

Ungolfed/commented:

```
{ (depth: Int, arr: inout [Int]) in
  // Iterate the specified number of times. The iteration number isn't needed.
  for _ in 0..<depth {
    // Modify the input array to contain the next iteration:
    arr =
      // Get adjacent pairs in reverse order -- dropFirst returns a slice
      // without mutating the original array.
      zip(arr.dropFirst(), arr)
        // Subtract adjacent pairs. Swift lets you use an operator as if it
        // were a value of function type -- in this case, (Int, Int) -> Int.
        // This particular case is only legal because ((T, U)) -> V and
        // (T, U) -> V are equivalent types, but I think they're only
        // equivalent to make this kind of thing legal.
        .map(-)
  }
}

```

# Answer
> 2 votes
# Uiua SBCS, 8 bytes

```
⍥(↘1°\+)

```

Try it!

# Answer
> 1 votes
# Japt, 7 bytes

A couple of alternatives I'd made available to Luis for his solution.

```
_än}gNÅ

```

Try it

## 10 bytes

```
ÏÄ<V}f@=än

```

Try it

# Answer
> 1 votes
# 05AB1E, 2 bytes

*Ties HyperNeutrino's Jelly answer for #1.*

Try it online!

```
F¥  # full program
F   # for N in [0, 1, 2, ...,
    # ..., implicit input...
F   # ...minus 1]...
 ¥  # get differences of elements in...
    # implicit input...
 ¥  # or top of stack if not first iteration
    # implicit output

```

# Answer
> 1 votes
# Pyth, 4 bytes

```
.+FE

```

Try it here!

# Answer
> 1 votes
# x86-16 machine code, 20 bytes

```
00000000: 4951 568b fead 938b 042b c3ab e2f7 5e59  IQV......+....^Y
00000010: 4a75 edc3                                Ju..

```

Listing:

```
        DEPTH_LOOP:
49          DEC  CX                 ; decrement length
51          PUSH CX                 ; save length
56          PUSH SI                 ; save array pointer
8B FE       MOV  DI, SI             ; set array pointer for output
        DIFF_LOOP:
AD          LODSW                   ; load first WORD into AX, advance SI
93          XCHG AX, BX             ; save first to BX
8B 04       MOV  AX, WORD PTR[SI]   ; load second WORD into AX (don't advance)
2B C3       SUB  AX, BX             ; AX = AX - BX
AB          STOSW                   ; save result to current array index
E2 F7       LOOP DIFF_LOOP          ; loop until end of array
5E          POP  SI                 ; restore array pointer
59          POP  CX                 ; restore length
4A          DEC  DX                 ; decrement depth counter
75 ED       JNZ  DEPTH_LOOP         ; loop until end of depth
C3          RET                     ; return to caller

```

Input array at `[SI]`, input length (in bytes) in `CX`, depth in `DX`.

Test with DOS DEBUG:

Note: data is shown as little endian hex in DEBUG (`A 0` = `0x000a` = `10`, `72 FF` = `0xff72` = `-142`).

# Answer
> 1 votes
# Vyxal, 2 bytes

Try it Online!

```
(  # n times
 ¯ # take forward differences

```

# Answer
> 0 votes
# Clojure, 47 bytes

```
#(if(= 0 %)%2(recur(dec %)(map -(rest %2)%2))))

```

A simple recursion on anonymous function. You save 1 byte if the order of arguments is swapped as now `%2` occurs more frequently than `%`.

# Answer
> 0 votes
# Jelly, 2 bytes

Try it online!

# Explanation

```
I¡  Main Link
 ¡  Repeat `n` times; this repeats the previous link by <right argument> times
I   Get forward differences

```

Very straightforward answer :P

# Answer
> 0 votes
# SmileBASIC, 76 bytes

Finally a reason to use `ARYOP`!

```
DEF F L,D
IF!D THEN@R
DIM B[0]COPY B,L
T=SHIFT(L)ARYOP 1,L,L,B
F L,D-1@R
END

```

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


# Question
Title: Remove all occurrences of the first letter of a string from the entire string
Given an input string only containing the characters `A-Z`, `a-z`, and spaces, remove all occurrences of the uppercase and lowercase versions of the first character of the string (if the first character is `A` remove all `A`s and `a`s, if the first character is (space) remove all spaces), and print the output.

Example cases:

* `Testing Testing One Two Three` -\> `esing esing One wo hree`
* `Programming Puzzles and Code Golf` -\> `rogramming uzzles and Code Golf`
* `How much wood would a woodchuck chuck if a woodchuck could chuck wood` -\> `ow muc wood would a woodcuck cuck if a woodcuck could cuck wood`
* `{space}hello world` -\> `helloworld`
* `welcome to WATER WORLD` -\> `elcome to ATER ORLD`

This is , shortest code in bytes wins!

Notes:

* Input will always be 2 or more valid characters.
* Output will never be an empty string.

# Answer
> 9 votes
# Pyth, 7 bytes

```
-zrBhz2

```

Try it online: Demonstration or Test Suite

Nice. The new bifurcate operator (only 8 days old) helps here to save one char. I think this is the first code, that uses this feature.

### Explanation

```
-zrBhz2   implicit: z = input string
    hz    take the first character of z
  rB  2   B generates a list, containing the original char and the
          result of r.2 applied to the char, which swaps the case
-z        remove these two chars from z and print the result

```

# Answer
> 15 votes
# Perl, 13 bytes

```
#!perl -p
/./,s/$&//gi

```

Counting the shebang as one, input is taken from stdin.

---

**Sample Usage**

```
$ echo Testing Testing One Two Three | perl remove-first.pl
esing esing One wo hree

$ echo \ Testing Testing One Two Three | perl primo-remove.pl
TestingTestingOneTwoThree

```

# Answer
> 14 votes
# brainfuck, 219 bytes

```
+[+[>+<+<]>],[<+<+>>-]>[<<[->]>[<]>-]++++[<++++++++>-]<<[[-]----[>-<----]>-<<[>+>+<<-]<,[[>+>>>+>>+>+<<<<<<<-]>>[<<+>>-]<<[>->+<<-]>[[-]+<]>[>]<<[>>+<<-]>>[<-<+>>-]<[[-]+>]>>[<]<<<<[>>>+<<<-]>>>-[>>.<<-]>>>[[-]<]<<<<<,]

```

(Requires tape that either allows the pointer to go to the negatives or loops to the end if it tries. Also requires `,` to return 0 at EOF. In my experience, most interpreters meet these requirements by default.)

This actually turned out to be pretty easy! I wouldn't be surprised if it's golfable (I have some idea of where there might be wasted bytes but I'm not super sure if it'll pan out). Still, getting it work wasn't really a challenge at all.

This code treats everything with an ASCII value below 97 as an uppercase character. If the first character is space, it'll try to remove any occurrences of a "lowercase space" (i.e. `chr(32+32)`, i.e. `@`) from the string. This is okay, because only letters and spaces will ever be present.

**With comments:**

```
to make comments shorter: everywhere it says "fc" means "first character"

#################################### GET FC ####################################

+[+[>+<+<]>]        shortest way to get 96
                    any number above 89 and less than 97 would work because this
                    is only for figuring out if the first character is capital

,[<+<+>>-]          create two copies of the first character

### current tape: | fc | fc | 000 | 096 | ###
###      pointer:              ^          ###

########################### FIND MAX(FC MINUS 96; 0) ###########################

>[                  96 times:

  <<                  go to the cell with the first char

  [->]                if not 0: sub one and move right

  ### current tape: | fc | char being worked on | 000 | 096 | ###
  ###      pointer:                           ^ OR ^          ###

  >[<]>               collapse the wavefunction; sync the branches

-]

### current tape: | fc | fc is lowercase ? nonzero : zero | 000 | 000 | ###
###      pointer:                                                  ^    ###

############################# GET BOTH CASES OF FC #############################

++++[<++++++++>-]   get 32 (add to uppercase character to get lowercase)

<<[                 if the character is already lowercase:

  [-]                 clear the lowercase flag

  ----[>-<----]>-     sub 64 from the cell with 32

<]

<[>+>+<<-]          add fc to the 32 or minus 32 to get both cases

### current tape: | 000 | fc | other case of fc | ###
###      pointer:    ^                            ###

###################### LOOP THROUGH REMAINING CHARACTERS #######################

<,[                 for each character:

  [>+>>>+>>+>+<<<<<<<-]
                      make four copies
                      (only 3 are strictly needed; 4th will resync a branch)

  >>                  go to the first case of fc

  [<<+>>-]<<[>->+<<-] subtract one case of fc from one copy

  >[[-]+<]            if the result is nonzero set it to 1

  >[>]<<              go to the other case of fc (and resync branches)

  [>>+<<-]>>[<-<+>>-] subtract other case of fc from other copy

  <[[-]+>]            if the result is nonzero set it to 1

  >>[<]               resync branches using extra copy

  <<<<[>>>+<<<-]>>>   add results together

  -                   subtract 1

   if the character exactly matched either case: 1 plus 0 minus 1 = 0
  if the character exactly matched neither case: 1 plus 1 minus 1 = 1
    if the character exactly matched both cases: impossible

  [                   if the result is 1:

    >>.<<               output character

    -                   set cell to 0 to kill loop

  ]

  >>>[[-]<]           clean up remaining copies

  <<<<<,              get next character; or end loop if done

]

```

# Answer
> 10 votes
# CJam, 8 bytes

```
q(_32^+-

```

Try it online in the CJam interpreter.

### How it works

```
q        e# Read all input from STDIN.
 (       e# Shift out the first character.
  _32^   e# Push a copy and XOR its character code with 32.
         e#   For a letter, this swaps its case.
         e#   For a space, this pushes a null byte.
      +  e# Concatenate these two characters.
       - e# Remove all occurrences of both from the input string.

```

# Answer
> 7 votes
# Pyth, 8 bytes

```
-zr*2hz3

```

Try it online

Uses Pyth's version of python's `str.title` to convert a string of the first letter twice into the form `"<Upper><Lower>"`. Then it removes each element from the input that is in that string. Spaces work fine because they are unaffected by `str.title`.

# Answer
> 5 votes
## JavaScript (ES6), ~~38~~ 36 bytes

This does not depend on the `flags` parameter which is Mozilla-specific.

```
f=x=>x.replace(RegExp(x[0],'gi'),'')

```

## CoffeeScript, ~~39~~ 37 bytes

For once it's shorter in JS than CoffeeScript!

```
f=(x)->x.replace RegExp(x[0],'gi'),''

```

# Answer
> 5 votes
# MATLAB, 28 bytes

```
@(S)S(lower(S)~=lower(S(1)))

```

# Answer
> 4 votes
## PHP, 41 bytes

Takes one command-line argument. Short open tags need to be enabled for PHP \< 5.4.

```
<?=str_ireplace($argv[1][0],'',$argv[1]);

```

# Answer
> 3 votes
## Minkolang 0.9, ~~23~~ 33 bytes

No way this will win but eh, it's fun!

```
" Z"od0c`1c*-$I[odd0c`1c*-2c=?O].

```

Try it here.

### Explanation

```
" Z"                                 Makes it easier to uppercase
    od                               Take first character of input and duplicate
      0c`1c*-                        Uppercase if needed
             $I[               ]     Loop over the input
                odd                  Take character from input and duplicate twice
                   0c`1c*-           If it's lowercase, uppercase it.
                          0c=?       Check to see if it's equal to first character
                              O      If not, output as character
                                .    Exit

```

(This might fail in some edge cases, like if the first character is a symbol.)

# Answer
> 3 votes
# Perl, 27 bytes

This is a complete program, although it's just based on 2 regexes that could probably copied into a Retina program to save bytes on I/O.

```
$_=<>;m/(.)/;s/$1//gi;print

```

Edit: Looks like this has already been beaten with somebody using the `-p` option. Oh, and using `$&` instead of `$1`.

# Answer
> 3 votes
# TECO, ~~15~~ 14 bytes

Editing text? When in doubt, use the Text Editor and COrrecter!

After much trial-and-error (mostly error), I think this is the shortest generic TECO program that will do the job.

```
0,1XA<S^EQA$-D>

```

Or, in human-readable form

```
0,1XA    ! Read the first character of the string into the text area of !
         ! Q-buffer A.                                                  !
<        ! Loop,                                                        !
S^EQA$   ! searching for the text in Q-buffer A in either lowercase or  !
         ! uppercase,                                                   !
-D       ! and deleting it,                                             !
>        ! until the search fails.                                      !

```

`$` represents the escape key, and `^E` represents the sequence `CTRL`+`E`. Depending on the flavor of TECO you're using, it may recognize these ASCII substitutions, or it may not.

According to the manual, some dialects of TECO accept this 13-byte version (using a find-and-delete command instead of separate "find" and "delete" commands) instead:

```
0,1XA<FD^EQA$>

```

# Answer
> 3 votes
# Pip, 8 bytes

```
aR-Xa@0x

```

Takes the string as a command-line argument (will need to be quoted if it contains spaces). Explanation:

```
          a gets cmdline arg; x is "" (implicit)
    a@0   First character of a
   X      Convert to regex
  -       Make regex case-insensitive
aR     x  Replace all matches of that regex in a with empty string
          Autoprint (implicit)

```

This solution has the extra bonus of working on strings containing *any* printable ASCII characters. (The `X` operator backslash-escapes anything that's not alphanumeric.)

# Answer
> 3 votes
## Python, 66 char

```
a=raw_input()
print a.replace(a[0],'').replace(a[0].swapcase(),'')

```

# Answer
> 3 votes
# Julia, 34 bytes

```
s->replace(s,Regex(s[1:1],"i"),"")

```

This creates an unnamed function that accepts a string and returns a string. It constructs a case-insensitive regular expression from the first character in the input and replaces all occurrences of that with an empty string.

# Answer
> 3 votes
# Python 2, 43

```
lambda s:s.translate(None,(s[0]*2).title())

```

This is somewhat based on my Pyth answer, but it's also related to some comments from ThomasKwa and xnor from here. Mostly posting because I wanted this answer to exist.

# Answer
> 2 votes
# Python, 61 bytes (way too many)

```
lambda x:"".join(map(lambda y:(y.lower()!=x[0].lower())*y,x))

```

I imagine there is a better way to go about doing this, but I can't seem to find it. Any ideas on removing the `"".join(...)`?

# Answer
> 2 votes
# Mathematica, 47 bytes

```
StringDelete[#,#~StringTake~1,IgnoreCase->1>0]&

```

# Answer
> 2 votes
# R, 43 bytes

```
cat(gsub(substr(s,1,1),"",s<-readline(),T))

```

This is a full program that reads a line from STDIN and writes the modified result to STDOUT.

Ungolfed:

```
# Read a line from STDIN
s <- readline()

# Replace all occurrences of the first character with an empty
# string, ignoring case
r <- gsub(substr(s, 1, 1), "", s, ignore.case = TRUE)

# Write the result to STDOUT
cat(r)

```

# Answer
> 2 votes
# Ruby, 25 bytes

Anonymous function:

```
->s{s.gsub /#{s[0]}/i,""}

```

Full prgram, 29 bytes:

```
puts gets.gsub /#{$_[0]}/i,""

```

# Answer
> 2 votes
# Ouroboros, 61 bytes

Hey, it's shorter than C++! Ha.

```
i..91<\64>*32*+m1(
)L!34*.(;Si.1+!24*(Y.@@.@=@.@32-=\@+2*.(yo

```

In Ouroboros, each line of the program represents a snake with its tail in its mouth. Control flow is accomplished by eating or regurgitating sections of tail, with a shared stack to synchronize between snakes.

### Snake 1

`i.` reads a character from input and duplicates it. `.91<\64>*32*` pushes `32` if the character was an uppercase letter, `0` otherwise. `+`ing that to the character converts uppercase letters to lowercase while leaving lowercase letters and spaces unchanged. All this has been taking place on snake 1's stack, so we now push the value to the shared stack (`m`) for snake 2 to process. Finally, `1(` eats the last character of snake 1's tail. Since that's where the instruction pointer is, the snake dies.

### Snake 2

`)` has no effect the first time through. `L!34*` pushes `34` if the shared stack is empty, `0` otherwise. We then `.` dup and `(` eat that many characters.

* If the shared stack was empty, this puts the end of the snake right after the `(` we just executed. Therefore, control loops back to the beginning of the line, where `)` regurgitates the characters we just ate (having previously pushed an extra copy of `34`) and repeat the stack-length test.
* If the shared stack was not empty, no characters are eaten, ';' drops the extra `0`, and execution continues:

`Si` switches to the shared stack and inputs another character. `.1+!24*` pushes `24` if that character was -1 / EOF, `0` otherwise. On EOF, `(` swallows 24 characters--including the IP--and the snake dies. Otherwise, execution continues.

`Y` yanks a copy of the top of the shared stack (the character we just read) to snake 2's own stack for future use. Then `.@@.@=@.@32-=\@+2*` calculates whether the new character is equal to the first character or to the first character minus 32, pushing `2` if so and `0` if not. We `.` duplicate and `(` eat that many characters:

* If the characters matched, we go straight back to the head of the snake, where `(` regurgitates the 2 characters we just ate and execution proceeds with the next character.
* If not, we `y`ank the character back from snake 2's stack, `o`utput it, and then loop.

### See it in action

```
// Define Stack class
function Stack() {
  this.stack = [];
  this.length = 0;
}
Stack.prototype.push = function(item) {
  this.stack.push(item);
  this.length++;
}
Stack.prototype.pop = function() {
  var result = 0;
  if (this.length > 0) {
    result = this.stack.pop();
    this.length--;
  }
  return result;
}
Stack.prototype.top = function() {
  var result = 0;
  if (this.length > 0) {
    result = this.stack[this.length - 1];
  }
  return result;
}
Stack.prototype.toString = function() {
    return "" + this.stack;
  }

// Define Snake class
function Snake(code) {
  this.code = code;
  this.length = this.code.length;
  this.ip = 0;
  this.ownStack = new Stack();
  this.currStack = this.ownStack;
  this.alive = true;
  this.wait = 0;
  this.partialString = this.partialNumber = null;
}
Snake.prototype.step = function() {
    if (!this.alive) {
      return null;
    }
    if (this.wait > 0) {
      this.wait--;
      return null;
    }
    var instruction = this.code.charAt(this.ip);
    var output = null;
    if (this.partialString !== null) {
      // We're in the middle of a double-quoted string
      if (instruction == '"') {
        // Close the string and push its character codes in reverse order
        for (var i = this.partialString.length - 1; i >= 0; i--) {
          this.currStack.push(this.partialString.charCodeAt(i));
        }
        this.partialString = null;
      } else {
        this.partialString += instruction;
      }
    } else if (instruction == '"') {
      this.partialString = "";
    } else if ("0" <= instruction && instruction <= "9") {
      if (this.partialNumber !== null) {
        this.partialNumber = this.partialNumber + instruction; // NB: concatenation!
      } else {
        this.partialNumber = instruction;
      }
      next = this.code.charAt((this.ip + 1) % this.length);
      if (next < "0" || "9" < next) {
        // Next instruction is non-numeric, so end number and push it
        this.currStack.push(+this.partialNumber);
        this.partialNumber = null;
      }
    } else if ("a" <= instruction && instruction <= "f") {
      // a-f push numbers 10 through 15
      var value = instruction.charCodeAt(0) - 87;
      this.currStack.push(value);
    } else if (instruction == "$") {
      // Toggle the current stack
      if (this.currStack === this.ownStack) {
        this.currStack = this.program.sharedStack;
      } else {
        this.currStack = this.ownStack;
      }
    } else if (instruction == "s") {
      this.currStack = this.ownStack;
    } else if (instruction == "S") {
      this.currStack = this.program.sharedStack;
    } else if (instruction == "l") {
      this.currStack.push(this.ownStack.length);
    } else if (instruction == "L") {
      this.currStack.push(this.program.sharedStack.length);
    } else if (instruction == ".") {
      var item = this.currStack.pop();
      this.currStack.push(item);
      this.currStack.push(item);
    } else if (instruction == "m") {
      var item = this.ownStack.pop();
      this.program.sharedStack.push(item);
    } else if (instruction == "M") {
      var item = this.program.sharedStack.pop();
      this.ownStack.push(item);
    } else if (instruction == "y") {
      var item = this.ownStack.top();
      this.program.sharedStack.push(item);
    } else if (instruction == "Y") {
      var item = this.program.sharedStack.top();
      this.ownStack.push(item);
    } else if (instruction == "\\") {
      var top = this.currStack.pop();
      var next = this.currStack.pop()
      this.currStack.push(top);
      this.currStack.push(next);
    } else if (instruction == "@") {
      var c = this.currStack.pop();
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(c);
      this.currStack.push(a);
      this.currStack.push(b);
    } else if (instruction == ";") {
      this.currStack.pop();
    } else if (instruction == "+") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(a + b);
    } else if (instruction == "-") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(a - b);
    } else if (instruction == "*") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(a * b);
    } else if (instruction == "/") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(a / b);
    } else if (instruction == "%") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(a % b);
    } else if (instruction == "_") {
      this.currStack.push(-this.currStack.pop());
    } else if (instruction == "I") {
      var value = this.currStack.pop();
      if (value < 0) {
        this.currStack.push(Math.ceil(value));
      } else {
        this.currStack.push(Math.floor(value));
      }
    } else if (instruction == ">") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(+(a > b));
    } else if (instruction == "<") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(+(a < b));
    } else if (instruction == "=") {
      var b = this.currStack.pop();
      var a = this.currStack.pop();
      this.currStack.push(+(a == b));
    } else if (instruction == "!") {
      this.currStack.push(+!this.currStack.pop());
    } else if (instruction == "?") {
      this.currStack.push(Math.random());
    } else if (instruction == "n") {
      output = "" + this.currStack.pop();
    } else if (instruction == "o") {
      output = String.fromCharCode(this.currStack.pop());
    } else if (instruction == "r") {
      var input = this.program.io.getNumber();
      this.currStack.push(input);
    } else if (instruction == "i") {
      var input = this.program.io.getChar();
      this.currStack.push(input);
    } else if (instruction == "(") {
      this.length -= Math.floor(this.currStack.pop());
      this.length = Math.max(this.length, 0);
    } else if (instruction == ")") {
      this.length += Math.floor(this.currStack.pop());
      this.length = Math.min(this.length, this.code.length);
    } else if (instruction == "w") {
      this.wait = this.currStack.pop();
    }
    // Any instruction not covered by the above cases is ignored
    if (this.ip >= this.length) {
      // We've swallowed the IP, so this snake dies
      this.alive = false;
      this.program.snakesLiving--;
    } else {
      // Increment IP and loop if appropriate
      this.ip = (this.ip + 1) % this.length;
    }
    return output;
  }

// Define Program class
function Program(source, speed, io) {
  this.sharedStack = new Stack();
  this.snakes = source.split(/\r?\n/).map(function(snakeCode) {
    var snake = new Snake(snakeCode);
    snake.program = this;
    snake.sharedStack = this.sharedStack;
    return snake;
  }.bind(this));
  this.snakesLiving = this.snakes.length;
  this.io = io;
  this.speed = speed || 10;
  this.halting = false;
}
Program.prototype.run = function() {
  if (this.snakesLiving) {
    this.step();
    this.timeout = window.setTimeout(this.run.bind(this), 1000 / this.speed);
  }
}
Program.prototype.step = function() {
  for (var s = 0; s < this.snakes.length; s++) {
    var output = this.snakes[s].step();
    if (output) {
      this.io.print(output);
    }
  }
}
Program.prototype.halt = function() {
  window.clearTimeout(this.timeout);
}
var ioFunctions = {
  print: function(item) {
    var stdout = document.getElementById('stdout');
    stdout.value += "" + item;
  },
  getChar: function() {
    if (inputData) {
      var inputChar = inputData[0];
      inputData = inputData.slice(1);
      return inputChar.charCodeAt(0);
    } else {
      return -1;
    }
  },
  getNumber: function() {
    while (inputData && (inputData[0] < "0" || "9" < inputData[0])) {
      inputData = inputData.slice(1);
    }
    if (inputData) {
      var inputNumber = inputData.match(/\d+/)[0];
      inputData = inputData.slice(inputNumber.length);
      return +inputNumber;
    } else {
      return -1;
    }
  }
};
var program = null;
var inputData = null;

function resetProgram() {
  var stdout = document.getElementById('stdout');
  stdout.value = null;
  if (program !== null) {
    program.halt();
  }
  program = null;
  inputData = null;
}

function initProgram() {
  var source = document.getElementById('source'),
    stepsPerSecond = document.getElementById('steps-per-second'),
    stdin = document.getElementById('stdin');
  program = new Program(source.value, +stepsPerSecond.innerHTML, ioFunctions);
  inputData = stdin.value;
}

function runBtnClick() {
  if (program === null || program.snakesLiving == 0) {
    resetProgram();
    initProgram();
  } else {
    program.halt();
    var stepsPerSecond = document.getElementById('steps-per-second');
    program.speed = +stepsPerSecond.innerHTML;
  }
  program.run();
}

function stepBtnClick() {
  if (program === null) {
    initProgram();
  } else {
    program.halt();
  }
  program.step();
}
```

```
.container {
  width: 100%;
}
.so-box {
  font-family: 'Helvetica Neue', Arial, sans-serif;
  font-weight: bold;
  color: #fff;
  text-align: center;
  padding: .3em .7em;
  font-size: 1em;
  line-height: 1.1;
  border: 1px solid #c47b07;
  -webkit-box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset;
  text-shadow: 0 0 2px rgba(0, 0, 0, 0.5);
  background: #f88912;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset;
}
.control {
  display: inline-block;
  border-radius: 6px;
  float: left;
  margin-right: 25px;
  cursor: pointer;
}
.option {
  padding: 10px 20px;
  margin-right: 25px;
  float: left;
}
h1 {
  text-align: center;
  font-family: Georgia, 'Times New Roman', serif;
}
a {
  text-decoration: none;
}
input,
textarea {
  box-sizing: border-box;
}
textarea {
  display: block;
  white-space: pre;
  overflow: auto;
  height: 40px;
  width: 100%;
  max-width: 100%;
  min-height: 25px;
}
span[contenteditable] {
  padding: 2px 6px;
  background: #cc7801;
  color: #fff;
}
#stdout-container,
#stdin-container {
  height: auto;
  padding: 6px 0;
}
#reset {
  float: right;
}
#source-display-wrapper {
  display: none;
  width: 100%;
  height: 100%;
  overflow: auto;
  border: 1px solid black;
  box-sizing: border-box;
}
#source-display {
  font-family: monospace;
  white-space: pre;
  padding: 2px;
}
.activeToken {
  background: #f88912;
}
.clearfix:after {
  content: ".";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}
.clearfix {
  display: inline-block;
}
* html .clearfix {
  height: 1%;
}
.clearfix {
  display: block;
}
```

```
<!--
Designed and written 2015 by D. Loscutoff
Much of the HTML and CSS was taken from this Befunge interpreter by Ingo Bürk: http://codegolf.stackexchange.com/a/40331/16766
-->
<div class="container">
<textarea id="source" placeholder="Enter your program here" wrap="off">i..96<\64>*32*+m1(
)L!34*.(;Si.1+!24*(Y.@@.@=@.@32-=\@+2*.(yo</textarea>
<div id="source-display-wrapper"><div id="source-display"></div></div></div><div id="stdin-container" class="container">
<textarea id="stdin" placeholder="Input" wrap="off">Testing Testing One Two Three</textarea>
</div><div id="controls-container" class="container clearfix"><input type="button" id="run" class="control so-box" value="Run" onclick="runBtnClick()" /><input type="button" id="pause" class="control so-box" value="Pause" onclick="program.halt()" /><input type="button" id="step" class="control so-box" value="Step" onclick="stepBtnClick()" /><input type="button" id="reset" class="control so-box" value="Reset" onclick="resetProgram()" /></div><div id="stdout-container" class="container"><textarea id="stdout" placeholder="Output" wrap="off" readonly></textarea></div><div id="options-container" class="container"><div class="option so-box">Steps per Second:
<span id="steps-per-second" contenteditable>1000</span></div></div>
```

# Answer
> 2 votes
# C, 60 bytes

`n,c,d;main(){for(;read(0,&c-n,1);n=2)d-c&31&&n&&putchar(d);}`

Edit: Fixed a bug which caused a null byte to be printed at the beginning

# Answer
> 2 votes
# Vim, 30 Keystrokes

Sorry to unearth, but i don't see any Vim answer D:

```
If<Right>xh@x.<Esc>"xy07|@x2|~0"xd7|@x0x

```

Explanation:

1. `If<Right>xh@x.<Esc>`
Write a (recursive) macro around the first character
Moving left (`h`) is needed to stay at the left of the next unread character
Adding any character (`.`) at the end is needed in case the second must be removed
2. `"xy0` Copy the macro in the register `x`
3. `7|` Move to the 7th char
4. `@x` Run the macro from `x`
5. `2|~` Switch the case of the first char (actually at the 2nd position)
6. `0"xd7|` Cut the macro in the register `x`
7. `@x` Run the macro from `x`
8. `0x` Remove the place-holder `.`

# Answer
> 2 votes
# Zsh\*, 21 bytes

```
<<<${1//(#i)${1:0:1}}

```

Try it online!

(\*) Using `setopt extendedglob`

# Answer
> 1 votes
# TeaScript, 16 bytes

TeaScript is JavaScript with shortened property names.

```
x.g(x[0],'','i')

```

Try it online

---

TeaScript 3 came out and now this is **10 bytes**.

```
xg(x░,u,'i

```

which compiles to:

```
xg(x[0],u,'i

```

which compiles to:

```
x.g(x[0],u,'i')

```

where `u` is preset to `""`

# Answer
> 1 votes
# C++, ~~100~~ ~~99~~ 98 bytes

```
#include<ios>
int main(){for(int c,f=getchar();~(c=getchar());)tolower(c)-tolower(f)&&putchar(c);}

```

Just one more byte to get under 100. `getchar()` returns `-1` when it reads end of stream, so that's why the `~` is in `for` cycle. (`~-1 == 0`)

Ungolfed

```
#include <ios>
int main()
{
    for (int c, f = getchar(); ~(c = getchar()); )
        tolower(c) - tolower(f) && putchar(c);
}

```

# Answer
> 1 votes
# Haskell, 52 bytes

```
import Data.Char
t=toUpper
r(h:s)=filter((t h/=).t)s

```

# Answer
> 1 votes
# C, ~~65~~ 61 bytes

```
main(c,v)char**v;{for(c=**++v;*++*v;**v-c&31&&putchar(**v));}

```

Compiles with warnings. Reads string from `argv[1]`. Online example

# Answer
> 1 votes
# TI-BASIC, 164 bytes

For TI-83+/84+ series graphing calculators.

```
Input Str1
1→X
"sub(Str1,X,1→u
"ABCDEFGHIJKLMNOPQRSTUVWXYZ zyxwvutsrqponmlkjihgfedcba
u+sub(Ans,54-inString(Ans,u),1
For(X,2,length(Str1
If 2<inString(Ans+Str1,u
Ans+u
End
sub(Ans,3,length(Ans)-2

```

TI-BASIC is clearly the wrong tool for the job.

* It doesn't have a command to remove characters, so we need to loop through the string and append characters if they don't match what is to be removed.
* It doesn't support empty strings, so we need to start the string with the two letters to be removed, build the output onto the end, and chop the first two characters off.
* It doesn't have case-change commands, so we need to hardcode the entire alphabet...
    + twice...
    + Did I mention lowercase letters take two bytes each in the TI-BASIC encoding?

I'm not 100% sure, but I spent over six hours on this, and it seems to be the shortest possible solution.

To test this with non-uppercase inputs (or to type it into your calculator), make a different program with the contents `AsmPrgmFDCB24DEC9`, and run it using `Asm([whatever you named it]` to enable lowercase typing mode.

# Answer
> 1 votes
# Lua, ~~93~~ 78 Bytes

```
a=io.read()m=a:sub(1,1):upper()print(({a:gsub("["..m..m:lower().."]","")})[1])

```

# Answer
> 1 votes
# Common Lisp, 77

```
(princ(let((x(read-char)))(remove-if(lambda(y)(char-equal x y))(read-line))))

```

Curse these long function names (and parentheses (but I still love them anyway (:3))).

# Answer
> 1 votes
# AppleScript, ~~209~~ 201 bytes

My only consolation is that I beat Brainfuck.

```
set a to(display dialog""default answer"")'s text returned
set n to a's characters's number
set o to""
repeat n
if not a's character n=a's character 1 then set o to a's character n&o
set n to n-1
end
o
```

How this works is that I take input through `a`, get the length of `a` and mark it as `n`, and set an output variable `o`. For every character that I find that does not contain the first character of a (`a's character 1`), I concatenate it to `o`. The final line prints `o`.

Note: This automatically supports all Unicode. c:

# Answer
> 1 votes
## Retina, 16 bytes

```
i`(.)(?<=^\1.*)

```

Save the code with a trailing linefeed and run it with the `-s` flag.

How it works: the trailing linefeed makes this a replacement stage, such that any matches of the given regex are replaced with an empty string. The `i` turns on case-insensitive mode which also makes backreferences case-insensitive. Finally, the regex simply matches and captures a single characters and then checks whether the first character in the string is the same (up to case) using a backreference.

# Answer
> 1 votes
# Gema, 19 characters

```
\A?=@set{c;?}
\C$c=

```

Sample run:

```
bash-4.3$ gema '\A?=@set{c;?};\C$c=' <<< 'Testing Testing One Two Three'
esing esing One wo hree

bash-4.3$ gema '\A?=@set{c;?};\C$c=' <<< ' Testing Testing One Two Three'
TestingTestingOneTwoThree

```

# Answer
> 1 votes
# Bash, 35 characters

```
c=${1::1}
echo "${1//[${c^}${c,}]}"

```

Sample run:

```
bash-4.3$ bash rm-1st-char.sh 'Testing Testing One Two Three'
esing esing One wo hree

bash-4.3$ bash rm-1st-char.sh ' Testing Testing One Two Three'
TestingTestingOneTwoThree

```

# Answer
> 1 votes
## Brainfuck, 72 bytes

```
,>>,
[
  <<[>+>->+<<<-]
  >>
  [
    >+>>+<
    [>-]
    >[+++[<++++++++>-]>]
    <<-<<-
  ]
  >>[<.>[-]]
  <,
]

```

Try it online.

Checks whether the differences between the first character and subsequent characters are divisible by 32.

# Answer
> 1 votes
# Vim, 11 keystrokes

```
x:s/<C-r>-//gi

```

With a trailing newline

Although there already is a Vim answer, this one uses a different approach.

This deletes the first first character, which automatically gets stored in register `-`. Then we do a search and replace, replacing the deleted character (`<C-r>-`) with nothing (ie deleting it). The `gi` flags are used (`g`lobal and case-`i`nsensitive).

# Answer
> 1 votes
# Jelly, ~~7~~ 6 bytes

```
żŒsḢ⁸ḟ

```

Try it online!

1 byte saved thanks to Erik The Outgolfer

## How it works

```
żŒsḢ⁸ḟ - Main link. Argument: s (string) e.g. "ABCabc"

 Œs    - Swap the case                        "abcABC"
ż      - zip with the input                   ["Aa", "Bb", "Cc"]
   Ḣ   - take the first element               "Aa"
     ḟ - Filter those characters from...
    ⁸  -   the input                          "BCbc"

```

Original

```
ḟḢ;Œs$$ - Main link. Argument: s (string) e.g. "ABCabc"

 Ḣ      - Generate the first character of s    "A"
   Œs   - Generate the swapped case of ^       "a"
  ;     - Concatenate                          "Aa"
ḟ    $$ - Filter ^ from the input              "BCbc"

```

# Answer
> 1 votes
# 05AB1E, 5 bytes

```
ćDš«м

```

Try it online!

Newer version than what Adnan used.

# Answer
> 1 votes
# Vyxal, 5 bytes

```
h:N"F

```

Try it Online!

Look ma, no Unicode!

```
h     # First character of (implicit) input
   "  # Paired with
 :    # A copy of itself
  N   # With case swapped
    F # Remove those characters from (implicit) input

```

# Answer
> 1 votes
# Arturo, 31 bytes

```
$[s][l:lower s print l--@->l\0]

```

Try it

```
$[s][            ; a function taking an argument s
    l: lower s   ; assign lowercased s to l
    print        ; print
    l --         ; from l, remove...
    @->l\0       ; the first element of l (as a list)
]                ; end function

```

# Answer
> 1 votes
# Japt, 3 bytes

```
kUÎ

```

Try it (includes all test cases)

```
kUÎ     :Implicit input of string U
k       :Case insensitively remove
 UÎ     :First character of U

```

# Answer
> 1 votes
# Raku, 17 bytes

```
{S:i:g/$(m/./)//}

```

Try it online!

* `S:i:g/...//` returns a copy of the input string in which the regex between the first two slashes has been `S`ubstituted, case-`i`nsensitively and `g`lobally, with the content between the last two slashes, which is nothing--that is, the matches are deleted.
* `m/./` matches the first character of the input string, returning a Match object. Note that unlike many regular expression dialects, a dot matches any character, even a newline.
* `$(m/./)` interpolates that first character into the regex as a plain string pattern.

# Answer
> 1 votes
# Nibbles, 6.5 bytes

```
+%~@%`)/_$`)$

```

Attempt This Online!

Interestingly, this only works because none of the ASCII codes of the allowed characters are divisible by each other. That's because I'm using `%` (modulo) to test if two characters are different.

# Answer
> 1 votes
# Thunno 2, 6 bytes

```
hẊoxPo

```

Attempt This Online!

## Thunno 2 `J`, 8 bytes

```
ḢçRL'|jḄ

```

Attempt This Online!

More fun answer using regex.

#### Explanation

```
hẊoxPo  # Implicit input
h       # First character of the input
 Ẋ      # Store in x without popping
  o     # Remove this from input
   x    # Push x again
    P   # Swap its case
     o  # Remove this from the string
        # Implicit output

```

```
ḢçRL'|jḄ  '# Implicit input
Ḣ          # First character of the input
 ç         # Apply and collect results:
  R        #  Uppercase the character
   L       #  Lowercase the character
    '|j   '# Join the pair by "|"
       Ḅ   # Split the string on this regex
           # Implicit output, joined

```

# Answer
> 0 votes
# Hassium, 57 Bytes

```
func main(){s=input().toLower()print(s.replace(s[0],""))}

```

Run online and see expanded here

# Answer
> 0 votes
# Julia, 40 bytes

```
t->t[find([(l=lowercase(t))...].!=l[1])]

```

`l=lowercase(t)` makes `l` store the string `t` reduced to lowercase. `[l...]` then converts the string into a character array. `.!=l[1]` compares that array element-wise with the first value of it, returning `true` if they don't match. `find` then converts the resulting boolean array into an array containing the true indices, and `t[]` then returns the desired string.

It feels like Julia should be able to do better than this, but so far I can't see it. It's a lot easier if you don't have to catch both upper- and lower-case instances of the letter.

# Answer
> 0 votes
# Ceylon, ~~93~~ 84

`String r(String i)=>String{if(exists f=i[0])for(c in i.rest)if(c.offset(f)%32!=0)c};`

This defines a function `r` which takes and returns a String, solving the task.

Formatted:

```
String r(String i) =>
        String {
    if (exists f = i[0])
        for (c in i.rest)
            if (c.offset(f) % 32 != 0)
                c };

```

The function creates and returns a string from an Iterable comprehension, composed of several if- and for-clauses.

The first `if` makes sure that the string is non-empty (if its empty, the iterable will be empty, thus the returned string too), and at the same time declares the `f` variable to be used later. (`i[0]` could have also been written `i.first`, but this way is shorter.) While the question says we can be sure the input has always length \> 1, the compiler doesn't know this. (A different way of saying this would be to use an `assert` statement, but this would be even longer.)

The next `for` clause iterates over the remainder of the string (i.e. the string without its first character). Each item is named `c`.

The second `if` does the case-check. It turns out that in ASCII, the upper- and lower case letters have distance 32 from each other, so `c.offset(f) % 32 != 0` is a slightly shorter way of writing `c.uppercased != f.uppercased`. (This would also filter other character, e.g. in the input strings `Testing Testing One Two Three4`, `Programming Puzzles and 0Code0 Golf00`, `((((How much wood would (a( woodchuck chuck (if a woodchuck could chuck (wood`, `@ hello` `world`, `7welcome to WATER WORLD7` would also result in the example outputs in the question. But as the input is restricted to `[A-Z a-z]+`, we don't care.)

The last clause it simply the expression `c` – which will be included if the if clause's condition is true, and omitted otherwise.

The resulting iterable is passed to the String's class constructor, which iterates over it and creates the string.

As a bonus, here is a version which works for all of unicode:

```
String r(String i) =>
        String {
    if (exists f = i[0])
        for (c in i.rest)
            if (c.uppercased != f.uppercased)
                c };

```

After space-removal this is 93 bytes:

`String r(String i)=>String{if(exists f=i[0])for(c in i.rest)if(c.uppercased!=f.uppercased)c};`

It converts (beside the example phrases) also `Übel wütet der Gürtelwürger` to `bel wtet der Grtelwrger`.

# Answer
> 0 votes
# Simplex v.0.6, 10 bytes

```
bC&0/gi//g
b          ~~ takes input as a string
 C  /  //  ~~ match as SiRegex
  &0       ~~ replace the first cell
     gi    ~~ globally, ignoring case,
           ~~ with the empty string
         g ~~ output the result

```

No regrets about adding a new type of Regular Expression. (`SiRegex` FTW!)

# Answer
> 0 votes
## C(136)

```
#define t(x)(x+32*(x>>5==2))
char*h(char*a,int b,int*c){char*v=a[b+1]?h(a,b+1,c):0;return(b<=*c)?v:&(a[b]=a[b-(*c+=t(*a)==t(a[b]))]);}

```

## Execution

```
void main(){

    char a[]="abac";int v=0;
    printf("%s",h((char*)a,0,&v));
    return;
}

```

## Output

`bc`

* the function is recursive which is called from the initial parameters: h(string,0,0) and returns the beginning of the resulting string.

# Answer
> 0 votes
# Powershell, 62 60 44 bytes

```
$args-replace"$($args.substring(0,1))",""

```

Powershell of all things.

Edit: removed whitespace to save 2 bytes
Edit2: removed type accelerators to save 16 more bytes

# Answer
> 0 votes
# , 6 chars / 13 bytes (non-competitive)

```
ïĥ/⏖î⍀

```

`Try it here (Firefox only).`

As does happen a lot, I beat everyone in char count but not in byte count :P

# Explanation

`ï` is input, `ĥ` is replace, `/...⍀` transpiles to `/.../gi` in JS, and `⏖î` directly replaces the result of `ï[0]` in the compiled code.

# Answer
> 0 votes
# 05AB1E, 7 Bytes

```
¬DŠ-sš-

```

Explanation:

```
¬        # Take the first character of the input
 D       # Duplicate top of the stack
  Š      # Pop a,b,c and push c,a,b
   -     # Remove all occurencies of the first letter
    s    # Swap the two top elements
     š   # Swapcase the top of the stack
      -  # Remove all occurencies of the swapcased letter
         # Implicit: print top of the stack

```

Uses ISO 8859-1 encoding

# Answer
> 0 votes
## Common Lisp, 47 bytes

```
(lambda(s)(remove(aref s 0)s :test'char-equal))

```

# Answer
> 0 votes
# J, 17 bytes

```
#~1-(={.)@tolower

```

## Usage

```
   f =: #~1-(={.)@tolower
   f 'Testing Testing One Two Three'
esing esing One wo hree
   f 'Programming Puzzles and Code Golf'
rogramming uzzles and Code Golf
   f ' hello world'
helloworld

```

# Answer
> 0 votes
# Rebol, 25 bytes

```
print replace/all s s/1{}

```

Alternative function at 28 bytes:

```
func[s][replace/all s s/1{}]

```

# Answer
> 0 votes
# C#, 101 bytes

```
void m(string s){Console.Write(s.Replace(char.ToUpper(s[0]),'\0').Replace(char.ToLower(s[0]),'\0'));}

```

Sadly C# falls short on this one due to not having a case insensitivity option in `Replace` and not having an empty char literal

I tried using regex but it's more bytes (someone might manage shorter with it though)

# Answer
> 0 votes
# Java, 96 bytes.

Java is an unlikely winner, it's pretty verbose even in a golfed form. Here `|32` is to force lower-case comparison regardless of the actual value, doesn't affect space.

```
void m(String s){char[]c=s.toCharArray();for(char a:c)System.out.print((a|32)!=(c[0]|32)?a:"");}

```

At a slightly higher level of `String` class it would be more explicit (121 bytes):

```
void m(String s){String f=s.substring(0,1).toLowerCase();System.out.println(s.replaceAll("["+f+f.toUpperCase()+"]",""));}

```

# Answer
> 0 votes
# Convex, 5 bytes, noncompeting

```
(_±+-

```

Try it online!

# Answer
> 0 votes
# Uiua <sup>SBCS</sup>, 6 bytes

```
▽≠⊢.⌵.

```

Try it!

# Answer
> 0 votes
# Python 3, 55 bytes

```
lambda s:''.join(c*(c.lower()!=s[0].lower())for c in s)

```

Try it online!

Outgolfed, but I like the elegance :)

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