title: Bitwise XOR of floats

text:
# Question
Title: Bitwise XOR of floats
This is different from Floating Point XOR, and more in the spirit of a comment by R.. GitHub STOP HELPING ICE on that challenge, but I thought of this idea independently.

## Generalized XOR

The bitwise exclusive or (XOR) operation is usually considered in terms of integers, but it can be naturally generalized (extended, in fact!) to real numbers. There are some finicky details when asking which representation to choose for finite expansions, but to simplify matters, we will only use binary floats. For example, `3.141592653589793 ^ 0.2` is

```
3.141592653589793: 11.001001000011111101101010100010001000010110100011000
0.200000000000000: 00.0011001100110011001100110011001100110011001100110011010
                   11.000101110000110001011001101110111011011010010000010...
                       ≈ 3.090032203987506

```

The values were written out exactly and a bitwise XOR performed. Note that the result is not always exactly representable as a double, but we can round.

## Challenge

Given two positive (IEEE-754) double-precision floating-point numbers, find their XOR as *numbers*. The answer must have a *relative* accuracy of `1e-6`, i.e., the error should be at most `1e-6` times the correct answer. (The error bound is there because the result is not always exactly representable.)

Examples (rounded to within 1 ulp—answers may vary):

```
1 ^ 2 -> 3
3.141592653589793 ^ 2.141592653589793 -> 1
2.718281828459045 ^ 2.141592653589793 -> 0.5776097723422073  (funnily close to the Euler–Mascheroni constant)
1000000000 ^ 0.1 -> 1000000000.1
0.002 ^ 0.0016666666666666668 -> 0.0036340002590589515
0.002000000000000001 ^ 0.002 -> 8.6736173798840355e-19
1e+300 ^ 1 -> 1e+300
1e+300 ^ 4e299 -> 1.2730472723278628e+300
0.1 ^ 0.1 -> 0
7.888609052210118e-31 ^ 5.380186160021159e-32 -> 8.426627668212235e-31

```

### Notes

Subnormal numbers (), nonpositive numbers, and non-finite numbers do not need to be supported, but it should output zero when the operands are equal. Standard loopholes are of course not allowed, and the inputs may be given in any format corresponding closely to a float (decimal, 64-bit integer bit representation, etc.). This is a code golf question; may the shortest answer win.

# Answer
# JavaScript, 47 bytes

```
f=(x,y,k=8**341)=>k&&k*(x<k^y<k)+f(x%k,y%k,k/2)

```

Try it online!

`k` runs through every representable power of 2 and adds it to the result, or not, as appropriate.
> 10 votes

# Answer
# Python 3, 57 bytes

```
f=lambda a,b,e=8**341:e and(a//e+b//e)%2*e+f(a%e,b%e,e/2)

```

Try it online!
> 4 votes

# Answer
# C (gcc), 223 bytes

```
typedef double D;D f(D x,D y){D z;long m,o,a,c,b,d;x<y?z=x,x=y,y=z:0;m=-1lu>>12;o=1l<<52;a=*(long*)&x;b=*(long*)&y;c=a>>52;d=b>>52;b=__builtin_clzl(a=(a&m|o)^(b&m|o)>>(c-d<53?c-d:53))-11;a=a?a<<b&m|c-b<<52:0;return*(D*)&a;}

```

Try it online!

(-11 bytes @ceilingcat)

I thought directly manipulating the bit representation would be the shortcut, but it wasn't..

A bit ungolfed,

```
typedef double D;
D f(D x,D y){
  D z;
  long m,o,a,c,b,d;
  x<y?z=x,x=y,y=z:0;
  m=-1lu>>12;
  o=1l<<52;
  a=*(long*)&x;
  b=*(long*)&y;
  c=a>>52;
  d=b>>52;
  b=__builtin_clzl(a=(a&m|o)^(b&m|o)>>(c-d<53?c-d:53))-11;
  a=a?a<<b&m|c-b<<52:0;
  return*(D*)&a;
}

```
> 4 votes

# Answer
# C (gcc), ~~202~~ 196 bytes

*-6 bytes thanks to @ceilingcat*

```
double a,b,t;long*c=&a,*d=&b,r,e,m=1L<<52;main(){scanf("%lf%lf",c,d);b>a?t=a,a=b,b=t:0;for(r=(*c&m-1|m)^(*d&m-1|m)>>(*c>>52)-(*d>>52),e=*c&m*4095;*c^*d&&!(r&m);r+=r)e-=m;*c=e|r&~m;printf("%f",a);}

```

Try it online!

What the program basically does:

* save two doubles from `stdin` into variables `a` and `b`; if needed, swap the two doubles so `a>b` always;
* take the exponent of `a` as the exponent of the result;
* take the fraction parts of `a` and `b`, the leading implicit bit, left shift `b` (according to the exponents difference), and XOR the two values to obtain the fraction of the result;
* finally, in the result if there are leading zeros in the fraction, remove them (and decrement the exponent).
> 4 votes

# Answer
# Wolfram Language (Mathematica), 58 bytes

```
Plus@@Apply@Xor//@{0,(i=#2;2^--i#&/@#)&@@@#~RealDigits~2}&

```

Try it online!

Input two `Real`s in a list. Also works with an arbitrary even number of `Real` arguments.
> 4 votes

# Answer
# x86-64 machine code, x32 ABI, ~~64~~ ~~58~~ ~~55~~ ~~54~~ ~~53~~ ~~49~~ ~~48~~ ~~46~~ 44 bytes

xxd output:

```
00000000: 87fc 5859 5e5a 6629 d17d 0548 96f7 d9eb  ..XY^Zf).}.H....
00000010: 01ca 6683 f940 7d0f 48d3 ee48 31f0 87d1  ..f..@}.H..H1...
00000020: 7805 48d1 e0e2 f951 5089 fcc3            x.H....QP...

```

In assembly, with comments:

```
xor_double:
    xchg esp,edi # save stack pointer and points new stack at the input

    # long doubles are 80-bit floating point numbers,
    # with the low 8 bytes giving the significand and the high 2 bytes giving the exponent
    # Conveniently, long doubles have an alignment of sixteen, so the "stack" now looks like:
    #  rsp    --> significand of first argument
    #  rsp+8  --> exponent of first argument (plus six bytes of junk)
    #  rsp+10 --> significand of second argument
    #  rsp+18 --> exponent of second argument (plus six bytes of junk)
    # So, just 4 pops puts all the arguments into registers:

    pop rax # rax=sig1
    pop rcx # rcx=junk48:exp1
    pop rsi # rsi=sig2
    pop rdx # rdx=junk48:exp2

    # check which argument is greater and swap the two if the second is greater. Otherwise swap them

    sub cx,dx   # find difference of exponents
    jge good    # jmp if exp1 >= exp2

    # exp1 < exp2, switch around the arguments

    xchg rsi,rax
    neg ecx

    # note that dx is unchanged and is now the biggest exponent- this will also be true in the other branch

    # This next two opcodes assemble together to EB 01 CA. If decoded from here, that is "JMP $+1 ; .byte CA", which skips the CA byte
    # But the "jge good" earlier jumps to the middle of EB 01 and so it is instead decoded as "01 CA", or "add edx,ecx"
    .byte 0xEB
good:
    add edx,ecx
    # dx=cx-dx+dx=original value of cx, the biggest exponent

switched:
    cmp cx,0x40 #ratio >= 2**64, just return initial number
    jge dontxor
    shr rsi,cl  #shift the smaller significand so they line up
    xor rax,rsi

    # the significand of a floating point number always has 1 as its MSB.
    # so if it's missing, shift the bits around to restore it
    # i.e. multiply significand by two and subtract one off the exponent until the MSB is 1

    xchg ecx,edx
subnormal_loop: #multiply significand by two and subtract exponent by 1 until either exponent is zero or the number is normal
    js dontxor #done
    shl rax
    loop subnormal_loop #decrements ecx and jmp if not zero

dontxor:
    # return output in long_double[1]
    # put exponent in place
    push rcx
    # put significand in place
    push rax
    # restore the stack pointer
    mov esp,edi
    ret

```

Takes a pointer to an array of 80-bit x87 long doubles and returns in the 2nd element of the array. Uses the x32 ABI (not to be confused with x86-32), which is just like the usual System V ABI, but all pointers are 32 bits.

The padding outside the actual 10-byte long doubles is allowed to be garbage, not zero, which means we have to be careful when comparing or using FLAGS results from operations on exponents: 16-bit operand-size is necessary because we loaded the whole qword including high garbage into the full register.

Because it uses the x32 calling convention, you can compile this and link it with a C program to test it, with the function prototype `void xor_double(long double[2])`. You will need to compile it as x32, though.

The strategy is to shift the smaller number's significand to the right, by the difference in exponent. This aligns the significand to the place-value position of the significand of the larger, like they were fixed-point. (This may mean shifting out all the bits if the exponents are different by 64 or more, but x86 scalar shifts mask the count by &63 or &31 so we need to special-case that).

Then xor the aligned significands and use this as the 64-bit significand with the larger exponent.

80-bit long double has an *explicit* leading 1 in the 64-bit significand, unlike 64-bit double (IEEE binary64) using an implicit 1 (implied by a non-zero exponent field). That means shift/xor Just Works on the significand field directly.

But we still need to renormalize when equal exponents cause the leading 1 bits cancel between significands. Other than subnormals (where the exponent field is zero), `long double` values with bit 63 clear are not valid. (8087 and 80287 allow them as "unnormal" according to Wikipedia, but hardware operations on such a value on 387 and later treat them as invalid, producing NaN. All x86-64 CPUs include 387-compatible FPUs, and we need 64-bit mode to make it convenient to deal with a 64-bit significand.)

The renormalization uses a `loop` command, which decrements the exponent and jumps back to the start of the loop. This is necessary because if the significand is zero, the exponent must also be cleared or the result is an invalid floating point number. This actually clears `rcx` in that case, not just `cx`, which potentially makes the program take (much) longer, but is harmless otherwise.

The renormalization loop also handles the case of two equal inputs, where xoring aligned significands leaves zero. We shift left (and decrement the exponent) until a 1 bit appears at the top of the significand (normal case), or the exponent field becomes zero. (Producing a subnormal or a zero).

This handles the equal-input case because left-shifting an all-zero significand will never shift a 1 to the top, so eventually the exponent becomes zero. If there is a 1 bit somewhere but the exponent becomes zero before it gets to the top, in that case it is a valid subnormal value. (Too small to be representable as a normalized float.) The question doesn't require us to support subnormal inputs or outputs so the actual correct value isn't required in this case, although it probably is correct. This ended up being shorter than `lzcnt` / `shl` plus branching for special cases.

At the end, it returns a `long double*`, which "conveniently" points to `[rsp]` right after the function call. Returning a pointer into the calling function's stack frame is perhaps somewhat malicious compliance with the calling conventions, but it works!

Some general notes on registers:

* I avoid `rbx`, `rbp`, and `rsp` as registers because the System V ABI forbids changing them without saving their previous value, which costs some bytes.
* I avoid `r8-r15` because they cost an extra byte for most uses.
* In most cases using a 32-bit register saves some bytes, so I only use `cx` and `dx` when the junk in the higher bits of the registers would get in the way.
* Using `rax` instead of any other register for one of the significands saves a byte on `xchg`, since `xchg rax,[anything]` is two bytes instead of three.
* `ecx` has many special uses. It is the only register allowed for `shr [reg],cl`, and `rcx` is the only one used by `loop`. That is why the `xchg ecx,edx` is required to put the exponent in this special register.

Try it online! Note that TIO doesn't appear to support the x32 ABI, so I simulated it by using `mmap` to create a new stack at a 32 bit address.
> 4 votes

# Answer
# Charcoal, 45 bytes

```
Ｆ²⊞υＮ≔Ｘ²⁺φ²³η≔⁰ζＷ⌈υ«Ｆ﹪ΣＥυ‹κη²≧⁺ηζ≧﹪ηυ≧∕²η»⭆¹ζ

```

Try it online! Link is to verbose version of code. Note: Charcoal requires floating-point numbers to contain a `.`, which is why the link uses `1.0e+300` as the first input. Explanation:

```
Ｆ²⊞υＮ

```

Input the two numbers.

```
≔Ｘ²⁺φ²³η

```

Start at `2¹⁰²³`.

```
≔⁰ζ

```

Start with a zero result.

```
Ｗ⌈υ«

```

Repeat until the inputs are zero.

```
Ｆ﹪ΣＥυ‹κη²

```

If exactly one of the inputs is less than the power of `2`, then...

```
≧⁺ηζ

```

... add that power of `2` to the total.

```
≧﹪ηυ

```

Subtract the power of `2` from those inputs that are not lower.

```
≧∕²η

```

Halve the power of `2`. (Sadly I can't use `Halve` here because it rounds the result for some inexplicable reason.)

```
»⭆¹ζ

```

Format the result as a float. (Charcoal defaults to formatting large floats as an integer.)
> 3 votes

# Answer
# Swift Language, 113 bytes

```
typealias D=Double;let c=D(bitPattern:1<<32);let x:(D,D)->D={D(bitPattern:($0*c).bitPattern^($1*c).bitPattern)/c}

```

Try it online!

Based on the 87 byte GCC answer. Unfortunately swift's verbosity gets in the way of brevity when bitcasting
> 3 votes

# Answer
# Assembly (gcc, x64, Linux), custom ABI, ~~39~~ 37 bytes

xxd dump:

```
00000000: 5f58 595e 5a29 d17d 0548 96f7 d9eb 01ca  _XY^Z).}.H......
00000010: e305 48d1 eee2 f948 31f0 87d1 7805 48d1  ..H....H1...x.H.
00000020: e0e2 f957 c3                             ...W.

```

Uses the System V ABI, but returns long doubles in cx:rax, high bits of variables passed on the stack must be zeroed, and `rsp` is decremented by `0x20` per call.

```
xor_double:

    # Custom ABI: like System V but returns long doubles in cx:rax, zeroes out high bits of stack variables, and decreases rsp by 0x20

    # System V passes long doubles on the stack. long doubles are 80-bit floating point numbers,
    # with the low 8 bytes giving the significand and the high 2 bytes giving the exponent
    # Conveniently, long doubles have an alignment of sixteen, so the stack looks like
    #  rsp    --> return address
    #  rsp+8  --> significand of first argument (plus six bytes of zeroes)
    #  rsp+10 --> exponent of first argument
    #  rsp+18 --> significand of second argument (plus six bytes of zeroes)
    #  rsp+20 --> exponent of second argument
    # So, just 5 pops puts all the arguments into registers:

    pop rdi # rdi=return address
    pop rax # rax=sig1
    pop rcx # rcx=0:exp1
    pop rsi # rsi=sig2
    pop rdx # rdx=0:exp2

    # check which argument is greater and swap the two if the second is greater. Otherwise swap them

    sub ecx,edx   # find difference of exponents
    jge good      # jmp if exp1 >= exp2

    # exp1 < exp2, switch around the arguments

    xchg rsi,rax
    neg ecx

    # note that edx is unchanged and is now the biggest exponent- this will also be true in the other branch

    # This next two opcodes assemble together to EB 01 CA. If decoded from here, that is "JMP $+1 ; .byte CA", which skips the CA byte
    # But the "jge good" earlier jumps to the middle of EB 01 and so it is instead decoded as "01 CA", or "add edx,ecx"
    .byte 0xEB
good:
    add edx,ecx
    # dx=cx-dx+dx=original value of cx, the biggest exponent

switched:
    jrcxz equal
    shr rsi #shift the smaller significand so they line up
    loop switched
equal:
    xor rax,rsi

    # the significand of a floating point number always has 1 as its MSB.
    # so if it's missing, shift the bits around to restore it
    # i.e. multiply significand by two and subtract one off the exponent until the MSB is 1

    xchg ecx,edx
subnormal_loop: #multiply significand by two and subtract exponent by 1 until either exponent is zero or the number is normal
    js done #not subnormal
    shl rax
    loop subnormal_loop

done:
    push rdi #push return address
    ret

```

Try it online!

The overall strategy is similar to my other answer, and most of @PeterCordes's very helpful contribution still applies. This answer saves:

* two bytes by avoiding otherwise useless pushes at the end (and thus decrements `rsp` by two). This also makes a loop strategy `jrcxz; shr rsi; loop` shorter than `cmp cx,0x40; jge; shr rsi,cl`. I can't use that in the first answer because it depends on `rcx`, which is full of junk.
* one byte every time `ecx` or `edx` is used instead of `cx` (which can only be done by insuring that the higher bits are set to zero in the function call).
* five bytes by returning in `rax:rdx` instead of the x87 stack, which removes the need to push the result back on the stack and use `fld tbyte ptr [rsp]` to load it into the x87 stack.
> 3 votes

# Answer
# Vyxal , 10 bytes

```
k⁋E*÷꘍k⁋E/

```

Try it Online! or Verify all test cases!

For the `0.002000000000000001 ^ 0.002` test case, it unfortunately fails because it seems to automatically round it to `0.002`. It does work with three zeros removed, though. This seems to be a problem with `sympy.nsimplify`:

```
>>> sympy.nsimplify(0.002000000000000001, rational=True)
1/500
>>> sympy.nsimplify(0.002000000000001, rational=True)
2000000000001/1000000000000000

```

(from Python REPL)

## How?

```
k⁋E*÷꘍k⁋E/
k⁋         # Push 1024
  E        # Push 2**1024
   *       # Multiply the (implicit) input pair by that
    ÷      # Push both elements of the multiplied pair to the stack
     ꘍     # Bitwise XOR them
      k⁋E/ # Divide by 2**1024

```
> 2 votes

# Answer
# Julia 1.0, 51 bytes

```
f(a,b,e=8^341.)=e>0&&(a÷e+b÷e)%2*e+f(a%e,b%e,e/2)

```

Try it online!

port of m90's answer

I tried so many things but always landed on 51 bytes
> 1 votes

# Answer
# C (gcc), 87 bytes

```
typedef double d;d c=1LL<<32;d x(d a,d b){return((long long)(a*c)^(long long)(b*c))/c;}

```

In the spirit of the Python answer above, converts to a fixed point integer and does the XOR, before converting back. It only has 32 bits of precision to either side of the decimal point, assuming `long long` is 64 bits wide, which is exactly the worst precision allowed by the challenge (1e-6). Because of this, the 1e300 answers overflow.

If your platform has 64-bit `long`s 11 bytes can be saved, for a total of 76 bytes:

```
typedef double d;d c=1L<<32;d x(d a,d b){return((long)(a*c)^(long)(b*c))/c;}

```
> 0 votes

# Answer
# Stax, 25 bytes

```
∩√=êⁿ;r⌂$══▓ìêCO¥ÇnµtƒÉd+

```

Run and debug it
> 0 votes

# Answer
# C (gcc), 96 bytes

```
#define D double
#define P*(long*)
D z;D f(D x,D y){P&z=P&x^P&y;z=x>=y&x<2e-308?z:f(y/2,x/2)*2;}

```

Try it online!

subnormal number is good

# JavaScript (Node.js), 81 bytes

```
f=(x,y)=>x+y>1e60?+[g(x)^g(y)]:f(x*2,y*2)/2
g=x=>BigInt(x%1?0:'0o'+x.toString(8))

```

Try it online!

Base 8 to avoid `e+66`, `>1e60` to avoid overflow
> 0 votes

---
Tags: code-golf, binary, floating-point
---


title: Rolling a 1x1x2 block

text:
# Question
Title: Rolling a 1x1x2 block
# Rolling a 1x1x2 block

This challenge is inspired by the game Bloxorz. Like that game, there is a 1x1x2 block, which may be moved on a square grid in any of the four cardinal directions. It moves by rotating 90 degrees about one of its edges which is touching the ground. Initially, the block is standing upright on a single square in a square grid. After some sequence of moves, determine whether it is:

* Standing upright on the starting square,
* Laying half-on, half-off the starting square, or
* Not on the starting square at all.

## Input

Input is given as a string consisting of the characters `F`, `B`, `L`, and `R`, which represent moving forward, backward, left, and right.

## Output

Output can be 1, 0.5, or 0, representing the fraction of the block resting on the starting square. Your program may use some other set of three distinct outputs, as long as they consistently represent the three possibilities.

## Test cases

```
"FFFBBB" -> 1
"" -> 1
"FRRRBLL" -> 1
"FRBL" -> 0.5
"FRBBL" -> 0

```

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

*-3 thanks to @Steffan, and -2 from there*

Expects an array of ASCII codes. Returns \\$0,1,2\\$ instead of \\$0,1/2,1\\$.

```
a=>a.map(d=>o=(p[d<76|0]+="011343011334"[o+=d%7%4*3]-2,2-o%9&7)%3,p=[o=0,0])|o?3>>p[o-1]+1&!p[2-o]:(p=='0,0')*2

```

Try it online!

### How?

We keep track of the orientation \\$o\in\[0,1,2\]\\$ of the rolling block and the position \\$p=(x,y)\\$ of its top-left cube as described in this diagram:

Given the ASCII code \\$d\\$ of a direction character, we can turn it into a value in \\$\[0,1,2,3\]\\$ by reducing it modulo \\$7\\$ and then modulo \\$4\\$. To determine whether it's a vertical or horizontal move, we can simply test \\$d\<76\\$.

| Character | d = ASCII code | d mod 7 | (d mod 7) mod 4 | d \< 76 |
| --- | --- | --- | --- | --- |
| "B" | 66 | 3 | 3 | true |
| "F" | 70 | 0 | 0 | true |
| "L" | 76 | 6 | 2 | false |
| "R" | 82 | 5 | 1 | false |

We use a lookup string of digits in \\$\[0\dots4\]\\$ to get either \\$dx+2\\$ or \\$dy+2\\$:

```
p[d < 76 | 0] += "011343011334"[o += d % 7 % 4 * 3] - 2

```

The new orientation is given by the following magic formula (found by Steffan):

```
o = (2 - o % 9 & 7) % 3

```

Once all iterations have been processed, the test to be applied depends on the final value of \\$o\\$.

```
o ?
  3 >> p[o - 1] + 1 & !p[2 - o]
:
  (p == '0,0') * 2

```
* \\$o=0\\$ : return \\$2\\$ if \\$x=0\\$ and \\$y=0\\$, or \\$0\\$ otherwise
* \\$o=1\\$ : return \\$1\\$ if \\$y=0\\$ and \\$x\in\[-1,0\]\\$, or \\$0\\$ otherwise
* \\$o=2\\$ : return \\$1\\$ if \\$x=0\\$ and \\$y\in\[-1,0\]\\$, or \\$0\\$ otherwise
> 7 votes

# Answer
# Jelly, 39 bytes

Maybe there is a clever string replacement or complex number algorithm that'll crush this score?

```
NÑN
=ḞḢH‘ɓ+0¦
ṚÇṚ
Ṛ1ĿṚ
⁹Ŀ
O:5%6çƒØ0AṀ«1

```

A full program which accepts the string and prints \\$0\\$ (standing at the origin), \\$\frac{1}{2}\\$ (covering the origin, but laying down), or \\$1\\$ (neither).

**Try it online!**

### How?

Starts at \\$\[0,0\]\\$ and executes the string as instructions tracking coordinates of the centre of the block (i.e. executing `F` would lead to \\$\[0,1.5\]\\$) then inspects the resulting position.

Note, right and left are actually mirrored to make the code slightly shorter, so executing `R` would lead to \\$\[-1.5, 0\]\\$.

```
NÑN            - Link 1 (B): [x, y]
N              - negate
 Ñ             - call the next Link (Link 2) as a monad
  N            - negate

=ḞḢH‘ɓ+0¦      - Link 2 (F): [x, y]
 Ḟ             - floor -> [floor(x), floor(y)]
=              - ([x, y]) equals? (that) (vectorises)
  Ḣ            - head -> x eqauls floor(x)?
   H           - halve
    ‘          - increment -> 1 if rolling or 1.5 if toppling or erecting
     ɓ         - start a new chain with swapped arguments
       0¦      - apply to index 0 (the y of [x, y])
      +        -   add

ṚÇṚ            - Link 3 (L): [x, y]
Ṛ              - reverse
 Ç             - call the last Link (Link 2) as a monad
  Ṛ            - reverse

Ṛ1ĿṚ           - Link 4 (R): [x, y]
Ṛ              - reverse
  Ŀ            - monadic call to Link:
 1             -  1
   Ṛ           - reverse

⁹Ŀ             - Link 5 (call correct function): location [x, y]; instruction N
 Ŀ             - monadic call to Link:
⁹              -   chain's right argument = N
               - ...i.e. call Link N with argument [x, y]

O:5%6çƒØ0AṀ«1 - Main Link: list of characters, S
O             - ordinals (S) e.g. "BFLR" ->[66,70,76,82]
 :5           - integer divide by five   ->[13,14,15,16]
   %6         - mod six                  ->[ 1, 2, 3, 4]
      ƒØ0     - starting with [x,y]=[0,0] reduce that using:
     ç        -   call the last Link (Link 5) as a dyad
         A    - absolute values (that)
          Ṁ   - maximum
           «1 - minimum of that and one

```
> 3 votes

# Answer
# Charcoal, ~~78~~ 43 bytes

```
≔ＵＶ1jθ≔Ｅ²θηＦＥＳＸθ⌕FRBιＵＭη⁺κ×ι⊕№⁺⁻ηι…ηλκＩ⊘№ηθ

```

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

```
≔ＵＶ1jθ

```

Get `i` (square root of `-1`) into a variable.

```
≔Ｅ²θη

```

Start off with both cubes of the block on the starting square, which I've chosen to be `i` as it's golfier that way.

```
ＦＥＳＸθ⌕FRBι

```

Convert the movements into powers of `i` (`F = 1, R = i, B = -1, L = -i`) and loop over them.

```
ＵＭη⁺κ×ι⊕№⁺⁻ηι…ηλκ

```

Calculate which cube (if any) needs to move two squares (if both cubes were on the same square then I move the second cube two squares otherwise if one cube would have moved onto the square the other cube vacated then that cube moves two squares so that both cubes end up on the same square) and move the cubes appropriately.

```
Ｉ⊘№ηθ

```

Output half of the number of cubes that have returned to the starting square.
> 3 votes

# Answer
# Python 3.8+, 173 bytes

```
f=lambda s,c=[0,0]:f(s[1:],[v*n for v in(lambda x,y:[x,y+1.5-x%1])(*[w*n for w in c[::r]])[::r]])if s and[n:=2*(s[0]in"BL")-1,r:=2*(s[0]in"RL")-1]else min(1,max(map(abs,c)))

```

A recursive function that accepts a string ,`s`, and returns \\$0\\$ (standing at the origin), \\$\frac{1}{2}\\$ (covering the origin, but laying down), or \\$1\\$ (neither).

**Try it online!**
> 3 votes

# Answer
# Python3, 356 bytes:

```
m={'F':[0,1],'B':[0,-1],'L':[1,-1],'R':[1,1]}
def M(x,c,o):p,v=m[x[0]];J=c[[0,-1][v!=1]][0];K=c[[0,-1][v!=1]][1];return[[([(J+2*v,K),(J+v,K)],1),([(J+v,K)],0),([(x+v,y)for x,y in c],o)][o],[([(J,K+2*v),(J,K+v)],2),([(x,y+v)for x,y in c],o),([(J,K+v)],0)][o]][p]
f=lambda x,c=[(0,0)],o=0:1*((0,0)in c)/len(c)if''==x else f(x[1:],*M(x,sorted(c,reverse=1),o))

```

Try it online!
> 2 votes

# Answer
# , 54 bytes

```
1#.0=&><@0 0(2$]-.~]+(*1,1+=/))&.>/@,~0j1<@^'RFLB'i.|.

```

Try it online!

Output:

* 2 = fully on origin
* 1 = half on origin
* 0 = not on origin

## idea

We imagine the moving block as two separate squares which move around together, sometimes sliding on top of one another (flat to upright), sometimes spreading out (upright to flat), sometimes moving in parallel (flat rolling). For example, Consider `FFRR`:

```
0   0   <- start, both blocks on origin
0j1 0j2 <- F, blocks slide apart
0j3 0j3 <- F, blocks slide together
1j3 2j3 <- R, blocks slide apart again
1j2 2j2 <- B, blocks move in parallel

```

At a high level, it works like this:

1. `0j1<@^'RFLB'i.|.` Map `RFLB` to the complex numbers `1 0j1 _1 0j_1`, reverse them, and append `0 0` (the starting point of our two sliding blocks), setting ourselves up for a single reduction.
2. `2$]-.~]+(*1,1+=/)` The reduction logic. Multiply the current "step direction" by either `1 1` or `1 2`. Multiply by `1 1` if our sliding blocks are currently separate, and by `1 2` (to separate them) if they are currently overlapping.
3. `]+` Add that adjusted "step direction" elementwise to the current position to create two new positions...
4. `]-.` And set minus the current positions from the new ones.
5. `2$` Ensure the new position is extended to two elements -- in the case that we go to standing long ways, the previous step will only return a single result -- the new position -- and so we have to duplicate that.
> 2 votes

# Answer
# C++ (gcc), 145 bytes

A little late to the party, but here is my two cents (or 145, rather).

Outputs:

* 2 = Standing upright on origin
* 1 = Half-on, half-off the origin
* 0 = Not on the origin

```
int f(char*s){int d=0,p=0;for(s--;*++s;){int n=*s>71?*s>79?3:-3:*s>69?2:-2;p+=d&&d!=n?n:n*2;if(d==-n||d==n)d=0;else if(!d)d=-n;}return!p+!(p+d);}

```

Try it online!

## Explanation

We store the direction the block is facing in variable `d` and the position of one side of the block in variable `p`. We then use numbers 2 and 3 to represent the directions (with ±2 being forward/backward and ±3 being right/left), since 2 and 3 are linearly independent so we can represent any position that way with a single variable.

We then check if `p` equals 0 and if `p+d` equals 0, and add those values. If both `p == 0` and `p+d == 0`, then we are standing upright on the origin. If one of `p == 0` and `p+d == 0` is true, then we are sideways on the origin (since p is always tracking the same end of the block). If neither is true, then we are not on the origin.

### Ungolfed

```
int f(char*s) {
    int d = 0;  // Direction of the block (-2 = back, +2 = front, -3 = left, +3 = right)
    int p = 0;  // Position of the block

    // Loop through the string with pointer arithmetic. When we reach \0, we break out.
    for (s--;*++s;) {
        // The current movement of the block.
        int n = *s > 71 ? (*s > 79 ? 3 : -3) : (*s > 69 ? 2 : -2);

        p += (d && d != n) ? n : n*2;  // If (d == 0 || d == n) (if d is upright or d and n are in the same direction), add 2n. Otherwise, add n. (we flipped the conditional to save a byte)
        if (d == -n || d == n) d = 0;  // If (d == -n || d == n) (in other words, if d is aligned with n), set d to be 0 (upright).
        else if (d == 0) d = -n;       // If no direction (block is upright), set d to be -n.
                                       // Otherwise, don't touch d since we are rolling "sideways", so the direction does not have to change.
    }
    return !p+!(p+d);                  // If p+d == 0, then the block is either straight or sideways on the origin. If additionally, p == 0, then the block is straight and on the origin.
}

```
> 0 votes

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

```
a=>a.map(d=>p[k=d<76|0]+=~-(d/2&2)*(p[1-k]&1^3),p=[0,0])|'21'[p[0]**2+p[1]**2]

```

Try it online!

Only even positions are tile. Position \[1,0\] mean half on \[0,0\] and half on \[2,0\]. Position \[1,1\] unused

| Character | d = ASCII code | d in binary | d / 2 & 2 | d \< 76 |
| --- | --- | --- | --- | --- |
| "B" | 66 | 1000010 | 0 | true |
| "F" | 70 | 1000110 | 2 | true |
| "L" | 76 | 1001100 | 2 | false |
| "R" | 82 | 1010010 | 0 | false |

```
a=>                   // Take Buffer input instead to save a byte
a.map(d=>             // For each instruction
  p[k=d=='B'|d=='F']  // Dimension
  +=((d/2&2)-1)       // Direction
  *(p[1-k]%2?2:3)     // If lay on another direction, move 1
  ,                   // Else move 1.5
  p=[0,0]
)|(                   // Result
  p[0]**2+p[1]**2==0?2:p[0]**2+p[1]**2==1?1:0
)

```
> 0 votes

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


# Question
Title: add commas to Numbers without String manipulation
This challenge consist in adding commas to numbers every `3` spaces like:

```
123456789 => 123,456,789

```

## Specifications:

* The possible inputs will be `1,000 <= input <= 100,000,000`
* You can ONLY use Mathematical Operators
* (\*) You can NOT do string, array, index or character manipulation
* You can NOT use any kind of built-in functions that add these commas
* The zeros should remain, ex `10000 => 10,000`
* You need to print/alert/log the output (so "the output is at x var" is not allowed)

(\*) the only exception is when forming/printing the output (but not in a manner that suggest cheating)

## Examples

```
10100 => 10,100
120406 => 120,406
999999999 => 999,999,999

```

---

**A basic idea on how to get numbers legally:**

```
n = 123456;
m = roundDown(n / 10);//even if ends with .9
d = n - m;//we get the last number

```

# Answer
## GolfScript, ~~13~~ 37 chars

```
0:|;~{.10%|):|3%''','if@10/.9>}do]-1%

```

Look, Ma, no arrays!

Well, almost. The pieces of the output are collected on the stack in right-to-left order, so the final `]-1%` is needed to reverse them. But I assume that's OK, as it counts as "forming/printing the output".

Here's an ungolfed version with comments:

```
0 :| ;         # initialize the variable | to the value 0
~              # eval the input, turning it from a string into a number

{              # start of loop
  .            # duplicate the number on top of the stack; we'll need it later
  10 %         # take the remainder modulo 10 and leave it on the stack

  | ) :| 3 %   # increment | by one and take the remainder modulo 3 of the result
  '' ',' if    # if the remainder is 0, push a comma onto the stack, else an empty string

  @            # pull the value we saved at the start of the loop to top of the stack
  10 /         # divide it by ten, rounding down
  . 9 >        # check if the result is greater than 9...
} do           # ...and repeat the loop if so

]              # finally, collect the digits and commas off the stack into an array...
-1 %           # ...and reverse it for output

```

---

If it weren't for a few pesky details, the following 13-char solution would be pretty hard to beat:

```
~1000base','*

```

However, it fails on two counts: it doesn't correctly preserve leading zeros in digit groups, and the built-in base conversion operator `base` *might* be considered "array manipulation", since it takes a number and returns an array of digits.

---

Ps. Here's an older 49-char arrayless solution:

```
~{.999>}{:^1000%:&9&>99&>+{0}*','^1000/}while]-1%

```
> 5 votes

# Answer
You weren't very specific on the output format...

## Haskell, 56

```
reverse.takeWhile(>0).map(`mod`1000).iterate(`div`1000)

```

example:

```
GHCi> reverse.takeWhile(>0).map(`mod`1000).iterate(`div`1000)$93842390862398
[93,842,390,862,398]

```
> 6 votes

# Answer
## Python 2, 86 chars

I figured this warranted a different enough answer. The first answer is for 3.0 only because of the print statement with `end=`, and this answer because division automatically floors instead of converts to float, and the use of backticks

```
b=input()
k=0
x=''
while b>0:
 x=`b%10`+x;b/=10;k+=1
 if k%3==0and b>0:x=','+x
print x

```

Only string manipulation is building the output

edit: by adding 5 characters `int()`, this program can accept any integer, even above 1 billion. The previous program inserts `L`s (python longs) if the number is too large, but is still within the constraints of the challenge. Here is the program that works with any integer:

```
b=input()
k=0
x=''
while b>0:
 x=`int(b%10)`+x;b/=10;k+=1
 if k%3==0and b>0:x=','+x
print x

```

-

```
879612587634598623589762354009
879,612,587,634,598,623,589,762,354,009

```
> 2 votes

# Answer
AWK, no strings, 84 chars:

```
{for(p=$0;.1<p/=10;++i);for(;i-->0;printf i&&i%3==0?"%d,":"%d",$0/10**i%10);print""}

```

Test runs:

```
% awk -f commas.awk <<< 1230
1,230
% awk -f commas.awk <<< 123012
123,012
% awk -f commas.awk <<< 12301
12,301
% awk -f commas.awk <<< 12301000
12,301,000

```
> 2 votes

# Answer
## C, 136

```
i,j,k;main(m,n){scanf("%d",&n);for(m=n;n^0;i++,n/=10);k=i%3;while(j++<i)printf("%d%c",(int)(m/pow(10,i-j))%10,j%3==k?',':0);putchar(8);}

```
> 2 votes

# Answer
`awk`, 47 chars

> ```
> awk '{for(_=NF-2;1<_;_-=3)$_=","$_}NR' FS= OFS=
>
> ```

```
10,100
120,406
999,999,999

```
> 2 votes

# Answer
## Python, 82 chars

```
n=input()
x=''
while n>999:x=','+`n/100%10`+`n/10%10`+`n%10`+x;n/=1000
print `n`+x

```

I can get it shorter (67 chars) with

```
while n>999:x=',%03d'%(n%1000)+x;n/=1000

```

Not sure if that's legal.
> 1 votes

# Answer
## befunge, 62

```
&# <v%3-\3%3y+8a$j*d`0:/a\%a:
1`j@>:3%\3/!3*j',,\'0+,1+a8+y

```

well this code is array free, since befunge itself is array free.

* the first line simply reads a number and push every digit into stack.
* the second line reads those digits and prints then once at a time. and put commas if needed.

note that if you are trying to run it using rcfunge, you need run using "-Y" option.
> 1 votes

# Answer
### Scala 65:

```
def f(n:Int){if(n<1000)print(n)else{f(n/1000)
print("."+n%1000)}}

```

Testcode:

```
val l=List(1,12,123,1234,12345,123456,1234567)
l.foreach(x=>{f(x);println})

```
> 1 votes

# Answer
## JavaScript ~~104~~, ~~99~~, ~~90~~, 81

> Edit: I just noticed I also have this missing zeros bug when any group of contains 000 ,00X or 0X0. If you see this message, the code below isn't fixed yet

Code:

```
for(n=0,s="",i=m=1e3,r=0;i<n*m;i*=m)r=~~((n%i-r)/i*m),s=r+(i-m?",":"")+s;alert(s)

```

**Note:** change the value of `n` for different inputs
> 0 votes

# Answer
## Python 3, 165 chars

```
from math import*
b=int(input())
j=10**8
k=l=0
while j>0:
 z=int(floor(b/j));b-=z*j;k+=1;j=floor(j/10)
 if not l:l=z!=0
 if l:print(z,end=','if k%3==0and j>0 else'')

```

No strings except for '' and ',', no arrays/lists/tuples/dicts, or indexing

edit: nixxed some characters
> 0 votes

# Answer
## Python 2.6.5, ~~65~~ 94 chars

```
n=input()
s=''
while n:
    s=','+str(x)+s if x else','+'000'+s
    n/=1000
print s[1:]

```

Just used the string to store the output.

~~\*Now preserves zeros~~
> 0 votes

# Answer
## C, 80 chars

Using recursion within `printf` to reverse the printing order (recursion handles the least significant digits first, but printing is done when returning, so they're printed last).

```
n;
p(x) {
    x=n%1000;
    n/=1000;
    printf(n?p(),",%03d":"%d",x);
}
main(){
    p(scanf("%d",&n));
}

```
> 0 votes

---
Tags: code-golf, number
---


# Question
Title: Fastest code: Does a list of string contains %s, %d, %f, or %r?
The aim is to create an algorithm to detect that one of the string in a small list of strings contains `%s`, `%d`, `%f`, or `%r`. All sub-string will start by '%' and be 2 characters longs. Input string will be from 1 to 500 characters with a median of around 20 characters and contain zero to multiple of the possible sub-strings. the number of string in a batch is small, 2 to 5 strings.

Here's the naive python implementation:

```
SUBSTRING_TO_SEARCH_FOR = ["%s", "%d", "%f", "%r"]

def any_substring_in_inputs(inputs: list[str]) -> bool:
    for input in inputs:
        for substring in SUBSTRING_TO_SEARCH_FOR:
            if substring in input:
                return True
    return False

```

The way the values are recovered in inputs isn't important, the algorithm is. The best execution time in a language agnostic environment and in the specified condition win.

There is real world application in pylint, a static analysis tool for python. The best algorithm will be ported to it to detect string with missing formatting parameter automatically.

# Answer
# C (clang), About 25ms for 10 million strings.

```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>

typedef struct
{
    char* ptr;
    size_t len;
} string;

int func(const string* sa, const int n)
{
    int found = 0;
#pragma omp parallel for
    for (int i = 0; i < n; i++)
    {
        if (!found)
        {
            const string* s = sa + i;
            char* ptr = memchr(s->ptr, '%', s->len);
            while (ptr)
            {
                char c = *++ptr;
                if (c == 's' || c == 'd' || c == 'f' || c == 'r')
                {
                    found = 1;
                    break;
                }
                ptr = memchr(ptr, '%', s->len - (ptr - s->ptr));
            }
        }
    }
    return found;
}

void showElapsed(struct timeval start)
{
    struct timeval stop;
    gettimeofday(&stop, NULL);
    printf("%lu ms\n", ((stop.tv_sec - start.tv_sec) * 1000000 + stop.tv_usec - start.tv_usec) / 1000);
}

int main()
{
    srand(time(0));
    struct timeval start, stop;
    int ret;
    int count = 10000000;

    puts("creating input...");
    gettimeofday(&start, NULL);
    string* test = malloc(count * sizeof(string));
    for (int i = 0; i < count; i++)
    {
        const char* txt = "rkjewj%q werhkhr";
        test[i].ptr = strdup(txt);
        test[i].len = strlen(txt);
        test[i].ptr[15] = 65 + rand() % 60;
    }
    showElapsed(start);

    puts("test false");
    gettimeofday(&start, NULL);
    ret = func(test, count);
    gettimeofday(&stop, NULL);
    printf("%d, expected = 0\n", ret);
    showElapsed(start);

    puts("test true");
    test[count - 1].ptr[7] = 'd';
    gettimeofday(&start, NULL);
    ret = func(test, count);
    gettimeofday(&stop, NULL);
    printf("%d, expected = 1\n", ret);
    showElapsed(start);
}

```

Try it online!
> 2 votes

# Answer
# AWK, takes about 150ms for 1 million lines of input

*Edit: messed-up the initial timing by 20x. Sorry.*

```
/%[adfs]/

```

Try it online!

Outputs the line itself (truthy) if it contains `%a`,`%d`,`%f` or `%s`. Outputs nothing (falsy) if it doesn't.

This could be considered a baseline answer: I'm assuming that the regex matching is pretty-well optimized, and AWK doesn't add much overhead onto it (as is probably apparent from the rather minimal program).
Note that this is 10x faster on my MacBook with solid-state storage than on \[Try it online!\].
> 1 votes

# Answer
# Python 3, about 3 microsecs for 1000 strings

```
lambda x:bool([y for y in x if bool([z for z in ["%s", "%d", "%f", "%r"]if z in y])])

```

I don't have the time right now to check for a million strings.
> 0 votes

# Answer
don't short change `awk` -

using a `12.5 mn rows` uncompressed `.txt` test file spanning `1.85 GB`, filled to the brim with multi-byte `UTF-8` characters

— (`349,725,658` multi-byte `Unicode` code points to be exact).

```
rows = 12494275. | UTF8 chars = 1285316715. | bytes = 1983544693.

```

`awk` finished scanning in `887 ms`

(and keep in mind that's inclusive of actually reading `/dev/stdin` instead of just spinning test cases within the program itself)

```
Sun Dec 18 23:26:35 2022 1671423995.300214000

      in0:  219MiB 0:00:00 [2.15GiB/s] [2.15GiB/s] [>] 11% ETA 0:00:00
     out9: 1.36KiB 0:00:00 [1.58KiB/s] [1.58KiB/s] [<=> ]
      in0: 1.85GiB 0:00:00 [2.16GiB/s] [2.16GiB/s] [========>] 100%

( pvE 0.1 in0 < "${m3t}" | mawk2 '/%[dfrs]/'; )

0.58s user 0.44s system 115% cpu 0.887 total

rows       = 7. | UTF8 chars = 1086. | bytes      = 1388.

Sun Dec 18 23:26:36 2022 1671423996.195609000

```
> 0 votes

---
Tags: string, fastest-code
---


# Question
Title: Remove the last 'n' occurences of a substring from a string
Given a string and a substring and a positive integer `n`.

Remove the `n` occurences of a substring from the *end* of the **originally given string**. If the substring is not present in the string or the number of times the substring appears is less than `n`, then the output is the original string. No space should be present in place of the removed substring.

### RULES

1. The shortest code wins the challenge (as this is ).

### Test-cases:

```
Input:
String = "Cats do meow-meow while lions do not meow."
Substring = "meow"
n = 2

Output:
"Cats do meow- while lions do not ."

Input:
String = "Cats do not memeowow, they do meow-ing."
Substring = "meow"
n = 2

Output:
"Cats do not meow, they do -ing."

Input:
String = "Cats do meow-meow while lions do not meow."
Substring = "meow"
n = 4

Output:
"Cats do meow-meow while lions do not meow."

```

# Answer
# Excel (ms365), ~~115~~, 83 bytes

-32 also thanks to @jdt and the idea to split instead of loop.

```
=LET(a,TEXTSPLIT(A1,,B1),b,ROWS(a),IF(b>C1,CONCAT(IF(SEQUENCE(b)<b-C1,a&B1,a)),A1))

```

---

**Note**: This answer has been edited to no longer loop to remove the substring from the *end* of the string, but split the input instead. This would now give the appropriate answer for input like 'Cats do meow not memeowow, they do meow-ing.' where 'n=3'.
> 11 votes

# Answer
# Python, ~~66~~ ~~53~~ 52 bytes

* -1 byte thanks to @92.100.97.109 (though not exactly in the way they intended)

```
lambda i,j,k:[i,''.join(a:=i.rsplit(j,k))][len(a)>k]

```

Attempt This Online!

Returning identity when the occurrences are less than N is annoying.
> 9 votes

# Answer
# C (clang), ~~109~~ ~~107~~ ~~112~~ ~~105~~ 100 bytes

-11 bytes thanks to c--

-2 bytes thanks to ceilingcat

+5 bytes for fixing an error pointed out by JvdV.

```
f(*a,i,*b,j,n,**r){for(*r=wcsdup(a);i--*n>0;)!bcmp(a+i,b,j)?wcscpy(a+i,a+i+j),n--,i-=j:0;!n?*r=a:0;}

```

Try it online!
> 7 votes

# Answer
# T-SQL 135 bytes

Is not looping to avoid the string being created again "memeowow"

```
WITH c(z)as(SELECT 1UNION ALL
SELECT charindex(@r,@,z+1)FROM c WHERE z>0)SELECT top(@n)@=stuff(@,z,len(@r),'')FROM
c ORDER BY-z PRINT @

```

**Try it online**
> 6 votes

# Answer
# Ruby, ~~67~~ ~~61~~ 75 bytes

Updated after clarification by OP, which unfortunately made it longer.

```
->s,u,n,*a{s.scan(u){a<<$`.size}
a.size<n||eval("s[a.pop,u.size]='';"*n)
s}

```

Attempt This Online!
> 6 votes

# Answer
### Python, 51 bytes

```
lambda A,B,n:"".join(A.rsplit(B,n*(n<=A.count(B))))

```
> 6 votes

# Answer
# 05AB1E, 13 bytes

```
¡`.gI›I*F«}¹ý

```

Inputs in the order `substring, string, n`.

Try it online or verify some more `n`.

**Explanation:**

```
¡           # Split the (implicit) second input-sentence on the (implicit) first substring
 `          # Pop and push all parts separated to the stack
  .g        # Get the amount of items on the stack
    I›      # Check if this is larger than the third input-integer `n`
      I*    # Multiply it by the third input-integer `n`
        F   # Loop that many times:
         «  #  Concat the top two parts on the stack together
        }¹ý # After the loop: join the stack with the first input substring as delimiter
            # (after which the result is output implicitly)

```
> 5 votes

# Answer
# JavaScript (ES6), 62 bytes

Expects `(string, substring, n)`.

```
(s,q,n)=>(a=s.split(q))[n]+1?a.map(s=>a[++n]+1?s+q:s).join``:s

```

Try it online!

### Commented

```
(s, q, n) => (   // s = string, q = substring, n = integer
  a = s.split(q) // split s on q and save the result in a[]
                 // if q appears x times, we get x + 1 entries
                 // some of these entries may be empty strings (falsy)
                 // so we do '+ 1' to distinguish between empty and undefined
)[n] + 1 ?       // if a[n] is defined:
  a.map(s =>     //   for each entry s in a[]:
    a[++n] + 1 ? //     increment n; if a[n] is still defined:
      s + q      //       append q to s
    :            //     else:
      s          //       leave s unchanged
  ).join``       //   end of map(); join everything back together
:                // else:
  s              //   return s unchanged

```
> 5 votes

# Answer
# Pip, 30 bytes

```
d:a^b#d>c?dZJ(bRL#d-UcALxRLc)a

```

Try It Online!

How?

```
d:a^b#d>c?dZJ(bRL#d-UcALxRLc)a
  a                            : First arg(string)
    b                          : Second arg(substring)
        c                      : Third arg(n)
d:                             : Assign d to the result of
  a^b                          : Split a on separator b
         ?                     : If
     #d>c                      : Length of d is greater then c
                    Uc           : Increment c
             bRL                 : Repeat b
                #d-              : Length of d - c times
                      AL         : Append list
                        x        : Empty String
                         RL      : Repeat x
                           c     : c times
          dZJ                    : Zip with iterable d
                             a : Else return a

```
> 5 votes

# Answer
# Japt v2.0a0, 21 bytes

```
qW ÔË+WpE>VÃw
qWpUÊ§V

```

Try it

Input as `string, n, substring`

v2.0a0 is necessary because v1.4.6 errors if you try to use `p` this way.

Explanation:

```
qW ÔË+WpE>VÃw
qW            # Split <string> where <substring> appears
   Ô          # Reverse the array
    Ë      Ã  # For each item in the array:
     +        #  Append:
      Wp      #   <substring> repeated a number of times equal to:
        E>V   #    The current index is greater than <n>
              #    (Boolean gets converted to 1 or 0)
            w # Reverse the new array
              # Store as U

qWpUÊ§V
q             # Turn U into a string by inserting this between each item:
 Wp           #  <substring> repeated a number of times equal to:
   UÊ         #   Length of U (i.e. 1 + number of times <substring> appeared)
     §V       #   Is less than or equal to <n>
              # Output that string

```

I've tried an alternate using `ð` but the best I got was 25 bytes.
> 5 votes

# Answer
# Vyxal `s`, 11 bytes

```
O≤[Ẇy?NẎY|_

```

Try it Online!

12 bytes without the flag. Takes `substring, text, n`

## Explained

```
O≤[Ẇy?NẎY|_
O≤          # is the count of the substring in text less than n?
  [      |  # if so:
   Ẇy       #   Split text on substring, keeping the delimiter. Then uninterleave - this gives a list of splits and a list of delimiters
     ?NẎ    #   Take up to the -nth item of the list of delimiters
        Y   #   Reinterleave the delimiters, which will now be shorter than before. The s flag combines all the pieces into a single sting
         |_ # Otherwise, just return the original text

```
> 5 votes

# Answer
# Desmos, 169 bytes

```
S=s.length
L=l.length
I=[L-S...1]
A=I[[(l[i...i+S]-s)^2.totalfori=I]=0]
B=\{n>A.\length:[-L],A[1...n]\}
f(l,s,n)=l[[[0^{(b-B)^2}.maxforb=z-[0...S-1]].maxforz=[1...L]]=0]

```

Try It On Desmos!

Try It On Desmos! - Prettified

\\$f(l,s,n)\\$ takes in two lists of codepoints, with \\$l\\$ representing the string and \\$s\\$ representing the substring, and a positive integer \\$n\\$, representing the number of substrings to remove. The output is also a list of codepoints.

As you can tell by the byte size of the code, Desmos is not really well suited for problems related with string manipulation (When was using Desmos on a string problem ever a good idea?!?!). Also fun fact, this is my first time using a nested list comprehension in Desmos, which is pretty nice. There's probably a better way of doing that part, but nested list comprehensions look cool :P (to be completely honest, I can't think of any better way to do that lol).
> 5 votes

# Answer
# Red, 89 bytes

```
func[s t n][reverse t either parse r: reverse copy s[n to remove t to end][reverse r][s]]

```

Try it online!

Working on a reversed copy of the string, I use `parse` to remove `n` times the reversed substring. If `parse` succeeds, I return the modified string reversed, otherwise - the original string.
> 5 votes

# Answer
# PHP, 75 111 bytes

Okay so... lot of change

+12 bytes for a bug found by @Ismael Miguel where loop keep running if no instance of searched string given (`strrpos()===false`)

+26 bytes for using $argv instead or pre defined variable as indicated by @Sʨɠɠan

-2 bytes (Hey! an actual upgrade :D) from @Sʨɠɠan who remind me i can just get ride of `{}` for a single line instruction ^^'

```
for($s=$argv[1];$argv[3]--&&false!==$c=strrpos($s,$argv[2]);)$s=substr($s,0,$c).substr($s,$c+strlen($argv[2]));

```

Try it online!
> 4 votes

# Answer
# simply, 99 bytes

Creates an anonymous function that returns the expected result.

The argument order is `$full_string`, `$substring` and then `$number`.

```
fn($F$S$N)&iff(run&len(&str_split($F$S))>$N&str_rev(&str_replace(&str_rev($F)&str_rev($S)''$N))$F);

```

## How does it work?

First, splits the full string by the substring, and counts the number of elements.

When splitting the string:

* If the substring isn't present, returns 1 element.
* If it is present, returns 1 extra element.
Example: `&str_split("abcbdbebf", 'b') -> ["a", "c", "d", "e", "f"]`
For 4 `'b'`s, returns 5 elements.

If the number of elements is higher than `$number`, that means there's at least `$number` substrings in the full string.

The `&iff()` function is just the same as a ternary operator, in C-like languages.

To remove from the end of the string, I need to reverse the string, since there isn't a way to indicate to remove from the end of the string.
However, it takes an argument that indicates how many times to replace, which means, it will replace up to `$number` occurrences.

The result is returned automatically, since it is a function without a scope, just like an arrow function in JavaScript.

## Ungolfed

Code-y looking:

```
$fn = fn($full_string, $substring, $num) => &iff(
    (call &len(&str_split($full_string, $substring))) > $num,
    &str_rev(
        &str_replace(
            &str_rev($full_string),
            &str_rev($substring),
            '', $num
        )
    ),
    $full_string
);

```

Pseudo-code looking:

```
Set $fn to an anonymous function ($full_string, $substring, $num)
Begin.
    Set $count to the result of calling &len(Call &str_split($full_string, $substring)).

    Return the result of calling &iff(
        $count > $num,
        Call &str_rev(
            Call &str_replace(
                Call &str_rev($full_string),
                Call &str_rev($substring),
                '', $num
            )
        ),
        $full_string
    ).
End.

```
> 4 votes

# Answer
# Pyth, 21 bytes

```
s.iJcwz*]zt-lJ*KE>lJK

```

Try it online!

### Explanation

```
s                        concatenate the elements of
 .i                      interleave
   Jcwz                  the input string split on the substring (assigned to J) and
        ]z               a singleton list of the substring
       *                 duplicated
          t              one less than
           -lJ           the length of J minus
              *KE>lJK    0 if substring has less than n occurrences, n otherwise

```
> 4 votes

# Answer
# Retina 0.8.2, 87 bytes

```
.+$
$*
(?=.*¶(.+)¶)\1
¶
rT`¶``(?(1)$)(?<-1>¶.*)+(?=¶.+¶(1)+$)
+`¶(.*¶(.+)¶1+$)
$2$1
1G`

```

Try it online! Takes the string, substring and count on three separate lines. Explanation:

```
.+$
$*

```

Convert the count to unary.

```
(?=.*¶(.+)¶)\1
¶

```

Replace occurrences of the substring in the string with newlines.

```
rT`¶``(?(1)$)(?<-1>¶.*)+(?=¶.+¶(1)+$)

```

Remove the last `n` newlines from the string if there are in fact that many. (Today I discovered that an empty "to" string in transliteration is treated as `_`, i.e. delete matching characters.) The `r` causes the regular expression to be evaluated from right to left, so the lookahead gets processed first (setting `$#1`), then the newline-matching loop in the middle, then the count check at the beginning.

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

```

Replace (remaining) newlines with the substring.

```
1G`

```

Keep only the (final) string.
> 4 votes

# Answer
# Charcoal, 25 bytes

```
Ｎθ≔⪪ηζηＦ›Ｌηθ⊞η⪫⮌Ｅ⊕θ⊟ηω⪫ηζ

```

Try it online! Link is to verbose version of code. Takes inputs in the order count, string, substring. Explanation:

```
Ｎθ

```

Input the count as an integer.

```
≔⪪ηζη

```

Split the string on the substring.

```
Ｆ›Ｌηθ

```

If this results in more than enough pieces, then...

```
⊞η⪫⮌Ｅ⊕θ⊟ηω

```

... join the last `n+1` pieces together.

```
⪫ηζ

```

Join the (remaining) pieces with the substring.
> 4 votes

# Answer
# PHP 8.x, 65 bytes

This anonymous function does the replacement, up to `$n`, and checks how many replacements were made.
If there were fewer than `$n` replacements made, returns the original string.

```
fn($F,$S,$N)=>($r=preg_replace("@$S@",'',$F,$N,$x))&&$N>$x?$F:$r;

```

Due to the use of `preg_replace`, the substring must be a valid regular expression.
Regular words will always be valid regular expressions, and there's no need to worry about it.

## How does it work?

The function `preg_replace` takes the following arguments:

* `$pattern` \- Which will be the substring, `$S`
* `$replacement` \- Which is an empty string
* `$subject` \- The full string, `$F`
* `$limit` \- Maximum number of replacements, `$N`
* `&$count` \- Variable which will hold the number of replacements made

If `$N` is higher than `$count`, returns the full string, otherwise returns the result of the replacement.

# Example

```
$fn=fn($F,$S,$N)=>($r=preg_replace("@$S@",'',$F,$N,$x))&&$N>$x?$F:$r;

echo $fn('Cats do not memeowow, they do meow-ing.', 'meow', 2);
// Should display: Cats do not meow, they do -ing.

```

You can try this on https://onlinephp.io/c/d08f3
> 4 votes

# Answer
# Raku, 42 bytes

```
{$^a.flip.subst($^b.flip,'',:x($^c)).flip}

```

Try it online!
> 4 votes

# Answer
# Shell, ~~238~~ ~~236~~ ~~220~~ ~~200~~ ~~199~~ ~~194~~ ~~191~~ 186 bytes

(counting the last newline to make the script file containing those commands a real unix text file. Otherwise 185 bytes.)

Can probably be highly optimized, but I found it funny to attempt.

usage: cat Text-cases | this\_script , or this\_script \< Test-cases

```
sed -e'/^O/N;s,\n,,;s,",,g;s, = ,:,g'|awk -F: '/^St/{I=$2}
/^Su/{S=$2}
/^n/{n=$2
R=s=""
for(i=1;i<=n;i++){R=R sprintf("\\(.*\\)%s",S)
s=s"\\"i}
system("echo "I"|sed -e\"s,"R","s",\"")}'

```

Explanation:

```
the sed :
  1) put the line following "Output:" at the end of that line
  2) takes out the doublequotes
  3) replace " = " by ":"
Then the awk:
  retrieve (I)nput String,
           (S)ubstring,
       and (n),
  loops on n to construct:
         the (r)egex "\(.*\)S\(.*\)S\(.*\)S" (if n==3)
     and its (s)ubstitution "\1\2\3"
  and use sed to do this search/replace on the (I)nput string.

I used "\n" instead of ";" when I could (in the awk part) as it
is 1 caracter all the same, and is more legible.

```
> 2 votes

# Answer
# Perl 5, 74 bytes

```
sub{($_,$s,$n)=@_;$n*2>(@a=split/($s)/)?$_:join'',grep!/$s/||++$n*2<@a,@a}

```

Try it online!
> 1 votes

# Answer
# Ruby, 64 bytes

`->s,u,n,*a{x=s.split(u);l=x.size-n;x[0...l].join(u)+x[l..].join}`

Try it online!

Code is mine - I thought `split` and `join` would be more efficient, but I will credit Jordan above for the tests and framework.
> 1 votes

# Answer
# K (ngn/k), 46 bytes

```
{x(!#x)^,/(!#y)+/:(-z*(~z>#t))#t:&(#y)(y~)':x}

```

Try it online!
> 1 votes

# Answer
# Python 3, 78 bytes

```
i=input
a=i()
b=i()
c=int(i())
d=a.rsplit(b,c)
print([a,''.join(d)][len(d)>c])

```

Pretty direct approach using Python 3. Try it online!
> 0 votes

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


title: Fault-Tolerant Hello World

text:
# Question
Title: Fault-Tolerant Hello World
At the end of your interview, the Evil Interviewer tells you, "We make all of our applicants take a short coding test, to see if they really know what they are talking about. Don't worry; it's easy. And if you create a working program, I'll offer you the job immediately." He gestures for you to sit down at a nearby computer. "All you have to do is create a working Hello World program. But"--and he grins broadly--"there's a catch. Unfortunately the only compiler we have on this machine has a small bug. It randomly deletes one character from the source code file before compiling. Ok, see you in five minutes!" And he walks out of the room, whistling happily.

Can you guarantee that you will get the job?

## The Task

Write a program that will print `Hello, world!` to standard output even after a single character is removed from any position in the file. Or come as close to this as possible.

## The Rules

**No Extraneous Output** \- `Hello, world!` must be the only substantive thing printed to standard output. It is ok to include other characters if they are naturally produced by your language of choice--such as a trailing newline or even something like `[1] "Hello, world!"` (for example if you were using R), but *it must print the exact same thing every time.* It cannot print `Hello, world!Hello, world!` or `Hello world!" && x==1` some of the time, for example. Warnings, however, are allowed.

**Testing** In order to test determine your score, you have to test each possible permutation of the program: test it with each character removed, and see if it produces the correct output. I have included a simple Perl program for this purpose below, which should work for many languages. If it doesn't work for you, please create a test program and include it in your answer.

**Scoring** Your score is *the number of times your program fails*. In other words, the number of individual positions in your file where deleting a character prevents your program from working. Lowest score wins. In the event of a tie, the shortest code wins.

**Trivial Solutions** such as `"Hello, world!"` in several languages (score of 15) are acceptable, but they aren't going to win.

Happy programming, and may you get the job. But if you fail, you probably didn't want to work for that evil boss anyway.

*Perl test script:*

```
use warnings;
use strict;

my $program   = 'test.pl';
my $temp_file = 'corrupt.pl';
my $command = "perl -X $temp_file"; #Disabled warnings for cleaner output.
my $expected_result = "Hello, world!";

open my $in,'<',$program or die $!;
local $/;           #Undef the line separator
my $code = <$in>;   #Read the entire file in.

my $fails = 0;
for my $omit_pos (0..length($code)-1)
{
    my $corrupt = $code;
    $corrupt =~ s/^.{$omit_pos}\K.//s;  #Delete a single character

    open my $out,'>',$temp_file or die $!;
    print {$out} $corrupt;  #Write the corrupt program to a file
    close $out;

    my $result = `$command`;    #Execute system command.
    if ($result ne $expected_result)
    {
        $fails++;
        print "Failure $fails:\nResult: ($result)\n$corrupt";
    }
}

print "\n$fails failed out of " . length $code;

```

# Answer
## Befunge, Score 0, 96 bytes

I think I cracked it - no single character deletion will change the output.
Deleting any character from line 1 changes nothing - it still goes down at the same place.
Lines 2 and 3 are redundant. Normally line 2 is executed, but if you delete a character from it, the `<` is missed, and line 3 takes charge.
Deleting newlines doesn't break it either (it did break my previous version).
No test program, sorry.

**EDIT**: simplified a lot.

```
                              vv
@,,,,,,,,,,,,,"Hello, world!"<<
@,,,,,,,,,,,,,"Hello, world!"<<

```

A short explanation of the flow:

1. Befunge starts executing from top-left, moving right. Spaces do nothing.
2. `v` turns the execution flow downward, so it goes down one line.
3. `<` turns the execution flow left, so it reads line 2 in reversed order.
4. `"Hello, world!"` pushes the string to the stack. It's pushed in reversed order, because we're executing right to left.
5. `,` pops a character and prints it. The last character pushed is printed first, which reverses the string once more.
6. `@` terminates the program.
> 154 votes

# Answer
# HQ9+

This will never fail to produce the intended result when a character is deleted so gets a score of zero.

```
HH

```

When do I start?
> 46 votes

# Answer
# Perl, Score 0

*(147 characters)*

Here is my solution, which I managed to get from 4 down to 0:

```
eval +qq(;\$_="Hello, world!";;*a=print()if length==13or!m/./#)||
+eval +qq(;\$_="Hello, world!";;print()if*a!~/1/||!m/./#)##)||
print"Hello, world!"

```

It must appear all on one line to work; line breaks are for "readability" only.

It benefits from Perl's pathologically permissive syntax. Some highlights:

* Barewords that are not recognized are treated as strings. So when `eval` becomes `evl`, that is not an error if a string is permissible at that point.
* Unary `+` operator, which does nothing other than disambiguate syntax in certain situations. This is useful with the above, because `function +argument` (where + is unary) becomes `string + argument` (addition) when a function name is mangled and becomes a string.
* Many ways to declare strings: a double quoted string `qq( )` can become a single-quoted string `q()`; a string delimited by parentheses `qq(; ... )` can become a string delimited by a semicolon `qq; ... ;`. `#` inside strings can eliminate balancing issues by converting things to comments.

The length of this can probably be reduced somewhat, though I doubt ugoren's solution can be beaten.
> 45 votes

# Answer
## Befunge-98, score 0, 45 bytes

```
20020xx""!!ddllrrooww  ,,oolllleeHH""cckk,,@@

```

Try it online!

Although an optimal solution has already been found (and there's no tie breaker), I thought I'd show that this can be simplified considerably with Befunge 98.

### Explanation

The `20020xx` reliably sets the delta (the steps of the instruction pointer between ticks) to `(2,0)` so that starting at the first `x`, only every other command is executed. See this answer for a detailed explanation of why this works. Afterwards, the code is merely:

```
"!dlrow ,olleH"ck,@

```

We first push all the relevant character codes onto the stack with `"!dlrow ,olleH"`. Then `ck,` means print the top of the stack (`,`), 13 (`c` plus 1) times (`k`). `@` terminates the program.
> 16 votes

# Answer
## J, 7 points

Selecting every letter with odd position:

```
   _2{.\'HHeellllo,,  wwoorrlldd!!'
Hello, world!

```
> 11 votes

# Answer
# Unary, score 0, 74817134662624094502265949627214372599829 bytes

The code is not included due to post length limitations, but it consists of 74817134662624094502265949627214372599829 zeros.

If any of these zeros is removed, the resulting brainfuck program is KSab's hello world program.

Sadly, I didn't get the job because my machine had only 500 GB of hard disk space.
> 9 votes

# Answer
# Lost, Score 0, 122 bytes

```
>>>>>>>>>>>>>%%/>>>>>>>>>>/
\\
>>>>>>>>>>>>>//>>>>>>>>>>>\\
//
/@+-(  "vUvdlrow ,olleH"?<<
///
/@+-("vUvdlrow ,olleH"? <<<

```

Try it online!

It never stops amazing me that are possible in Lost.

If you haven't seen Lost before it is a 2-D programming language in which instead of starting execution at a fixed location it chooses a random location and direction and starts there. This makes writing any lost program a bit of a radiation hardening challenge normally, since a program must work from every start location. But now we layer on too and every program must work from every start location. With 122 bytes, four directions and a 28 by 6 bounding box, this means there are approximately 80,000 different programs that must be work.

This program is built with a mix of standard lost methods and standard radiation hardening methods. To start here is the normal Hello World for lost:

```
v<<<<<<<<<<>>>>>>>>>>>
>%?"Hello, worldvU"-+@

```

It is comprised of a "collector" which gathers all the stray instruction pointers and points them to the beginning of the actual program.

```
v<<<<<<<<<<>>>>>>>>>>>
>               v

```

A more detailed explanation of how this program works can be found here.

Now we want to modify this program to use the duplicate alignment method of radiation hardening. This method works by having two copies of the desired code and entering them from the end of the line.

```
>>>>>>>>>vv
 program <
 program <

```

This way when on of the programs is edited it becomes misaligned and the other one is executed

```
>>>>>>>>>vv
 progam <
 program <

```

To do this with our lost program is pretty simple:

```
>>>>>>>>>>>>>>>>>>>>>\\
@+-"Uvdlrow ,olleH"?%<
@+-"Uvdlrow ,olleH"?%<

```

However there are some problems with this. The alignment of the `"`s is an issue because it causes infinite loops (in the example above there are basically two strings `">"` lain out vertically, so if you start on the quotes going in the right direction you just push the `>` character endlessly). So you need to make sure the quotes don't line up even when a character has been deleted.

```
>>>>>>>>>>>>>>>>>>>>>>>\\
@+-  "Uvdlrow ,olleH"?%<
@+-"Uvdlrow ,olleH"?%  <

```

Also since `v` is needed to escape the inside of the string it's deletion is potentially a problem. So we need a backup.

```
>>>>>>>>>>>>>>>>>>>>>>>>>\\
@+-(  "vUvdlrow ,olleH"?%<
@+-("vUvdlrow ,olleH"?%  <

```

Now while alignment prevents most pointers from entering the wrong program, if we delete a non-critical character from a program, e.g.

```
>>>>>>>>>>>>>>>>>>>>>>>>>\\
@+-(  "vUvdlrow ,olle"?%<
@+-("vUvdlrow ,olleH"?%  <

```

Then if execution starts on the `%` it doesn't need to care about the alignment at all and it will just execute the bad program. So we need to move `%` *before* the alignment

```
>>>>>>>>>>>>>>>>>>>>>>%%\\
@+-(  "vUvdlrow ,olleH"?<
@+-("vUvdlrow ,olleH"?  <

```

Now another line of collector is needed to fill the gap we made by adding non-redirecting characters to our collector (`%`s).

```
>>>>>>>>>>>>>>%%/>>>>>>>/
>>>>>>>>>>>>>>//>>>>>>>>\\
@+-(  "vUvdlrow ,olleH"?<
@+-("vUvdlrow ,olleH"?  <

```

*(Some small changes are glossed over here mainly just edge casey nonsense)*

Now we have to worry about what happens when a newline is deleted. This would normally be ok because the alignment doubling strategy works for these, however for us it opens the door to a lot of potential infinite loops for example in the program:

```
>>>>>>>>>>>>>>%%/>>>>>>>/
>>>>>>>>>>>>>>//>>>>>>>>\\@+-(  "vUvdlrow ,olleH"?<
@+-("vUvdlrow ,olleH"?  <

```

we now have a bunch of columns with no redirecting characters on them, so pointers starting there can just loop up or down endlessly.

The trick we use here is to add (nearly) blank lines so that deleting a newline doesn't smash two big lines together.

```
>>>>>>>>>>>>>>%%/>>>>>>>/

>>>>>>>>>>>>>>//>>>>>>>>\\

@+-(  "vUvdlrow ,olleH"?<

@+-("vUvdlrow ,olleH"?  <

```

So if we delete a newline:

```
>>>>>>>>>>>>>>%%/>>>>>>>/

>>>>>>>>>>>>>>//>>>>>>>>\\
@+-(  "vUvdlrow ,olleH"?<

@+-("vUvdlrow ,olleH"?  <

```

Nothing fundamentally changed about our program. However these lines can't be completely blank as it leaves the door open for infinite loops. In fact they need to have at least two (because one could be deleted) redirecting characters.

```
>>>>>>>>>>>>>>%%/>>>>>>>/
//
>>>>>>>>>>>>>>//>>>>>>>>\\
//
@+-(  "vUvdlrow ,olleH"?<
//
@+-("vUvdlrow ,olleH"?  <

```

Now if we delete the last newline our quotes align again:

```
>>>>>>>>>>>>>>%%/>>>>>>>/
//
>>>>>>>>>>>>>>//>>>>>>>>\\
//
@+-(  "vUvdlrow ,olleH"?<
//@+-("vUvdlrow ,olleH"?  <

```

Which is no good so we use *3* characters on the 3rd filler line:

```
>>>>>>>>>>>>>>%%/>>>>>>>/
//
>>>>>>>>>>>>>>//>>>>>>>>\\
//
@+-(  "vUvdlrow ,olleH"?<
///
@+-("vUvdlrow ,olleH"?  <

```

From here we arrive at the final program with just some minor fiddling. Iteratively fixing and finding mistakes. I've covered everything I think is interesting, but if you are interested in exactly why this or that just leave a commend and I will add it to the explanation.
> 6 votes

# Answer
# Klein 0X1, score 0, 38 bytes

*Works in both 011 (real projective plane) and 001 (Klein bottle)*

```
//
@"!dlrow ,olleH"<
@"!dlrow ,olleH"<

```

Try it online!

This reflects the ip over the top of the program. The geometry causes the ip to reenter the program on the opposite end of the program. This makes it a lot shorter than the traditional method which requires a full length line to reach the right side of the program.

# 000, score 0, 38 bytes

```
<<@"!dlrow ,olleH"/
<@"!dlrow ,olleH"/

```

Try it online!

# 1X1 or 20X, score 0, 39 bytes

*Works in 101, 111, 200, and 201*

```
..

@"!dlrow ,olleH"<
@"!dlrow ,olleH"<

```

Try it online!

Due to the longstanding bug that spaces are trimmed off the front of Klein programs two `.`s are needed to make this work. If it were not for this bug the 37 byte program:

```

@"!dlrow ,olleH"<
@"!dlrow ,olleH"<

```

world work in all of these geometries.

The idea here is that we choose a geometry that naturally reaches the location we want and clear its way. Particularly we want geometries that connect the east edge to either the north or south edges with the proper twisting so that the ip leaving the east edge enters on the right side of the program. There are 4 of these.

# 0X0, score 0, 40 bytes

*Works in both 000 (torus) and 010 (Klein bottle)*

```
||@"!dlrow ,olleH"./
..@"!dlrow ,olleH"/

```

Try it online!

# 1X1, 20X, 210, or 101, score 0, 43 bytes

*Works in 101, 111, 200, 201, 210, and 101*

```
..

  @"!dlrow ,olleH"<
  @"!dlrow ,olleH"<

```

Try it online!

A modified version of the above where we move the `@`s out of the path so that 210 and 101 work. Once again `..` is required due to a bug and could be removed for a 2 byte save if the bug were fixed.

# XXX, score 0, 54 bytes

*Works in every geometry*

```
.               \\
@"!dlrow ,olleH"<
@"!dlrow ,olleH"<

```

Try it online!
> 6 votes

# Answer
# Python 3, score = ~~6~~ 4, ~~454~~ 426 bytes

```
xec=eec=exc=exe=exeexec=rint=pint=prnt=prit=prin=ppprint=hhh=hh=hhh=fr=""""pp(fr[1::2]) rrr________:__"ii______p____;nn____p______ptt__(________p(( __________(ff__________rfrr________[__r[[______1____[11____:______1::__:________:22 __________:66__________-2::________4__]22______]____)]]____)______ ))"""##"""
xec=eec=exc=exe=exec
pp=print
fr=fr=fr=""""HHeelllloo,,  wwoorrlldd!!"""##"""

exec(hhh[1::2++2++2++2++2++2++2++00])

```

Try it online!

The undeletable char are parenthesis for the exec function and the brackets.

## How it works:

* `hhh=hh=hhh=fr=...` initialize the main code and stor it in `hhh`
* `xec=...=ppprint=...` initialize all possibe deletion of `exec` and `print` to avoid a future `NameError`
* `xec=eec=exc=exe=exec` ensure that `exec` (with possible deletions) is well defined
* `fr=fr=fr=""""HHeelllloo,, wwoorrlldd!!"""##"""` store in `fr` the string `Hello, world!` but doubled to keep the information even with a deletion
* the last slice can be equal to either `[1::14]`, `[::14]`, `[1:14]` or `[1::12]`. Both of them slice the main code to have respectively `print(fr[1:26:2])`, `"r";pp(fr[1::2])` , `pp(fr[1::2])`  or `p :pp( fr[1:: 6-4])`

Thanks to @Jo King♦ for pointing me my errors, helping me to solve them and helped me to golf the result
> 6 votes

# Answer
# 8086 machine code (MS-DOS .COM), 71 bytes, score = 0

Slight variation on previous answers on the same theme.

In binary form:

```
00000000 : EB 28 28 E8 00 00 5A 83 C2 09 B4 09 CD 21 C3 48 : .((...Z......!.H
00000010 : 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 24 90 90 90 : ello, World!$...
00000020 : 90 90 90 90 90 90 90 90 90 90 EB D7 D7 E8 00 00 : ................
00000030 : 5A 83 C2 09 B4 09 CD 21 C3 48 65 6C 6C 6F 2C 20 : Z......!.Hello,
00000040 : 57 6F 72 6C 64 21 24                            : World!$

```

In readable form (NASM syntax):

```
cpu 8086
org 0x100

%macro CODEPART 0
    call near .nextline
.nextline:
    pop dx
    add dx, 0x09
    mov ah, 0x09
    int 0x21
    ret

.msg        db "Hello, World!$"
%endmacro

jump1:
    jmp jump2
    db 0x28

part1:
    CODEPART

filler:
    times 13    db 0x90

jump2:
    jmp part1
    db 0xd7

part2:
    CODEPART

```

# Rundown

The active part is duplicated so that there is always one untouched by radiation. We select the healthy version by way of jumps. Each jump is a short jump, and so is only two bytes long, where the second byte is the displacement (i.e. distance to jump, with sign determining direction).

We can divide the code into four parts which could be irradiated: jump 1, code 1, jump 2, and code 2. The idea is to make sure a clean code part is always used. If one of the code parts is irradiated, the other must be chosen, but if one of the jumps is irradiated, both code parts will be clean, so it will not matter which one is chosen.

The reason for having two jump parts is to detect irradiation in the first part by jumping over it. If the first code part is irradiated, it means we will arrive one byte off the mark. If we make sure that such a botched landing selects code 2, and a proper landing selects code 1, we're golden.

For both jumps, we duplicate the displacement byte, making each jump part 3 bytes long. This ensures that irradiation in one of the two last bytes will still make the jump valid. Irradiation in the first byte will stop the jump from happening at all, since the last two bytes will form a completely different instruction.

Take the first jump:

```
EB 28 28        jmp +0x28 / db 0x28

```

If either of the `0x28` bytes are removed, it will still jump to the same place. If the `0xEB` byte is removed, we will instead end up with

```
28 28           sub [bx + si], ch

```

which is a benign instruction on MS-DOS (other flavours might disagree), and then we fall through to code 1, which must be clean, since the damage was in jump 1.

If the jump is taken, we land at the second jump:

```
EB D7 D7        jmp -0x29 / db 0xd7

```

If this byte sequence is intact, and we land right on the mark, that means that code 1 was clean, and this instruction jumps back to that part. The duplicated displacement byte guarantees this, even if it is one of these displacement bytes that were damaged. If we either land one byte off (because of a damaged code 1 or jump 1) or the `0xEB` byte is the damaged one, the two remaining bytes will also here be benign:

```
D7 D7           xlatb / xlatb

```

Whichever the case, if we end up executing those two instructions, we know that either jump 1, code 1, or jump 2 were irradiated, which makes a fall-through to code 2 safe.

## Testing

The following program takes the COM filename as an argument, and creates all variants of it, along with a file called `tester.bat`. When run in DOS, this BAT file will run each of the created binaries, redirecting the outputs into one text file per program.

```
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    FILE *fin, *fout, *fbat;
    int fsize;
    char *data;

    if (!(fin = fopen(argv[1], "rb")))
    {
        fprintf(stderr, "Could not open input file \"%s\".\n", argv[1]);
        exit(1);
    }

    if (!(fbat = fopen("tester.bat", "w")))
    {
        fprintf(stderr, "Could not create BAT test file.\n");
        exit(2);
    }

    fseek(fin, 0L, SEEK_END);
    fsize = ftell(fin);
    fseek(fin, 0L, SEEK_SET);

    if (!(data = malloc(fsize)))
    {
        fprintf(stderr, "Could not allocate memory.\n");
        exit(3);
    }

    fread(data, 1, fsize, fin);

    fprintf(fbat, "@echo off\n");

    for (int i = 0; i < fsize; i++)
    {
        char fname[512];

        sprintf(fname, "%02d.com", i);
        fprintf(fbat, "%s > %02d.txt\n", fname, i);

        fout = fopen(fname, "wb");

        fwrite(data, 1, i, fout);
        fwrite(data + i + 1, 1, fsize - i - 1, fout);

        fclose(fout);
    }

    free(data);
    fclose(fin);
    fclose(fbat);
}

```

DOSBox, where I tested this, does not have the `fc` command, so another BAT file was created to run under Windows. It compares each text file with the first one to make sure they are all identical:

```
@echo off

for %%x in (*.txt) do (
    fc %%x 00.txt > nul
    if ERRORLEVEL 1 echo Failed: %%x
)

```

Ocular inspection of one of the text files is still needed.
> 5 votes

# Answer
# Befunge-93, Score 0 (63 bytes)

I know this isn't a code-golf challenge, but I thought it would be interesting to see if the existing Befunge-93 solution could be improved upon in terms of size. I had originally developed this technique for use in the similar Error 404 challenge, but the need for a wrapping payload in that case made the 3 line solution more optimal.

This isn't quite as good as Martin's Befunge-98 answer, but it's still a fairly significant reduction on the winning Befunge-93 solution.

```
<>>  "!dlrow ,olleH">:#,_@  vv
  ^^@_,#!>#:<"Hello, world!"<<>#

```

Try it online!

**Explanation**

There are two versions of the payload. For an unaltered program, the first `<` causes the program to execute right to left, wrapping around to the end of the line, until it reaches a `v` directing it down to the second line, and a `<` directing it left into the left-to-right version of the payload.

An error on the second line causes the final `<` to be shifted left and replaced with a `>` directing the flow right instead. The `#` (bridge) command has nothing to jump over, so the code just continues until it wraps around and reaches a `^` at the start of the line, directing it up to the first line, and then a `>` directing it right into the right-to-left payload.

Most errors on the first line just cause the final `v` commands to shift across by one, but that doesn't alter the main flow of the code. Deleting the first `<` is slightly different, though - in that case the execution path just flows directly into the left-to-right payload on the first line.

The other special case is the removal of the line break. When the code wraps around to the end of the line, in this case it's now the end of the what used to be the second line. When it encounters the `#` command from the right, this jumps over the `>` and thus continues directly into the right-to-left payload.

In case there's any doubt, I've also tested with the perl script and it confirmed that "0 failed out of 63".
> 3 votes

# Answer
# Gol\>\<\>, score 0, 38 bytes

```
<<H"Hello, world!"/
H"Hello, world!" <

```

The language is released after the challenge.
> 2 votes

# Answer
# !@#$%^&\*()\_+, score 2, 242 bytes

```
!!!!!!!!!!!!!! ^!!!!!!!!!!!!!ddddddddddddddllllllllllllllrrrrrrrrrrrrrrooooooooooooooWWWWWWWWWWWWWW              ,,,,,,,,,,,,,,oooooooooooooolllllllllllllllllllllllllllleeeeeeeeeeeeeeHHHHHHHHHHHHHH(((@%%%%%%%%%%%%%%))üü&& ^dlroW ,olleH((@)

```

Try it online!

Well, I give up.

I'm on a mobile phone, so I cannot put the null character there. If someone would be so kind to replace the !!\_+ in the TIO link, I would appreciate it. The two weaknesses are the  `^` between the exclamation marks.

This is not particularly clever, and most of the characters are just padding. Contains two Unicode characters; the challenge specifications said remove one character, not one byte.

The HW is repeated 14 times to be immune to `%` removal or removal in the HW string. !@#$%^&\*()\_+ allow unmatched `(` but not unmatched `)` when parsing, so the left parenthesis is repeated one more time than the right parenthesis.

What if the `@` was removed? We can know from the stack size if 13 characters went missing, so we use stack indexing to exit by error if the stack size is too short. Each character is doubled to make sure the test is performed. If the test passed, it means the `@` is the removed character, and none of the characters after the test was removed, so you can put a normal Hello, World program there.

I made this one bored afternoon at school with a pencil, but I did not have time to debug and post this until now. Bugs might still be present.
> 2 votes

# Answer
# \>\<\>, score 0, 40 bytes

```
||o<"Hello, world!"\
|o<"Hello, world!"\

```

Try it online!

This is a port of my klein 000 answer. It's a little more costly to output in \>\<\>, but overall this is nicely competitive. This halts by triggering an error, as suggested by JoKing. For my original version that exits properly:

# \>\<\>, score 0, 54 bytes

```
||>!;!?o!l<"Hello, world!"\
|>!;!?o!l<"Hello, world!"\

```

Try it online!
> 1 votes

# Answer
# Vyxal, 9 bytes, score 0

```
kH0kH ∴¡¡

```

Try it Online!

## Explanation :

```
# unaltered
kH        # push 'Hello, World!'  => [ Hello, World! ]
  0       # push 0                => [ Hello, World! , 0 ]
   kH     # push 'Hello, World!'  => [ Hello, World! , 0 , Hello, World! ]
      ∴   # max(a,b)              => [ Hello, World! , Hello, World! ]
       ¡¡ # sentence case (twice) => [ Hello, World! , Hello, world! ]
          # implicit output

# 1st char missing
H         # convert to hex        => [ 0 ]
 0        # Push 0                => [ 0 , 0 ]
  kH      # push 'Hello, World!'  => [ 0 , 0 , Hello, World! ]
     ∴¡¡  # max and sentence case => [ 0 , Hello, world! ]

# 2nd char missing
k0        # do nothing            => [ ]
  kH      # push 'Hello, World!'  => [ Hello, World! ]
     ∴¡¡  # max and sentence case => [ Hello, world! ]

# 3nd char missing
kH        # push 'Hello, World!'  => [ Hello, World! ]
  kH      # push 'Hello, World!'  => [ Hello, World! , Hello, World! ]
     ∴¡¡  # max and sentence case => [ Hello, world! ]

# 4th char missing
kH        # push 'Hello, World!'  => [ Hello, World! ]
  0       # push 0                => [ Hello, World! , 0 ]
   H      # convert to hex        => [ Hello, World! , 0 ]
     ∴¡¡  # max and sentence case => [ Hello, world! ]

# 5th char missing
kH        # push 'Hello, World!'  => [ Hello, World! ]
  0       # push 0                => [ Hello, World! , 0 ]
   k      # do nothing            => [ Hello, World! , 0 ]
     ∴¡¡  # max and sentence case => [ Hello, world! ]

# 6th same as unaltered

# 7th char missing
kH        # push 'Hello, World!'  => [ Hello, World! ]
  0       # push 0                => [ Hello, World! , 0 ]
   kH     # push 'Hello, World!'  => [ Hello, World! , 0 , Hello, World! ]
      ¡¡  # sentence case (twice) => [ Hello, World! , 0 , Hello, world! ]

# 8th or 9th char missing same as unaltered but sentence case only once

```

Fun fact, the char `0` can be replaced by any of `$123456789₀₄₆₇₈Ȯ` (and maybe some more) and the program is still a solution
> 1 votes

# Answer
# REPL\*, ~~204~~ ~~137~~ ~~130~~ 99 bytes, score 0

**(or any other R environment in which errors do not halt execution of subsequent commands: entering the program into the R interactive console works fine; alternatively (and as simulated in the TIO link) we can use the command-line option `-e 'options(error=function(){})'` (which would then define the language as "`R -e 'options(error=function(){})'`").*

```
a="Hello, world!"##"
b="Hello, world!"##"
T=cat(`if`(exists("a")&&(nchar(a)==13),a,b));
if(T)cat(a)

```

Try it online!

**Explanation:**

Lines 1 & 2: At least one of `a` or `b` should contain the text `"Hello, world!"` even if any character is deleted:

* any deletion inside one quoted string shouldn't affect the other;
* deletion of any of `a="` will simply error without assigning `a` (or the same for `b`);
* deletion of the second `"` will assign \`\`\`"Hello, world!##"\`\`\`\` to that string without affecting the other;
* deletion of any of `##"` has no effect;
* deletion of the first newline will convert the following line into a comment and prevent assignment of `b`, without affecting `a`;
* deletion of the second newline will convert the following line into a comment, without affecting either `a` or `b` (see line 3 below).

Line 3: Aims to output one of `a` or `b` that exists and is the correct, 13-character `"Hello, world!"` string, or to error.
If it succeeds without erroring, the variable `T` is re-assigned to `NULL` (instead of its default value of `TRUE`).

* deletion of any of `T=`, `cat()`,  ``if`(,,b)`, `exists("a")`, or `nchar(a)==` will error and fail to re-assign `T`.
* deletion of any of `13` will select `b` instead of `a` to output; however, since this was the single deletion made, `b` is intact so this is Ok.
* deletion of either `;` or the third newline has no effect;
* if the entire line is commented-out (by deletion of the second newline), it will not re-assign `T`.

Line 4: If `T` is not NULL, then either an error has occurred (so the deletion was on line 3), or the second newline was deleted (so line 3 was commented-out).
In either case `a` should be the correct `"Hello, world!"` string, and nothing has yet been output, so we can safely output `a`.
Any deletion to this line should cause an error so that it doesn't output anything to stdout.

* deletion of any of `if(T)` will error;
* if `T` is `NULL` (so no error has yet occurred, and line 3 ran Ok), `if(T)` will error and this line will not output anything.
* if `T` is still `TRUE`, then the single deletion already happened on another line, so we shouldn't need to worry about further deletions on this line.
> 0 votes

# Answer
# MSDOS .COM, 51 bytes

```
00000000: eb18 18e8 0e00 4865 6c6c 6f2c 2057 6f72  ......Hello, Wor
00000010: 6c64 2124 b409 5acd 21c3 ebe7 e7b4 09ba  ld!$..Z.!.......
00000020: 2401 cd21 c348 656c 6c6f 2c20 576f 726c  $..!.Hello, Worl
00000030: 6421 24                                  d!$

    org 100h
    jmp .L2       ; SBB [BX+SI],BL if 1B removed
    db  .L2-$
.L0:call .L1
    db  "Hello, World!$"
.L1:mov ah, 9
    pop dx
    int 0x21
    ret
    db 0x11A-$ dup ? ; Actually none
.L2:jmp .L0       ; OUT E7, AX if 1B removed
    db .L0-$
    mov ah, 9
    mov dx, .L3-1 ; If it goes this way
    int 0x21      ; then 1 byte missing
    ret
.L3:db  "Hello, World!$"

```

gastropner suggests me do this

Collection of all programs with at most 1 byte removed in base64, confirmed

```
/Td6WFoAAATm1rRGAgAhARYAAAB0L+Wj4NX/AgVdACCLvBunjDQGwDuQeO2LBXimvB64zX4rztWL/i5Av150lJoeOSHW05X92oDP65IyBlb67MdiB3tAoqaEfRm3gzRuAXuwZhHgJsxZs0QpbeW6y0O+IUD3a6M3dV4n+YbVbdSu8MWbR9qg76ck36pl5sy9kzvUv9hcAczs00fsjGJS10OdrU6sDxTIOpMk13Z+WxChUK04r19vxvShWbKDb2pZawGxFVJ2Sks0JvZNOJExJQx8l0fa6sSqQtOJR4oWVmOf/lePTc/ZDE3pz2nVPYgxQeLN31fGGeoso1JwWvr3sDyL6v49m2ZR9y0fVwc/nactXKMTJLzKmxSuwq6azF2f6ddf+0OL5fgVgccV5M1P9lQ6WV+sp80RWo1ceO8OJWmvIGM3ZTcl7ZcYqWUxQyvqAp0aL9ZDvXJhnybKXDSKOhzjtLcKM/07aCsVmBe5hZwllSnjiAOwKeH/8KyP/Uxfwl0xO5zyWshxWa0Znji7HAQH9ais1UHVHAP9P9EQF+g0rU5WehexGtrRg74lGF9/hUSepXTZZAZLpMURXJC9zlhkAj7xKsL3Lmm/yNZyETgDiZMB2kD/k3js5jDnmAZjU15KkYHpuNVsjsFcP6ERVipU4b3WRGCjsMgzbTcN1naVFUNOWXLGcvdY2Y5o2Wf2+TMTD275J51Db4aNUX8rIRd3NUwAAAAASNVP9/NyC/kAAaEEgKwDAKrxg/KxxGf7AgAAAAAEWVo=

```
> 0 votes

---
Tags: code-challenge, source-layout, hello-world, radiation-hardening
---