# Question
Title: Tips for golfing in x86/x64 machine code
I noticed that there's no such question, so here it is:

Do you have general tips for golfing in x86/x64 machine code? If the tip only applies to a certain environment or calling convention, please specify that in your answer.

> Please only one tip per answer (see here).

# Answer
> 21 votes
# Choose your calling convention to put args where you want them.

**The language of your answer is asm (actually machine code), so treat it as part of a program written in asm, not C-compiled-for-x86.** Your function doesn't have to be easily callable from C with any standard calling convention. That's a nice bonus if it doesn't cost you any extra bytes, though.

In a pure asm program, it's normal for some helper functions to use a calling convention that's convenient for them and for their caller. Such functions document their calling convention (inputs/outputs/clobbers) with comments.

In real life, even asm programs do (I think) tend to use consistent calling conventions for most functions (especially across different source files), but any given important function could do something special. In code-golf, you're optimizing the crap out of one single function, so obviously it's important/special.

---

**To test your function from a C program, you can write a wrapper** that puts args in the right places, saves/restores any extra registers you clobber, and puts the return value into `e/rax` if it wasn't there already.

---

### The limits of what's reasonable: anything that doesn't impose an unreasonable burden on the caller:

* `esp`/`rsp` must be call-preserved1; other integer regs are fair game for being call-clobbered. (`rbp` and `rbx` are usually call-preserved in normal conventions, but you *could* clobber both.)
* Any arg in any register (except `rsp`) is reasonable, but asking the caller to copy the same arg to multiple registers is not.
* Requiring `DF` (string direction flag for `lods`/`stos`/etc.) to be clear (upward) on call/ret is normal. Letting it be undefined on call/ret would be ok. Requiring it to be cleared or set on entry but then leaving it modified when you return would be weird.
* Returning FP values in x87 `st0` is reasonable, but returning in `st3` with garbage in other x87 registers isn't. The caller would have to clean up the x87 stack. Even returning in `st0` with non-empty higher stack registers would also be questionable (unless you're returning multiple values).
* Your function will be called with `call`, so `[rsp]` is your return address. You *can* avoid `call`/`ret` on x86 using a link register like `lea rbx, [ret_addr]`/`jmp function` and return with `jmp rbx`, but that's not "reasonable". That's not as efficient as `call`/`ret`, so it's not something you'd plausibly find in real code.
* Clobbering unlimited memory above `rsp` is not reasonable, but clobbering your function args on the stack is allowed in normal calling conventions. x64 Windows requires 32 bytes of shadow space above the return address, while x86-64 System V gives you a 128 byte red-zone below `rsp`, so either of those are reasonable. (Or even a much larger red-zone, especially in a stand-alone program rather than function.)

Note 1: or have some well-defined sensible rule for how RSP is modified: e.g. callee-pops stack args like with `ret 8`. (Although stack args and a larger `ret imm16` encoding are usually not what you want for code-golf). Or even returning an array by value on the stack is an unconventional but usable calling-convention. e.g. pop the return address into a register, then push in a loop, then `jmp reg` to return. Probably only justifiable with a size in a register, else the caller would have to save the original RSP somewhere. RBP or some other reg would have to be call-preserved so a caller could use it as a frame pointer to easily clean up the result. Also probably not smaller than using `stos` to write an output pointer passed in RDI.

Borderline cases: write a function that produces a sequence in an array, given the first 2 elements *as function args*. I chose to have the caller store the start of the sequence into the array and just pass a pointer to the array. This is definitely bending the question's requirements. I considered taking the args packed into `xmm0` for `movlps [rdi], xmm0`, which would also be a weird calling convention and ever harder to justify / more of a stretch.

---

### Return a boolean in FLAGS (condition codes)

OS X system calls do this (`CF=0` means no error): Is it considered bad practice to use the flags register as a boolean return value?.

Any condition that can be checked with one `jcc` is perfectly reasonable, especially if you can pick one that has any semantic relevance to the problem. (e.g. a compare function might set flags so `jne` will be taken if they weren't equal).

---

### Require narrow args (like a `char`) to be sign or zero extended to 32 or 64 bits.

This is not unreasonable; using `movzx` or `movsx` to avoid partial-register slowdowns is normal in modern x86 asm. In fact clang/LLVM already makes code that depends on an undocumented extension to the x86-64 System V calling convention: args narrower than 32 bits are sign or zero extended to 32 bits by the caller.

You can document/describe extension to 64 bits by writing `uint64_t` or `int64_t` in your prototype if you want, e.g. so you can use a `loop` instruction, which uses the whole 64 bits of `rcx` unless you use an address-size prefix to override the size down to 32 bit `ecx` (yes really, address-size not operand-size).

Note that `long` is only a 32-bit type in the Windows 64-bit ABI, and the Linux x32 ABI; `uint64_t` is unambiguous and shorter to type than `unsigned long long`.

---

### Existing calling conventions:

* Windows 32-bit `__fastcall`, already suggested by another answer: integer args in `ecx` and `edx`.
* **x86-64 System V**: passes lots of args in registers, and has lots of call-clobbered registers you can use without REX prefixes. More importantly, it was actually chosen to allow compilers to inline (or implement in libc) `memcpy` or `memset` as `rep movsb` easily: the first 6 integer/pointer args are passed in `rdi`, `rsi`, `rdx`, `rcx`, `r8`, and `r9`.

If your function uses `lodsd`/`stosd` inside a loop that runs `rcx` times (with the `loop` instruction), you can say "callable from C as `int foo(int *rdi, const int *rsi, int dummy, uint64_t len)` with the x86-64 System V calling convention". example: chromakey.
* 32-bit GCC `regparm`: **Integer args in `eax`**, `ecx`, and `edx`, return in EAX (or EDX:EAX). Having the first arg in the same register as the return value allows some optimizations, like this case with an example caller and a prototype with a function attribute. And of course AL/EAX is special for some instructions.
* The Linux x32 ABI uses 32-bit pointers in long mode, so you can save a REX prefix when modifying a pointer (example use-case). You can still use 64-bit address-size, unless you have a 32-bit negative integer zero-extended in a register (so it would be a large unsigned value if you did `[rdi + rdx]`, going outside the low 32 bits of address space.).

Note that `push rsp`/`pop rax` is 2 bytes, and equivalent to `mov rax, rsp`, so you can still *copy* full 64-bit registers in 2 bytes.

# Answer
> 18 votes
## `mov`-immediate is expensive for constants

This might be obvious, but I'll still put it here. In general it pays off to think about the bit-level representation of a number when you need to initialize a value.

### Initializing `eax` with `0`:

```
b8 00 00 00 00          mov    $0x0,%eax

```

should be shortened (for performance as well as code-size) to

```
31 c0                   xor    %eax,%eax

```

### Initializing `eax` with `-1`:

```
b8 ff ff ff ff          mov    $-1,%eax

```

can be shortened to

```
31 c0                   xor    %eax,%eax
48                      dec    %eax

```

or

```
83 c8 ff                or     $-1,%eax

```

---

Or more generally, **any 8-bit sign-extended value can be created in 3 bytes with `push -12` (2 bytes) / `pop %eax` (1 byte).** This even works for 64-bit registers with no extra REX prefix; `push`/`pop` default operand-size = 64.

```
6a f3                   pushq  $0xfffffffffffffff3
5d                      pop    %rbp

```

Or given a known constant in a register, you can create another nearby constant using `lea 123(%eax), %ecx` (3 bytes). This is handy if you need a zeroed register *and* a constant; xor-zero (2 bytes) + `lea-disp8` (3 bytes).

```
31 c0                   xor    %eax,%eax
8d 48 0c                lea    0xc(%eax),%ecx

```

See also Set all bits in CPU register to 1 efficiently

# Answer
> 13 votes
In a lot of cases, accumulator-based instructions (i.e. those that take `(R|E)AX` as the destination operand) are 1 byte shorter than general-case instructions; see this question on StackOverflow.

# Answer
> 13 votes
**Use special-case short-form encodings for AL/AX/EAX, and other short forms and single-byte instructions**

Examples assume 32 / 64-bit mode, where the default operand size is 32 bits. An operand-size prefix changes the instruction to AX instead of EAX (or the reverse in 16-bit mode).

* **`inc/dec` a register** (other than 8-bit): `inc eax` / `dec ebp`. (Not x86-64: the `0x4x` opcode bytes were repurposed as REX prefixes, so `inc r/m32` is the only encoding.)

8-bit `inc bl` is 2 bytes, using the `inc r/m8` opcode + ModR/M operand encoding. So **use `inc ebx` to increment `bl`, if it's safe.** (e.g. if you don't need the ZF result in cases where the upper bytes might be non-zero).

* `scasd`: `e/rdi+=4`, requires that the register points to readable memory. Sometimes useful even if you don't care about the FLAGS result (like `cmp eax,[rdi]` / `rdi+=4`). And **in 64-bit mode, `scasb` can work as a 1-byte `inc rdi`**, if lodsb or stosb aren't useful.
* **`xchg eax, r32`**: this is where 0x90 NOP came from: `xchg eax,eax`. Example: re-arrange 3 registers with two `xchg` instructions in a `cdq` / `idiv` loop for GCD in 8 bytes where most of the instructions are single-byte, including an abuse of `inc ecx`/`loop` instead of `test ecx,ecx`/`jnz`
* `cdq`: sign-extend EAX into EDX:EAX, i.e. copying the high bit of EAX to all bits of EDX. To create a zero with known non-negative, or to get a 0/-1 to add/sub or mask with. x86 history lesson: `cltq` vs. `movslq`, and also AT&T vs. Intel mnemonics for this and the related `cdqe`.
* lodsb/d: like `mov eax, [rsi]` / `rsi += 4` without clobbering flags. (Assuming DF is clear, which standard calling conventions require on function entry.) Also stosb/d, sometimes scas, and more rarely movs / cmps.
* `push`/`pop reg`. e.g. in 64-bit mode, `push rsp` / `pop rdi` is 2 bytes, but `mov rdi, rsp` needs a REX prefix and is 3 bytes.

`xlatb` exists, but is rarely useful. A large lookup table is something to avoid. I've also never found a use for AAA / DAA or other packed-BCD or 2-ASCII-digit instructions, except for a hacky use of DAS as part of converting a 4-bit integer to an ASCII hex digit, thanks to Peter Ferrie.

1-byte `lahf` / `sahf` are rarely useful. You *could* `lahf` / `and ah, 1` as an alternative to `setc ah`, but it's typically not useful.

And for CF specifically, there's `sbb eax,eax` to get a 0/-1, or even **un-documented but universally supported 1-byte `salc` (set AL from Carry)** which effectively does `sbb al,al` without affecting flags. (Removed in x86-64). I used SALC in User Appreciation Challenge #1: Dennis ♦.

1-byte `cmc` / `clc` / `stc` (flip ("complement"), clear, or set CF) are rarely useful, although I did find **a use for `cmc`** in extended-precision addition with base 10^9 chunks. To unconditionally set/clear CF, usually arrange for that to happen as part of another instruction, e.g. `xor eax,eax` clears CF as well as EAX. There are no equivalent instructions for other condition flags, just DF (string direction) and IF (interrupts). The carry flag is special for a lot of instructions; shifts set it, `adc al, 0` can add it to AL in 2 byte, and I mentioned earlier the undocumented SALC.

**`std` / `cld` rarely seem worth it**. Especially in 32-bit code, it's better to just use `dec` on a pointer and a `mov` or memory source operand to an ALU instruction instead of setting DF so `lodsb` / `stosb` go downward instead of up. Usually if you need downward at all, you still have another pointer going up, so you'd need more than one `std` and `cld` in the whole function to use `lods` / `stos` for both. Instead, just use the string instructions for the upward direction. (The standard calling conventions guarantee DF=0 on function entry, so you can assume that for free without using `cld`.)

---

### 8086 history: why these encodings exist

In original 8086, AX was very special: instructions like `lodsb` / `stosb`, `cbw`, `mul` / `div` and others use it implicitly. That's still the case of course; current x86 hasn't dropped any of 8086's opcodes (at least not any of the officially documented ones, except in 64-bit mode). But later CPUs added new instructions that gave better / more efficient ways to do things without copying or swapping them to AX first. (Or to EAX in 32-bit mode.)

e.g. 8086 lacked later additions like `movsx` / `movzx` to load or move + sign-extend, or 2 and 3-operand `imul cx, bx, 1234` that don't produce a high-half result and don't have any implicit operands.

Also, **8086's main bottleneck was instruction-fetch, so optimizing for code-size was important for performance back then**. 8086's ISA designer (Stephen Morse) spent a lot of opcode coding space on special cases for AX / AL, including special (E)AX/AL-destination opcodes for all the basic immediate-src ALU- instructions, just opcode + immediate with no ModR/M byte. 2-byte `add/sub/and/or/xor/cmp/test/... AL,imm8` or `AX,imm16` or (in 32-bit mode) `EAX,imm32`.

But there's no special case for `EAX,imm8`, so the regular ModR/M encoding of `add eax,4` is shorter.

The assumption is that if you're going to work on some data, you'll want it in AX / AL, so swapping a register with AX was something you might want to do, maybe even more often than *copying* a register to AX with `mov`.

Everything about 8086 instruction encoding supports this paradigm, from instructions like `lodsb/w` to all the special-case encodings for immediates with EAX to its implicit use even for multiply/divide.

---

Don't get carried away; it's not automatically a win to swap everything to EAX, especially if you need to use immediates with 32-bit registers instead of 8-bit. Or if you need to interleave operations on multiple variables in registers at once. Or if you're using instructions with 2 registers, not immediates at all.

But always keep in mind: am I doing anything that would be shorter in EAX/AL? Can I rearrange so I have this in AL, or am I currently taking better advantage of AL with what I'm already using it for.

Mix 8-bit and 32-bit operations freely to take advantage whenever it's safe to do so (you don't need carry-out into the full register or whatever).

# Answer
> 10 votes
### Create 3 zeroes with `mul` (then `inc`/`dec` to get +1 / -1 as well as zero)

You can zero eax and edx by multiplying by zero in a third register.

```
xor   ebx, ebx      ; 2B  ebx = 0
mul   ebx           ; 2B  eax=edx = 0

inc   ebx           ; 1B  ebx=1

```

will result in EAX, EDX, and EBX all being zero in just four bytes. You can zero EAX and EDX in three bytes:

```
xor eax, eax
cdq

```

But from that starting point you can't get a 3rd zeroed register in one more byte, or a +1 or -1 register in another 2 bytes. Instead, use the mul technique.

Example use-case: concatenating the Fibonacci numbers in binary.

Note that after a `LOOP` loop finishes, ECX will be zero and can be used to zero EDX and EAX; you don't always have to create the first zero with `xor`.

# Answer
> 9 votes
# Subtract -128 instead of add 128

```
0100 81C38000      ADD     BX,0080
0104 83EB80        SUB     BX,-80

```

Samely, add -128 instead of subtract 128

# Answer
> 7 votes
# CPU registers and flags are in known startup states

For a full/standalone program, we can assume that the CPU is in a known and documented default state based on platform and OS.

For example:

DOS http://www.fysnet.net/yourhelp.htm

Linux x86 ELF http://asm.sourceforge.net/articles/startup.html \- in `_start` in a static executable, most registers are zero other than the stack pointer, to avoid leaking info into a fresh process. `pop` will load `argc` which is a small non-negative integer, `1` if run normally from a shell with no args.

Same applies for x86-64 processes on Linux.

# Answer
> 7 votes
# Skipping instructions

Skipping instructions are opcode fragments that combine with one or more subsequent opcodes. The subsequent opcodes can be used with a different entrypoint than the prepended skipping instruction. Using a skipping instruction instead of an unconditional short jump can save code space, be faster, and set up incidental state such as `NC` (No Carry).

My examples are all for 16-bit Real/Virtual 86 Mode, but a lot of these techniques can be used similarly in 16-bit Protected Mode, or 32- or 64-bit modes.

Quoting from my ACEGALS guide:

> ## 11: Skipping instructions
>
> The constants \__TEST\_IMM8, \__TEST\_IMM16, and \__TEST\_OFS16\_IMM8 are defined to the respective byte strings for these instructions. They can be used to skip subsequent instructions that fit into the following 1, 2, or 3 bytes. However, note that they modify the flags register, including always setting NC. The 16-bit offset plus 16-bit immediate test instruction is not included for these purposes because it might access a word at offset 0FFFFh in a segment. Also, the \__TEST\_OFS16\_IMM8 as provided should only be used in 86M, to avoid accessing data beyond a segment limit. After the db instruction using one of these constants, a parenthetical remark should list which instructions are skipped.

The 86 Mode defines in lmacros1.mac 323cc150061e (2021-08-29 21:45:54 +0200):

```
%define __TEST_IMM8 0A8h                        ; changes flags, NC
%define __TEST_IMM16 0A9h                       ; changes flags, NC
                                        ; Longer NOPs require two bytes, like a short jump does.
                                        ; However they execute faster than unconditional jumps.
                                        ; This one reads random data in the stack segment.
                                        ;  (Search for better ones.)
%define __TEST_OFS16_IMM8 0F6h,86h              ; changes flags, NC

```

The `0F6h,86h` opcode in 16-bit modes is a `test byte [bp + disp16], imm8` instruction. I believe I am not using this one anywhere actually. (A stack memory access might actually be slower than an unconditional short jump, in fact.)

`0A8h` is the opcode for `test al, imm8` in any mode. The `0A9h` opcode changes to an instruction of the form `test eax, imm32` in 32- and 64-bit modes.

Two use cases in ldosboot boot32.asm 07f4ba0ef8cd (2021-09-10 22:45:32 +0200):

First, chain two different entrypoints for a common function which both need to initialise a byte-sized register. The `mov al, X` instructions take 2 bytes each, so `__TEST_IMM16` can be used to skip one such instruction. (This pattern can be repeated if there are more than two entrypoints.)

```
error_fsiboot:
        mov al,'I'

        db __TEST_IMM16 ; (skip mov)
read_sector.err:
        mov al, 'R'     ; Disk 'R'ead error

error:

```

Second, a certain entrypoint that needs two bytes worth of additional teardown but can otherwise be shared with the fallthrough case of a later code part.

```
                mov bx, [VAR(para_per_sector)]
                sub word [VAR(paras_left)], bx
                jbe @F          ; read enough -->

                loop @BB
                pop bx
                pop cx

                call clust_next
                jnc next_load_cluster
                inc ax
                inc ax
                test al, 8      ; set in 0FFF_FFF8h--0FFF_FFFFh,
                                ;  clear in 0, 1, and 0FFF_FFF7h
                jz fsiboot_error_badchain
                db __TEST_IMM16
@@:
                pop bx
                pop cx
                call check_enough
                jmp near word [VAR(fsiboot_table.success)]

```

Here's a use case in inicomp lz4.asm 4d568330924c (2021-09-03 16:59:42 +0200) where we depend on the `test al, X` instruction clearing the Carry Flag:

```
.success:
        db __TEST_IMM8                  ; (NC)
.error:
        stc
        retn

```

Finally, here's a very similar use of a skipping instruction in DOSLFN Version 0.41c (11/2012). Instead of `test ax, imm16` they're using `mov cx, imm16` which has no effect on the status flags but clobbers the `cx` register instead. (Opcode `0B9h` is `mov ecx, imm32` in non-16-bit modes, and writes to the full `ecx` or `rcx` register.)

```
;THROW-Geschichten... [english: THROW stories...]
SetErr18:
        mov     al,18
        db      0B9h            ;mov cx,nnnn
SetErr5:
        mov     al,5
        db      0B9h            ;mov cx,nnnn
SetErr3:
        mov     al,3
        db      0B9h            ;mov cx,nnnn
SetErr2:
        mov     al,2
SetError:

```

# Answer
> 6 votes
# `mov` small immediates into lower registers when applicable

If you already know the upper bits of a register are 0, you can use a shorter instruction to move an immediate into the lower registers.

```
b8 0a 00 00 00          mov    $0xa,%eax

```

versus

```
b0 0a                   mov    $0xa,%al

```

# Use `push`/`pop` for imm8 to zero upper bits

Credit to Peter Cordes. `xor`/`mov` is 4 bytes, but `push`/`pop` is only 3!

```
6a 0a                   push   $0xa
58                      pop    %eax

```

# Answer
> 6 votes
# Use do-while loops instead of while loops

This is not x86 specific but is a widely applicable beginner assembly tip. If you know a while loop will run at least once, rewriting the loop as a do-while loop, with loop condition checking at the end, often saves a 2 byte jump instruction. In a special case you might even be able to use `loop`.

# Answer
> 5 votes
# Use `fastcall` conventions

x86 platform has many calling conventions. You should use those that pass parameters in registers. On x86\_64, the first few parameters are passed in registers anyway, so no problem there. On 32-bit platforms, the default calling convention (`cdecl`) passes parameters in stack, which is no good for golfing - accessing parameters on stack requires long instructions.

When using `fastcall` on 32-bit platforms, 2 first parameters are usually passed in `ecx` and `edx`. If your function has 3 parameters, you might consider implementing it on a 64-bit platform.

C function prototypes for `fastcall` convention (taken from this example answer):

```
extern int __fastcall SwapParity(int value);                 // MSVC
extern int __attribute__((fastcall)) SwapParity(int value);  // GNU

```

---

Note: you can also use other calling conventions, including custom ones. I never use custom calling conventions; for any ideas related to these, see here.

# Answer
> 5 votes
# The FLAGS are set after many instructions

After many arithmetic instructions, the Carry Flag (unsigned) and Overflow Flag (signed) are set automatically (more info). The Sign Flag and Zero Flag are set after many arithmetic and logical operations. This can be used for conditional branching.

Example:

```
d1 f8                   sar    %eax

```

ZF is set by this instruction, so we can use it for condtional branching.

# Answer
> 5 votes
# `lea` for math

This is probably one of the first things one learns about x86, but I leave it here as a reminder. `lea` can be used to do multiplication by 2, 3, 4, 5, 8, or 9, and adding an offset.

For example, to calculate `ebx = 9*eax + 3` in one instruction (in 32-bit mode):

```
8d 5c c0 03             lea    0x3(%eax,%eax,8),%ebx

```

Here it is without an offset:

```
8d 1c c0                lea    (%eax,%eax,8),%ebx

```

Wow! Of course, `lea` can be used to also do math like `ebx = edx + 8*eax + 3` for calculating array indexing.

# Answer
> 5 votes
# Combinations with CDQ for certain piecewise-linear functions

`CDQ` sign-extends EAX into EDX, making EDX 0 if EAX is nonnegative and -1 (all 1s) if EAX is negative. This can be combined with several other instructions to apply certain piecewise-linear functions to a value in EAX in 3 bytes:

`CDQ` \+ `AND`\\$ \min(x, 0) \\$ (in either EAX or EDX). (I have used this here.)

`CDQ` \+ `OR`\\$ \max(x, -1) \\$.

`CDQ` \+ `XOR`\\$ \max(x, -x-1) \\$.

`CDQ` \+ `MUL EDX`\\$ \max(-x, 0) \\$ in EAX and \\$ \left\\{ \begin{array}{ll} 0 & : x \ge 0 \\ x - 1 & : x \< 0 \end{array} \right.\\$ in EDX.

# Answer
> 4 votes
The loop and string instructions are smaller than alternative instruction sequences. Most useful is `loop <label>` which is smaller than the two instruction sequence `dec ECX` and `jnz <label>`, and `lodsb` is smaller than `mov al,[esi]` and `inc si`.

# Answer
> 4 votes
# Entry point doesn't necessarily have to be first byte of submission

I came across this answer, and didn't understand it at first until I realized that the intention is:

```
; ---- example calling code starts here -------------

                MOV     ECX, 1
                CALL    entry
                RET

; ---- code golf answer code starts here (5 bytes) --

       41       INC     ECX
entry: E3 FD    JECXZ   SHORT $-1
       91       XCHG    EAX,ECX
       C3       RETN

; ---- code golf answer code ends here -------------

```

Does not seem to conflict with any of the conditions of "Choose your calling convention" and is otherwise valid assembly language.

# Answer
> 4 votes
# Use a good assembler

There are dozens of x86 assemblers out there, and they are **not** created equal.

Not only can a bad assembler be painful to use, but **they might not always output the most optimal code.**

Most x86 instructions have multiple valid encodings, some shorter than others.

For example, I saw one user with a 16-bit assembler that emitted different code depending on the order of `xchg`'s operands. It is a commutative operation, it shouldn't make a difference.

```
87 D8   xchg    ax, bx
93      xchg    bx, ax

```

Life is too short for bad assemblers, and it should **not** be the thing getting in the way of golfing.

The three assemblers I would suggest are:

* nasm is the first one I would recommend to everyone (and I wish I had learned it first).
    + It fully supports 16-bit, 32-bit, *and* 64-bit code
    + It can easily assemble all sorts of object formats, as well as raw binaries/`.com` files (a multi-step ritual with GAS).
    + **It is officially supported on DOS** as well as all modern OSes.
    + While it doesn't support C macros, it has a god-tier preprocessor that is much better than C.
    + The way it handles local labels is really nice.
    + Good error messages, mostly fairly beginner-friendly pointing you in the direction of why an instruction isn't allowed or what it doesn't like about a source line.
* GAS (GCC's assembler) is another fairly good assembler.
    + It is the assembler used by GCC and Clang. You might recognize it if you use Godbolt or `gcc -S`.
    + It supports AT&T syntax which some might prefer
    + With `.intel_syntax noprefix`, you can switch to Intel syntax
    + While its built-in preprocessor is pretty limited, it can be easily combined with a C preprocessor.
    + For x87, beware of the AT&T syntax design bug that interchanges `fsubr` with `fsub` in some cases, same for `fdiv[r]`. Older GAS versions applied the same swap in Intel-syntax mode, and so did older binutils `objdump -d` versions. (This is AT&T's fault, not GNU's, and current GAS versions do as well as possible, but is an inherent downside in using AT&T syntax for x87.)
    + Error messages are less helpful than NASM about why an instruction is invalid
    + Ambiguous instructions other than `mov` default to dword operand-size instead of being an error in AT&T syntax, such as `add $123, (%rdi)` assembling as `addl`. Clang, and GAS in Intel syntax mode, error on this.
* Clang is, in most cases, completely exchangeable for GAS.
    + It has much more helpful error messages and doesn't silently treat x86\_64 registers as symbols in 32-bit mode.
    + While AT&T syntax is fully supported, Intel syntax currently has a few bugs.
        - It is the **only** reason I am recommending GAS over Clang.
        - It still works as a solid linter.
    + It also supports C macros.

I haven't used enough of the other assemblers to give a good opinion, as I am more than satisfied with those three.

FASM is also well-regarded, using very nearly the same syntax as NASM, and is supported on https://TIO.run/ ; It's able to make 32-bit executables on TIO, unlike with other assemblers, using the directive `format ELF executable 3` to emit a 32-bit ELF executable, not a `.o` object file that would need linking.

EuroAssembler is also open-source; its maintainer is active on Stack Overflow in the \[assembly\] and \[x86\] tags.

# Answer
> 3 votes
To add or subtract 1, use the one byte `inc` or `dec` instructions which are smaller than the multibyte add and sub instructions.

# Answer
> 3 votes
# Try `XLAT` for byte memory access

`XLAT` is a **one byte** instruction that is equivalent to `AL = [BX+AL]`. Yes, that's right, it lets you use `AL` as an index register for memory access.

# Answer
> 3 votes
# Take advantage of the x86\_64 code model

Linux's default code model will put all of your code and globals in the low 31 bits of memory, so 32-bit pointer arithmetic here is perfectly safe. The stack, libraries, and any dynamically allocated pointers are not, though. Try it online!

Make sure to still use the entire 64 bits in memory operands (**including lea**), because using `[eax]` requires a `67` prefix byte.

# Answer
> 3 votes
# Use interrupts and syscalls wisely

In general, unlike the C calling conventions, most syscalls and interrupts will preserve your registers and flags unless noted otherwise, except for a return value usually in AL/EAX/RAX depending on the OS. (e.g. the x86-64 `syscall` instruction itself destroys RCX and R11)

#### Linux specific:

* If exiting with a crash is okay, `int3`, `int1`, or `into` can usually do the job in one byte. Don't try this on DOS though, it will lock up.
    + Note that the error messages like `Segmentation fault (core dumped)` or `Trace/breakpoint trap` are actually printed by your *shell*, not the program/kernel. Don't believe me? Try running `set +m` before your program or redirecting stderr to a file.
* You can use `int 0x80` in 64-bit mode. It will use the 32-bit ABI though (eax, ebx, ecx, edx), so make sure all pointers are in the low 32 bits. On the small code model, this true for all code stored in your binary. Keep this in mind for .
    + Additionally, `sysenter` and `call dword gs:0x10` can also do syscalls in 32-bit mode, although the calling convention is quite....weird for the former.

#### DOS/BIOS specific:

* Use `int 29h` instead of `int 21h:02h` for printing single bytes to the screen. `int 29h` doesn't need `ah` to be set and *very* conveniently uses `al` instead of `dl`. It writes directly to the screen, so you can't just redirect to a file, though.
* DOS also has `strlen` and `strcmp` interrupts (see this helpful page for this and other undocumented goodies)
* Unless you modified `cs`, **don't** use `int 20h` or `int 21h:4Ch` for exiting, just `ret` from your `.com` file. Alternatively, if you happen to have `0x0000` on the top of your stack, you can also `ret` to that.
* In the rare case that you need to call helper functions more than 4 times, consider registering them to the `int1`, `int3`, or `into` interrupts. Make sure to use `iret` instead of `ret`, though.

```
        ; AH: 0x25 (set interrupt)
        ; AL: 0x03 (INT3)
        ; Use 0x2504 for INTO, or 0x2501 for INT1
        mov     ax, 0x2503
        ; DX: address to function (make sure to use IRET instead of RET)
        mov     dx, my_interrupt_func
        int     0x21

        ; Now instead of this 3 byte opcode...
        call    my_func
        ; ...just do this 1 byte opcode.
        int3 ; or int1, into

```
* tip: Your interrupt vector table is a table of far pointers at `0000:0000` (so for example, `int 21h` is at `0000h:0084h`).

# Answer
> 2 votes
# Use conditional moves `CMOVcc` and sets `SETcc`

This is more a reminder to myself, but conditional set instructions exist and conditional move instructions exist on processors P6 (Pentium Pro) or newer. There are many instructions that are based on one or more of the flags set in EFLAGS.

# Answer
> 2 votes
# Use whatever calling conventions are convenient

System V x86 uses the stack and System V x86-64 uses `rdi`, `rsi`, `rdx`, `rcx`, etc. for input parameters, and `rax` as the return value, but it is perfectly reasonable to use your own calling convention. \__fastcall uses `ecx` and `edx` as input parameters, and other compilers/OSes use their own conventions. Use the stack and whatever registers as input/output when convenient.

Example: The repetitive byte counter, using a clever calling convention for a 1 byte solution.

Meta: Writing input to registers, Writing output to registers

Other resources: Agner Fog's notes on calling conventions

# Answer
> 2 votes
# Save on `jmp` bytes by arranging into if/then rather than if/then/else

This is certainly very basic, just thought I would post this as something to think about when golfing. As an example, consider the following straightforward code to decode a hexadecimal digit character:

```
    cmp $'A', %al
    jae .Lletter
    sub $'0', %al
    jmp .Lprocess
.Lletter:
    sub $('A'-10), %al
.Lprocess:
    movzbl %al, %eax
    ...

```

This can be shortened by two bytes by letting a "then" case fall into an "else" case:

```
    cmp $'A', %al
    jb .digit
    sub $('A'-'0'-10), %eax
.digit:
    sub $'0', %eax
    movzbl %al, %eax
    ...

```

# Answer
> 2 votes
# (way too many) ways of zeroing a register

I remember being taught these by a certain person (I "invented" some of these myself); I don't remember who did I get them from, anyways these are the most interesting; possible use cases include restricted source code challenges or other bizzare stuff.

`=>` Zero mov:

```
mov reg, 0
; mov eax, 0: B800000000

```

`=>` `push`+`pop`:

```
push [something equal to zero]
pop reg
; push 0 / pop eax: 6A0058

; note: if you have a register equal to zero, it will be
; shorter but also equal to a mov.

```

`=>` `sub` from itself:

```
sub reg, reg
; sub eax, eax: 29C0

```

`=>` `mul` by zero:

```
imul reg, 0
; imul eax, 0: 6BC000

```

`=>` `and` by zero:

```
and reg, 0
; and eax, 0: 83E000

```

`=>` `xor` by itself:

```
xor reg, reg
; xor eax, eax: 31C0

; possibly the best way to zero an arbitrary register,
; I remembered this opcode (among other).

```

`=>` `or` and `inc` / `not`:

```
or reg, -1
inc reg     ; or not reg

; or eax, -1 / inc eax: 83C8FF40

```

`=>` reset `ECX`:

```
loop $

; loop $: E2FE

```

`=>` flush `EDX`:

```
shr eax, 1
cdq

; D1E899

```

`=>` zero `AL` (`AH = AL, AL = 0`)

```
aam 1
; D401

```

`=>` reset `AH`:

```
aad 0
; D500

```

`=>` Read 0 from the port

```
mov dx, 81h
in al, dx
; 66BA8100EC

```

`=>` Reset `AL`

```
stc
setnc al
; F90F93C0

```

`=>` Use the zero descriptor from `gdt`:

```
sgdt [esp-6]
mov reg, [esp-4]
mov reg, [reg]
; with eax: 0F014424FA8B4424FC8B00

```

`=>` Read zero from the `fs` segment (PE `exe` only)

```
mov reg, fs:[10h]
; with eax: 64A110000000

```

`=>` The brainfuck way

```
inc reg
jnz $-1
; with eax: 4075FD

```

`=>` Utilize the coprocessor

```
fldz
fistp dword ptr [esp-4]
mov eax, [esp-4]
; D9EEDB5C24FC8B4424FC

```

Another possible options:

* Read zero using the builtin random number generator.
* calculate sine from `pi * n` (use `fmul`).

There are way cooler and potentially useful ways to execute this operation; although I didn't come up with them, therefore I'm not posting.

# Answer
> 2 votes
# Use multiplication for hashing

IMUL, multiplication by an immediate signed number, is a powerful instruction which can be used for hashing.

The regular multiplication instruction hard-codes one of the input operands and the output operand to be in `eax` (or `ax` or `al`). This is inconvenient; it requires instructions for setup and sometimes also to save and restore `eax` and `edx`. But if one of the operands is a constant, the instruction becomes much more versatile:

* No need to load the constant into a register
* The other operand can be in any register, not only `eax`
* The result can be in any register, not necessarily overwriting the input!
* The result is 32-bit, not a pair of registers
* If the constant is between -128 and 127, it can be encoded by only one byte

I used this many times (I hope I can be excused for these shameless plugs:    ...)

# Answer
> 2 votes
"Free bypass": If you already have an instruction with an immediate on a register that you only care about the low part of, making the immediate longer than necessary could allow you to insert into its high part other instructions that can be jumped to (but don't execute when coming from before). This works because of little-endianness. Example; another example.

# Answer
> 1 votes
**To copy a 64-bit register, use `push rcx` ; `pop rdx`** instead of a 3-byte `mov`.
The default operand-size of push/pop is 64-bit without needing a REX prefix.

```
  51                      push   rcx
  5a                      pop    rdx
                vs.
  48 89 ca                mov    rdx,rcx

```

(An operand-size prefix can override the push/pop size to 16-bit, but 32-bit push/pop operand-size is not encodeable in 64-bit mode even with REX.W=0.)

If either or both registers are `r8`..`r15`, use `mov` because push and/or pop will need a REX prefix. Worst case this actually loses if both need REX prefixes. Obviously you should usually avoid r8..r15 anyway in code golf.

---

You can keep your source more readable while developing with this **NASM macro**. Just remember that it steps on the 8 bytes below RSP. (In the red-zone in x86-64 System V). But under normal conditions it's a drop-in replacement for 64-bit `mov r64,r64` or `mov r64, -128..127`

```
    ; mov  %1, %2       ; use this macro to copy 64-bit registers in 2 bytes (no REX prefix)
%macro MOVE 2
    push  %2
    pop   %1
%endmacro

```

Examples:

```
   MOVE  rax, rsi            ; 2 bytes  (push + pop)
   MOVE  rbp, rdx            ; 2 bytes  (push + pop)
   mov   ecx, edi            ; 2 bytes.  32-bit operand size doesn't need REX prefixes

   MOVE  r8, r10             ; 4 bytes, don't use
   mov   r8, r10             ; 3 bytes, REX prefix has W=1 and the bits for reg and r/m being high

   xchg  eax, edi            ; 1 byte  (special xchg-with-accumulator opcodes)
   xchg  rax, rdi            ; 2 bytes (REX.W + that)

   xchg  ecx, edx            ; 2 bytes (normal xchg + modrm)
   xchg  rcx, rdx            ; 3 bytes (normal REX + xchg + modrm)

```

The `xchg` part of the example is because sometimes you need to get a value into EAX or RAX and don't care about preserving the old copy. push/pop doesn't help you actually exchange, though.

# Answer
> 1 votes
# Try `AAM` or `AAD` for byte division operations

If you are working with only 8 bit values, using the `AAM` instruction can sometimes save several bytes over `DIV reg8` since it will take an `imm8` and returns remainder and quotient in opposite `AH/AL` registers as `DIV`.

```
D4 0A    AAM        ; AH = AL / 10, AL = AL % 10

```

It can also accept any byte value as the divisor as well by altering the second byte.

```
D4 XX    AAM  XX    ; AH = AL / XX, AL = AL % XX

```

And `AAD` is the inverse of this, which is two operations in one.

```
D5 XX    AAD  XX    ; AL = AH * XX + AL

```

# Answer
> 1 votes
# Avoid registers which need prefixes

Quite a simple tip I haven't seen mentioned before.

**Avoid `r8-r15` (as well as `dil`, `sil`, `bpl`, and `spl`) on x86\_64 like the plague.** Even just thinking about these registers requires an extra REX prefix. The only exception is if you are using them exclusively for 64-bit arithmetic (which also needs REX prefixes). Even still, you are usually better off using a low register since some operations can be done using the implicit zero extension.

Note that this tip also applies to ARM Thumb-2.

Additionally, be careful when using 16-bit registers in 32/64-bit mode (as well as 32-bit registers in 16-bit mode, but this is rare), as these need a prefix byte as well.

However, unlike the extra x86\_64 registers, 16-bit instructions can be useful: Many instructions which would otherwise need a full 32-bit immediate argument will only use a 16-bit argument. So, if you were to bitwise and `eax` by `0xfffff00f`, `and ax, 0xf00f` would be smaller.

# Answer
> 1 votes
# Use `shr` for first occurrence lookup tables

Often times you need to do something like this to check whether a byte has been encountered:

```
bool found[256]={false};
for (uint8_t x : data) {
    // Check for first occurrence
    if (!found[x]) {
        // mark it as encountered
        found[x] = true;
        // do something
        func(x);
    }
}

```

There is a very easy way to do this in x86, and that is via `shr`.

### Setup

Setting it up is easy thanks to `push -1` which can create a block of 1 bits. I use x86\_64 here, but it is the same on x86.

You can switch it to `rep stos` if you have that set up, but it isn't worth it to set up just for that loop.

```
        push    TABLE_SIZE/8
        pop     rcx
.Lpush_loop:
        push    -1
        loop    .Lpush_loop

```

### Usage

`shr` will both mark the occurrence **and** indicate that it was unique by setting `OF`.

```
.Lloop:
        lodsb # example

        # 3 bytes (2 bytes if you use RDI/RBX/RBP/RSI or a register src)
        shr     byte ptr [rsp + rax]
        # OF == first occurrence
        jno     .Lfound

.Lfirst_occurrence:
        ...
.Lfound:
        loop    .Lloop # example

```

Magic.

See my answer for Type uniqchars! where I thoroughly explain it.

# Answer
> 1 votes
## Align Registers to by Power of 2 Value with or/inc

Say you want to aligned a pointer for a load. I.e saying aligning for `xmm` load:

This is a pretty common idiom:

```
addq $16, %rdi   // 4b
andq $-16, %rdi  // 4b

```

A cheaper way:

```
orq $15, %rdi    // 4b
incq %rdi        // 3b

```

If your pointer is in RAX, the special 2-byte `op al, imm8` no-modrm encoding is useful. Writing a byte or word register leaves the upper bytes untouched. On older Intel CPUs (before Sandybridge) this can cause a partial-register stall, but even for performance it's safe on modern CPUs.

```
or  $0xf, %al     // 2b   (leave upper bytes untouched)
inc %rax          // 3b   (carry into the upper bytes is possible)

or  $0xf, %dl     // 3b
inc %rdx          // 3b

or  $0xf, %dil    // 4b  REX + opcode + modrm + imm8
inc %rdi          // 3b  no savings

```

Also works with `and $0xf0, %al` to round down to the previous alignment boundary.

---

Also worth noting the `or` alone will round to value minus 1 so it can be used to keep address offsets in `imm8` short encoding range i.e:

```
andq $-16, %rdi
// Stuff on (%rdi)[0, 79]
vmovdqa 80(%rdi), %xmm0

```

vs.

```
orq $15, %rdi
// Stuff on -15(%rdi)[0, 79]
vmovdqa 65(%rdi), %xmm0
# vmovdqa 80 - 15(%rdi), %xmm0   # same thing, but with the -15 in the asm source

```

# Answer
> 1 votes
# pop ax and throw a value from stack

```
pop eax

```

# push word 0; push word 8

```
push dword 8

```

# push dword 9999

```
push word 0
push word 9999

```

# Answer
> 1 votes
# AND to clear memory

```
0:  c7 01 00 00 00 00       mov    DWORD PTR [ecx],0x0
6:  31 c0 89 01             xor    eax,eax / mov DWORD PTR [ecx],eax
a:  83 21 00                and    DWORD PTR [ecx],0x0

```

# Answer
> 0 votes
You can fetch sequential objects from the stack by setting esi to esp, and performing a sequence of lodsd/xchg reg, eax.

---
Tags: code-golf, tips, assembly, machine-code, x86-family
---


# Question
Title: What is the ABSOLOUTE shortest way to write this code?
So I got kinda bored and was wondering if it was possible to make this code shorter without modifying anything except a file named coin.py...

```
from random import*;c=['heads','tails'];print('u win'if choice(c)==input(' / '.join(c)+': ')else'u lose')

```

The program asks the user for either "heads" or "tails", if the result from `random.choice(c)` matches the user's input, print "you win" to the console. Otherwise print "you lose" to the console.

Example:

```
heads / tails: tails
u win

heads / tails: tails
u lose

```

(no loop needed btw, just run once)

Maintaining all its functionality & having the EXACT same output

Have fun, stack exchage :)

Update: Security practices don't matter for this question

# Answer
> 4 votes
Few improvements off the top of my head:

1. (Shaves two characters) You don't need a `list`, a `tuple` will do, so:

```
c=['heads','tails']

```

can shorten to (parentheses around `tuple`s are optional when it has at least one item and it's unambiguous):

```
c='heads','tails'

```
2. (Shaves four characters) You can interleave the two output strings into a single one, and do a slice skipping by 2, with the start point based on your condition, shaving:

```
print('u win'if choice(c)==input(' / '.join(c)+': ')else'u lose')

```

down to:

```
print('uu  lwoisne'[choice(c)==input(' / '.join(c)+': ')::2])
# Or if you prefer, no change in length:
print('u','lwoisne'[choice(c)==input(' / '.join(c)+': ')::2])

```
3. (Shaves five characters) Use `printf`-style formatting to construct your string, now that `c` is a `tuple`, this is cheap:

```
print('uu  lwoisne'[choice(c)==input(' / '.join(c)+': ')::2])

```

to:

```
print('uu  lwoisne'[choice(c)==input('%s / %s: '%c)::2])

```

---
Tags: code-golf, tips, python
---


title: Knight to fork!

text:
# Question
Title: Knight to fork!
In chess, *fork* means to target two pieces with just one piece, and one of the best pieces for forking is the knight.

In this challenge, you will be given three coordinates in `a` to `h` and `1` to `8` (like `a8` or `e7`) format. The first and second coordinates are for two other random pieces, and the third is the knight's coordinate. You must return or output the coordinate where the knight can move to create a fork, attacking both pieces. An example is this:

Here, the first and second inputs will be `d6` and `f6` and the third (knight) will be `g3`. You must return `e4`, where the knight can attack both rooks.

### Testcases

```
Input: d6,f6,g3 | Output:e4
Input: d4,d6,e7 | Output:f5
Input: c3,f2,b2 | Output:d1

```

#### Notes

* You may assume it is possible to find a fork with the given input.

This is so the shortest code wins!

# Answer
> 16 votes
# Python 2, 129 bytes

```
def f(a):x,p,y,q,z,r=map(ord,a);x-=z;y-=z;p-=r;q-=r;u=x*x+p*p;v=y*y+q*q;w=x*q-y*p<<1;return chr((u*q-v*p)/w+z)+chr((v*x-u*y)/w+r)

```

Try it online!

Input as a single string like `f("d6f6g3")`.

For given three points \\$\left(x\_1,y\_1\right)\\$, \\$\left(x\_2,y\_2\right)\\$, \\$\left(x\_3,y\_3\right)\\$, the center of the circle determined by these three points is

$$ \left( \frac{\left|\begin{matrix}x\_1^2+y\_1^2 & y\_1 & 1 \\ x\_2^2+y\_2^2 & y\_2 & 1 \\ x\_3^2+y\_3^2 & y\_3 & 1 \end{matrix}\right|}{2\cdot\left|\begin{matrix}x\_1 & y\_1 & 1 \\ x\_2 & y\_2 & 1 \\ x\_3 & y\_3 & 1 \end{matrix}\right|}, \frac{\left|\begin{matrix}x\_1^2+y\_1^2 & x\_1 & 1 \\ x\_2^2+y\_2^2 & x\_2 & 1 \\ x\_3^2+y\_3^2 & x\_3 & 1 \end{matrix}\right|}{2\cdot\left|\begin{matrix}x\_1 & y\_1 & 1 \\ x\_2 & y\_2 & 1 \\ x\_3 & y\_3 & 1 \end{matrix}\right|} \right) $$

And this formula is find out from this SE post. I'm too lazy to find out the formula by myself.

# Answer
> 13 votes
# Vyxal, ~~50~~ ~~21~~ 19 bytes

```
ƛk-:dẊ:RJ$Cv+C;Þf∆M

```

Try it Online!

One of the programs ever written. Luckily, there's no enpassant with horseys, so there's no bricks needed. However, I will note that this doesn't account for knightboosting. Also doesn't account for knook movements.

Uses the simplification of the problem pointed out by @mousetail in the comments.

## Explained

```
□ƛ # To all squares in the input

k-:dẊ:RJ  # Generate all vector directions of how the horsey moves. This is the hardest part because until recently, not even the smartest scientists knew how the horsey moved.
# This will be a list of [horizontal spaces, vertical spaces]
# [[-1, 2], [2, 1], ...]]

# Generated by:
# Doubling the list [1, -1] (k-:d)
# Getting the cartesian product of those two lists (Ẋ)
# Pushing a second copy and reversing each list in it (R)
# And joining it to the cartesian product (J)

Cv+C # To a list of ordinal points of where the horsey is, add each horsey move

ÞfĊ↑h # Flatten by a layer and get the most common square.

```

If you can't tell from that, I am somewhat of a chess anarchist :p

# Answer
> 8 votes
# Factor, ~~86~~ ~~79~~ ~~76~~ 67 bytes

```
[ [ """"zip [ 3 v-n v+ ] with map ] map-flat mode ]

```

Try it online!

Takes input as a sequence of three strings.

* `[ ... ] map-flat` Map over each element in the input, flattening the results.
* `""""` Two strings with eight literal control characters each. (You can see them on TIO.)
* `zip` Zip them together. These are the knight moves + 3 -- i.e.

```
{ { 4 5 } { 4 1 } { 5 4 } { 5 2 } { 2 1 } { 2 5 } { 1 2 } { 1 4 } }

```
* `[ 3 v-n v+ ] with map` Add the element we're mapping over to each of the knight moves. For example, if the current element is `"d4"`, this is the result:

```
{ "e6" "e2" "f5" "f3" "c6" "c2" "b5" "b3" }

```
* There will occasionally be results that are outside of the board, but it doesn't matter because these will never be the most frequent move.
* `mode` Find the most common move.

# Answer
> 7 votes
# K (ngn/k), 32 bytes

Takes input as a single list of three strings.

```
`c$*>#'=,/(2-5\28848 84144)+/:\:

```

Try it online!

Apply all 8 knight moves to each of the pieces, then find the most common target square.

The knight moves are hardcoded using base encoding, the shortest way I found to actually generate them was 5 bytes longer:

```
+,/|:\',/2 -2,'/:1 -1

```

# Answer
> 7 votes
# Python, 96 bytes (@tsh)

```
f=lambda A,R=1:{5}^{(R//9-ord(f))**2+(R%9-int(r))**2for f,r in A}and f(A,R+1)or f"{R//9:c}{R%9}"

```

Attempt This Online!

### Old Python, 100 bytes

```
f=lambda A,R=1,F=97:{5}^{(F-ord(f))**2+(R-int(r))**2for f,r in A}and f(A,R%8+1,F+R//8)or f"{F:c}{R}"

```

Attempt This Online!

Expects a list of three two-character strings. Trusts OP's promise that it is a forkable position (will never return otherwise).

### How?

Well, there are only 64 candidate squares so we check them all.

# Answer
> 6 votes
# Python, 144 bytes

```
lambda a,b,c:(g(a)&g(b)&g(c)).pop()
g=lambda x:{chr(ord(x[0])+i)+str(int(x[1])+j)for(k,l)in((1,2),(-1,2),(1,-2),(-1,-2))for(i,j)in((k,l),(l,k))}

```

Attempt This Online!

Performs "en passant" whenever possible. Which is never, since there are no white pawns.

# Answer
> 6 votes
# Excel, ~~126~~ 122 bytes

Saved 4 bytes by dropping `m` as a variable.

```
=LET(a,A1:C3,x,CODE(A1:A3)-96,c,MMULT(MINVERSE(2*IFS(a=0,.5,ISTEXT(a),x,1,a)),x^2+B1:B3^2),CHAR(INDEX(c,1)+96)&INDEX(c,2))

```

Inspired by tsh's answer although I found a different formula. Note that Excel will change `IFS(a=0,.5,` to `IFS(a=0,0.5,` after you enter the formula.

Input is in the range `A1:B3` with one half of each coordinate per cell. The range `C1:C3` must be left blank. The formula can go anywhere except in the range `A1:C3`. The first testcase is input like this:

The `LET()` function allows you to store data as variables and later reference those variables. The terms are in pairs except the last which is the output.

* `a,A1:C3` stores the input range as a 3x3 array.
* `x,CODE(A1:A3)-96` stores the number version of the input letters in a 1x3 array.

+ You *could* leave off the `-96` part here and the `+96` part later but doing that matrix math with larger numbers has rounding errors so you may sometimes get answers like `e4.00000000000023` and these two offsets are less bytes than trying to round it later.
* `IFS(a=0,.5,ISTEXT(a),x,1,a)` converts the input array into a more usable form by:

+ Replacing the blanks in `C1:C3` with `.5`
    + Replace the characters in `A1:A3` with their numerical equivalent
    + The end result looks like this:
* `c,MMULT(MINVERSE(2*IFS(~)),x^2+B1:B3^2)` does fancy math stuff (that I did not write myself but I did tweak a bit) and it spits out a 1x3 array with the x-coordinate, y-coordinate, and constant from the general equation for a circle. For the first testcase, the value of `c` looks like this:
* `CHAR(INDEX(c,1)+96)&INDEX(c,2)` changes the x-coordinate to a letter and concatenates it with the y-coordinate.

---

Here are the results for the three testcases:

# Answer
> 5 votes
# Charcoal, ~~52~~ 30 bytes

```
Ｆ³⊞υＳΦΣＥβＥχ⁺ιλ⬤υ⁼⁵ΣＸＥλ⁻℅ν℅§ιξ²

```

Attempt This Online! Link is to verbose version of code. Explanation:

```
Ｆ³⊞υＳ

```

Input the three strings.

```
ΦΣＥβＥχ⁺ιλ

```

Create the 260 strings `a0` to `z9` and filter on the one that satisfies...

```
⬤υ⁼⁵ΣＸＥλ⁻℅ν℅§ιξ²

```

... the sum of the squared ordinal differences between corresponding code points is equal to `5`.

# Answer
> 5 votes
# Jelly, 14 bytes

```
O+€Ø+pḤUƬẎ¤f/Ọ

```

A monadic Link that accepts a list of the three distinct, pairs of characters and yields a list of one pair of characters representing the destination square. When run as a full program the destination is printed.

**Try it online!**

### How?

The square on which the knight may fork is the square all three pieces could move to *if* they were all knights. The code finds those three sets of squares (including off-board ones\*) and finds the intersection.

```
O+€Ø+pḤUƬẎ¤f/Ọ - Link: list of lists of characters, C
O              - cast (C) to ordinals
          ¤    - nilad followed by link(s) as a nilad:
   Ø+          -   [-1, 1]
      Ḥ        -   double -> [-2, 2]
     p         -   cartesian product -> [[1,2],[1,-2],[-1,2],[-1,-2]]
        Ƭ      -   collect while distinct applying:
       U       -     reverse each -> [[[1,2],[1,-2],[-1,2],[-1,-2]],[[2,1],[-2,1],[2,-1],[-2,-1]]]
         Ẏ     -   tighten -> [[1,2],[1,-2],[-1,2],[-1,-2],[2,1],[-2,1],[2,-1],[-2,-1]]
 +€            - add to each ordinal pair (vectorises)
            /  - reduce by:
           f   -   filter keep
             Ọ - cast to characters

```

---

* Even though off-board positions may be present in the three sets I believe that this will yield the single destination square if possible or an empty list if not possible. (The three inputs just need to be distinct!)

# Answer
> 5 votes
# Brachylog, 20 bytes

```
{l;1~ȧᵐ≜p;?ạᵗz+ᵐ~ạ}ᵛ

```

Try it online!

```
{                 }ᵛ    Produce the same output from all elements of the input:
 l                      take the element's length (2),
  ;1                    pair it with 1,
    ~ȧᵐ≜                un-absolute-value both,
        p               and permute;
         ;   z+ᵐ        sum with corresponding elements of
           ạᵗ           the character codes of
          ?             the element;
                ~ạ      convert from character codes.

```

# Answer
> 4 votes
# 05AB1E, 16 bytes

```
Ç®X‚xâDí«δ+çJ˜.M

```

Inspired by *@mousetail*'s comment!

Try it online or verify all test cases.

**Explanation:**

```
Ç         # Convert the (implicit) input-triplet of strings to pairs of their codepoints
®X‚xâDí«  # Push list [[-1,-2],[-1,2],[1,-2],[1,2],[-2,-1],[2,-1],[-2,1],[2,1]]:
®X‚       #  Push pair [-1,1]
   x      #  Double the values in this pair (without popping): [-2,2]
    â     #  Get the cartesian product of the two pairs
     D    #  Duplicate this list
      í   #  Reverse each inner pair
       «  #  Merge the two lists together
δ         # Apply on the two lists double-vectorized:
 +        #  Add them together
ç         # Convert each inner-most integer back to a character with this codepoint
 J        # Join each inner pair together to a string
  ˜       # Flatten the list of lists of strings
   .M     # Pop and leave the most frequent string
          # (which is output implicitly as result)

```

# Answer
> 4 votes
# Jelly, 11 bytes

```
⁹p`ạỤ€Ƒ¥ƇOỌ

```

Try it online!

Sidesteps actually generating knight moves by just checking them with good old brute force.

```
⁹p`            Generate the Cartesian product of [1 .. 256] with itself.
⁹p`            256 is Jelly's smallest single byte constant >= 108,
         O     the character code of 'h'.
        Ƈ      Filter that list of pairs to the single one for which
   ạ   ¥       the list of its element-wise absolute differences from each of
         O     the input pairs converted to character codes
      Ƒ        is equal to itself with
     €         each difference pair
    Ụ          graded up (converted to a list of indices sorted by their values).
    Ụ Ƒ        Every list of length 2 grades up to either [1, 2] or [2, 1].
          Ọ    Convert the surviving pair from character codes.

```

# Answer
> 4 votes
# C (GCC), ~~138~~ ~~133~~ ~~131~~ 126 bytes

*-12 bytes thanks to @ceilingcat*

```
f(s,x,b,i)char*s,*x;{b=0;for(*x=96;b=i=!b&(++x[1]<58||++*x<105&&(x[1]=48));)for(;i<8;i+=3)b*=abs((*x-s[i-1])*(x[1]-s[i]))==2;}

```

Attempt This Online!

# Answer
> 3 votes
# JavaScript (Node.js), ~~77~~  76 bytes idea from tsh

-1 byte from naffetS

```
f=(a,i)=>a.some(x=>(parseInt(x,18)-i)**2%323%179^77)?f(a,-~i):i.toString(18)

```

Try it online!

# JavaScript (Node.js), ~~87~~ 85 bytes

```
f=(a,i=180)=>a.every(x=>/16|20|35|37/.test(parseInt(x,18)-i))?i.toString(18):f(a,-~i)

```

Try it online!

Discuss in base 18

18 is only choice

25-29 to only save a `$`

# Answer
> 3 votes
# Ruby, 113 bytes

```
->s{a=s.bytes
20000.times{|i|(a[1+j=i%3*2]-y=i/3%58)**2+(a[j<1?C=0:j]-x=i/174)**2==5&&C+=1
C>2&&(p x.chr+y.chr)}}

```

Try it online!

Function takes input as a single string like `d6f6g3` and prints output to stdout.

The idea is to find coordinates whose euclidean distance squared from all three inputs is 5. This is counted in `C`, which is reset every third iteration when `j=i%3*2` is zero. A lowercase `c` (variable) would halt execution because Ruby assumes that it may not be initialized by the time it is needed. Therefore we use an uppercase constant `C` which executes fine (but generates a warning to stderror every time it is changed.)

Input is converted from characters to ASCII codes and final result is converted back from ASCII codes to characters. As ASCII codes for `h8` are 104 and 56, there are nearly 6000 possibilities for the output. For each of these we have to check the 3 inputs so the minimum number of iterations required is a little under 20000. Code is short, but inefficient! If uppercase input is allowed, this can be reduced to just over 12000 iterations.

# Answer
> 3 votes
# Desmos, 126 bytes

```
L=[-2...2]
P=[(a,b)fora=L,b=L]
A=[p+qforp=l+0P,q=P[P.x^2+P.y^2=5]]
X=A[A.x=i.x]
C=[X[X.y=i.y].lengthfori=A]
f(l)=A[C=C.max][1]

```

Takes in a list of points, with each coordinate being a charpoint, and returns a point, with each coordinate being a charpoint.

This is just a port of one of the strategies I saw while scrolling through here. It finds all possible positions that can be reached if all three pieces are treated as knights, and find the mode (most common value) of those positions. There is probably a better way to do this (maybe something more mathematical?), but I think this is fine for now.

As a bonus, I included a simple chessboard graphic so y'all can visualize the test cases :D

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 3 votes
# Wolfram Language (Mathematica), ~~182~~ 170 bytes

Saved 12 bytes thanks to comment.

```
Module[{x,p,y,q,z,r,u,v,w},{x,p,y,q,z,r}=ToCharacterCode@a;x-=z;y-=z;p-=r;q-=r;u=x^2+p^2;v=y^2+q^2;w=(x*q-y*p)*2;FromCharacterCode@{⌊u*q-v* p⌋/w+z,⌊v*x-u*y⌋/w+r}]

```

Try it online!

A port of @tsh's answer.

Explicit Mathematica code

```
f[a_String] := Module[{x, p, y, q, z, r, u, v, w, char1, char2},
  {x, p, y, q, z, r} = ToCharacterCode[a];
  x -= z;
  y -= z;
  p -= r;
  q -= r;
  u = x*x + p*p;
  v = y*y + q*q;
  w = BitShiftLeft[x*q - y*p, 1];
  char1 = FromCharacterCode[Quotient[(u*q - v*p), w] + z];
  char2 = FromCharacterCode[Quotient[(v*x - u*y), w] + r];
  StringJoin[char1, char2]
]

```

# Answer
> 0 votes
# Nekomata, 13 bytes

```
eᵐ{2R↕ᵐᶜ_+}≡H

```

Attempt This Online!

```
eᵐ{2R↕ᵐᶜ_+}≡H
e               Char to codepoint
 ᵐ{       }     Map
   2R↕ᵐᶜ_       Any of the 8 knight moves
         +      Add
           ≡    Check if all equal
            H   Char from codepoint

```

The `2R↕ᵐᶜ_` part is taken from my answer to the challenge *Generate All 8 Knight's Moves*.

---
Tags: code-golf, chess
---


title: Reversencode the given string

text:
# Question
Title: Reversencode the given string
Given a string, if it is even, break the string into 2 even parts, then reverse the parts to get the "reversencoded" string.

Example:

onomatopoeia -\> tamonoaieopo

If the string is not of even length, then do not change the position of the middle character, and reverse the letters before and after the middle character.

Example:

pizza -\> ipzaz

discord -\> sidcdro

Limitations: The input will not contain any other characters other than AlphaNumeric characters. i.e. No newlines/whitespaces.

General contest, shortest code in each language will be winning. Good luck!

*btw: i made up the word reversencoded, i'm fairly sure such a form of "encryption" doesnt exist*

# Answer
# Jelly, 6 bytes

```
ṚŒHZUZ

```

Try it online!

## Explanation

Consider the string `ABCDEFGHI`:

```
ṚŒHZUZ
Ṛ      reverse -> IHGFEDCBA
 ŒH    split into halves -> IHGFE
                            DCBA
   Z   transpose -> ID
                    HC
                    GB
                    FA
                    E
    U  reverse each row -> DI
                           CH
                           BG
                           AF
                           E
     Z transpose -> DCBAE
                    IHGF
       implicitly concatenate -> DCBAEIHGF

```

*I never thought the time would come when I'd outgolf Jonathan Allan in Jelly…*
> 16 votes

# Answer
# Factor, ~~76~~ ~~72~~ 65 bytes

```
[ dup length 2 rem swap halves rot cut [ reverse ] tri@ 3append ]

```

Try it online!

*-7 bytes thanks to @Bubbler!*

## Explanation:

It's a quotation (anonymous function) that takes a string from the data stack as input and leaves a string on the data stack as output. Assuming `"pizza"` is on the data stack when this quotation is called...

* `dup` Duplicate the object on top of the data stack

**Stack:** `"pizza" "pizza"`
* `length` Take the length

**Stack:** `"pizza" 5`
* `2` Push `2` to the stack

**Stack:** `"pizza" 5 2`
* `rem` The remainder of dividing second-from-top by top

**Stack:** `"pizza" 1`
* `swap` Swap the top two objects

**Stack:** `1 "pizza"`
* `halves` Cut a sequence in half. If the sequence has an odd number of elements, the extra element will be in the sequence that is on top of the stack. `halves` returns slices for efficiency.

**Stack:** `1 T{ slice f 0 2 "pizza" } T{ slice f 2 5 "pizza" }`
* `rot` Move the object third from the top to the top

**Stack:** `T{ slice f 0 2 "pizza" } T{ slice f 2 5 "pizza" } 1`
* `cut` Take a sequence and an index and split the sequence in two at that index. When given an index at either end of a sequence, an empty string will be one of the outputs. `cut` will "reify" the slice.

**Stack:** `T{ slice f 0 2 "pizza" } "z" "za"`
* `[ reverse ]` Push a quotation for `tri@` to use later

**Stack:** `T{ slice f 0 2 "pizza" } "z" "za" [ reverse ]`
* `tri@` Apply a quotation to three objects. In this case, reverse them.

**Stack:** `"ip" "z" "az"`
* `3append` Append three sequences

**Stack:** `"ipzaz"`
> 11 votes

# Answer
# Jelly, 9 bytes

```
LHịJ‘œṖ⁸U

```

Try it online!

Full program, due to Jelly's smash-printing

## How it works

```
LHịJ‘œṖ⁸U - Main link. Takes a string S on the left
L         - Length of S, L
 H        - L÷2
   J      - Indices of S; [1, 2, 3, ..., L]
  ị       - Index into;
             If L is even, this just returns L÷2
             If L is odd, this returns [(L-1)÷2, [(L+1)÷2]
    ‘     - Increment
       ⁸  - Yield S, to prevent œṖ hooking to U
     œṖ   - Partition S at the indices in the left
        U - Reverse each sublist
            Implicitly "smash" together (["ip", "z", "az"] -> "ipzaz") and print

```
> 6 votes

# Answer
# Retina, 36 bytes

```
^((.)+?)(.)??((?<-2>.)+)$
$^$1$3$^$4

```

Try it online! Link includes test cases. Explanation:

```
^((.)+?)(.)??((?<-2>.)+)$

```

Match a minimal prefix, an optional centre character, and then a suffix of the same length as the prefix. The prefix and centre are lazy rather than greedy as that's shorter than checking that the group `$2` is properly balanced.

```
$^$1$3$^$4

```

Reverse the prefix and suffix.
> 6 votes

# Answer
# , 86 bytes

(or 79 bytes with output as a vector of characters instead of a string)

```
function(s,n=nchar(s),m=n/2+.5,o=n:1)intToUtf8(utf8ToInt(s)[c(o[o<m],o[o==m],o[o>m])])

```

Try it online!
> 6 votes

# Answer
# Python 3.8 (pre-release), 50 bytes

```
lambda x:x[(l:=len(x)//2)-1::-1]+x[l:-l]+x[:~l:-1]

```

Try it online!

-8 bytes thanks to dingledooper
> 4 votes

# Answer
# JavaScript (ES6),  ~~59~~  58 bytes

*Saved 1 byte thanks to @edc65*

Expects an array of characters.

```
s=>s.map(c=>s[i*2]?p=s[i+++i]?c+p:p+c:q=c+q,i=p=q='')&&p+q

```

Try it online!

### Commented

```
s =>                 // s[] = input string, as an array
  s.map(c =>         // for each character c in s[]:
    s[i * 2] ?       //   if s[i * 2] is defined, this is either the first
                     //   half of the string or the middle character of a
                     //   string of odd length:
      p =            //     update p:
        s[i++ + i] ? //       if s[i * 2 + 1] is defined, this is not the
                     //       middle character:
          c + p      //         prepend c to p
        :            //       else (middle character):
          p + c      //         append c to p
    :                //   else (2nd half of the string):
      q = c + q,     //     prepend c to q
    i = p = q = ''   //   start with p = q = '' and i zero'ish
  )                  // end of map()
  && p + q           // return p + q

```
> 4 votes

# Answer
# , 25 22 bytes

```
[:;]<@|./.~#\*@-2%~1+#

```

Try it online!

## the idea

Consider `discord`. We solve in two steps:

* Create a mask like `_1 _1 _1 0 1 1 1`. For even number inputs, the mask will not contain 0.
* Use that mask to partition into groups, reversing each group.

## J details

Using discord as an example:

* `1+#` The length plus one, 8 in this case
* `2%~` Divided by 2, so now 4.
* `-` Subtracted elementwise from
* `#\` The range `1..<length>`

```
 _3 _2 _1 0 1 2 3

```
* `*@` Sign of each:

```
 _1 _1 _1 0 1 1 1

```
* `/.~` Use that as mask to group the input
* `<@|.` Reversing and boxing each group

```
┌───┬─┬───┐
│sid│c│dro│
└───┴─┴───┘

```
* `[:;` Raze

```
sidcdro

```
> 4 votes

# Answer
# , ~~81~~ 79 bytes

```
function(s,n=nchar(s),m=n/2+1)intToUtf8(utf8ToInt(s)[c(m:2-1,m[n>1&n%%2],n:m)])

```

Try it online!

*-2 bytes thanks to @Dominic*
*-2 bytes thanks to @Giuseppe*

Developed independently from @Dominic's answer, but some golfs adapted from there.

Abuses the fact that range operator `:` and extract operator `[` both cast their inputs to int.
> 4 votes

# Answer
# Pyth, 21 bytes

```
++_<QK/lQ2*@QK%lQ2_>K

```

Try it online!

```
Q        # input
K/lQ2    # Set K to len(Q)/2 (integer division)
_<QK     # Take first K elements and reverse them
*@QK%lQ2 # The element at index K taken len(Q) % 2 times
_>K      # Take last K elements and reverse them
++       # Concatenate them

```

*-2 bytes thanks to hakr14*
> 3 votes

# Answer
# 05AB1E, ~~16~~ ~~13~~ 12 bytes

```
R2ä`?IgÉiÁ}?

```

Try it online!

```
R     reverse input
2ä    slice to 2 pieces, i.e. ["azz", "ip"]
`     dump pieces to stack
?     print last piece without newline
I     push input
g     length
É     is odd
iÁ}   if true rotate right by one
?     print without newline

```
> 3 votes

# Answer
# Retina 0.8.2, 42 bytes

```
^|$
¶
+`(.*¶)(.)(.*)(.)(¶.*)
$2$1$3$5$4
¶

```

Try it online! Link includes test cases. Explanation:

```
^|$
¶

```

Wrap the input in a working area of three lines.

```
(.*¶)(.)(.*)(.)(¶.*)
$2$1$3$5$4

```

Extract the first and last characters of the input, building them up in reverse in the working area.

```
+`

```

Continue extracting characters until there is at most one left.

Join the pieces back together.
> 3 votes

# Answer
# Jelly, 9 bytes

```
ŒHṚU2¦FƲ⁺

```

A monadic Link accepting a list that yields a list.

**Try it online!**

### How?

```
ŒHṚU2¦FƲ⁺ - Link: list, S
        ⁺ - repeat this twice - i.e. f(f(S)):
       Ʋ  -   last four links as a monad - f(x)
ŒH        -     split (x) into two halves (odd length x gives longer first half)
  Ṛ       -     reverse
    2¦    -     apply to second element:
   U      -       upend (reverses just 2nd element)
      F   -     flatten

```

---

Another 9 byter using the same method:

```
ŒHṪ;UFƲ$⁺

```
> 3 votes

# Answer
# Red, 81 bytes

```
func[s][rejoin[reverse take/part s(n: length? s)/ 2 take/part s n % 2 reverse s]]

```

Try it online!

# Using `parse`, 93 bytes

```
func[s][h:(n: length? s)/ 2 d: n % 2 b:[change copy t h skip(reverse t)]parse s[b d skip b]s]

```

Try it online!
> 3 votes

# Answer
# SNOBOL4 (CSNOBOL4), 95 bytes

```
	M =LEN(SIZE(I =INPUT) / 2)
	I M . L ARB . C M . R RPOS(0)
	OUTPUT =REVERSE(L) C REVERSE(R)
END

```

Try it online!
> 3 votes

# Answer
# V (vim), 54 bytes

```
YpC<c-r>=strlen('<c-r>"')/2
<esc>DkA <esc>0@"li
<esc>$@"hi
<Esc>:%!rev
gJgJF x

```

Try it online!

The 'no whitespace' guarantee helped a lot with writing this solution.

## Explanation

```
YpC<c-r>=strlen('<c-r>"')/2
Yp                          copy input to new line
  C                         cut and open insert mode
   <c-r>=strlen('<c-r>"')/2 set the line to half of input length
                            call this k

<esc>DkA <esc>0@"li
<esc>                       exit insert mode
     D                      delete the number k(and copy)
      k                     move to the input
       A <esc>              insert a space at the end
              0@"l          move right k times from the start
                  i         insert a newline

<esc>$@"hi
     $@"hi                  do the same thing, except from the right

<esc>:%!rev                 reverse all lines

gJgJF x
gJgJ                        join the three lines
    F                       navigate to the previous space
      x                     delete it

```
> 3 votes

# Answer
# Vyxal `s`, 36 bitsv1, 4.5 bytes

```
Ṙ½∩R∩

```

Try it Online!

Porting Jelly is always the best way to do code-golf. Can't believe transpose used to be 2 bytes

## Explained

```
Ṙ½∩R∩
Ṙ         # reversed(input)
 ½        # ↑ split into two halves
  ∩       # transpose ↑
   R      # reverse each row in ↑ (when neither argument is a function, reduce performs vectorised reverse instead)
    ∩     # transpose ↑ and sum using s flag

```
> 3 votes

# Answer
# Julia, ~~50~~ 48 bytes

```
a->a[(d=(l=end)÷2):-1:1]a[d+1:l-d]a[l:-1:l-d+1]

```

Try it online!
> 3 votes

# Answer
# Charcoal, 15 bytes

```
⭆⪪θ⊘⊕Ｌθ⭆⪪ι⊘Ｌθ⮌λ

```

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

```
  θ             Input string
 ⪪              Split into pieces of length
      θ         Input string
     Ｌ          Length
    ⊕           Incremented
   ⊘            Halved
⭆               Map over pieces and join
         ι      Current piece
        ⪪       Split into pieces of length
            θ   Input string
           Ｌ    Length
          ⊘     Halved
       ⭆        Map over pieces and join
              λ Current piece
             ⮌  Reversed
                Implicitly print

```
> 2 votes

# Answer
# Python 3.8, ~~63~~ 62 bytes

```
lambda s:s[(l:=len(s))//2-1::-1]+s[l//2]*(l&1)+s[:-~l//2-1:-1]

```

Try it online!
> 2 votes

# Answer
# 05AB1E (legacy), 9 bytes

```
g;¤Ā‚Ć£íJ

```

Try it online or verify all test cases.

**Explanation:**

```
g          # Get the length of the (implicit) input
 ;         # Halve it
  ¤        # Get the last digit (without popping), which is either 0 or 5
   Ā       # Truthify it, converting the 5 to 1 (0 remains 0)
    ‚      # Pair the two values together
     Ć     # Enclose it; appending the leading halve length as trailing item
      £    # Split the (implicit) input into parts of that size (which truncates the
           # decimals)
       í   # Reverse each part
        J  # Join the parts back together to a string
           # (after which the result is output implicitly)

```

It uses the legacy version of 05AB1E, because in the new version the `¤` won't work on decimals and would require an explicit cast to string (so 10 bytes instead: `g;§¤Ā‚Ć£íJ`).
> 2 votes

# Answer
# Japt, 13 bytes

Splits the input (e.g. `"pizza"` or `"pizzas"`) into an array based on indexes (e.g. `["pi", "z", "za"]` or `["piz", "zas"]`), then maps each item through string reverse and joins again.

```
üÏgUÊ*½-½ÃmÔ¬
ü             // Group input characters by mapped value where
 Ï            // depending on whether the index is smaller, equal or larger than
   UÊ*½-½     // input's length in half minus half,
  g           // the value is -1, 0, or 1.
         Ã    // Then,
          mÔ¬ // map each item through reverse and join to a string.

```

Try it here.
> 1 votes

# Answer
# Scala, 145 bytes

Golfed version, try it online!

```
def f(a:String)={val h=a.length/2;val m=(if(a.length%2==1)a.charAt(h).toString else"");a.substring(0,h).reverse+ a.substring(h+m.length).reverse}

```

Ungolfed version

```
object A extends App {
  val f:String=>String=input=>{
   val halfLength = input.length / 2
   val middleChar = if (input.length % 2 == 1) input.charAt(halfLength).toString else ""
   val firstHalfReversed = input.substring(0, halfLength).reverse
   val secondHalfReversed = input.substring(halfLength + middleChar.length).reverse
   firstHalfReversed + middleChar + secondHalfReversed
  }
  println(f("pizza"))
  println(f("onomatopoeia"))
}

```
> 1 votes

# Answer
# Java (JDK), 102 ~~106~~ bytes

> -4 bytes thanks to @ceilingcat !

For each character we calculate the index of the character it should switch place with.
Incidentally this calculation also gives `-1` for the middle character of an odd-length String, which is quite useful!

```
s->{var r="";for(int j,i=0,l=s.length();i<l;r+=s.charAt(j<0?i-1:j))j=l-(i++*2/l*2-1)*~l/2-i;return r;}

```

Try it online!
> 1 votes

# Answer
# SAS, 132 bytes

```
%let n=%eval(%length(&s)/2);data;s="&s";length a b$&n;a=s;b=reverse(s);s=cats(reverse(a),ifc(length(s)/2=&n,"",char(s,&n+1)),b);run;

```

Assuming you have macrovariable `s` containing the text:

```
%let s=abcXdef;

```

Execute ("ungolfed" for readability):

```
%let n = %eval(%length(&s)/2);

data;
 s = "&s";
 length a b $ &n;
 a = s;
 b = reverse(s);
 s = cats(reverse(a)
         ,ifc(length(s)/2 = &n, "", char(s, &n+1))
         ,b);
run;

```

to print out content of created dataset (named automatically `data<N>`) run:

```
proc print;
run;

```
> 1 votes

# Answer
# ReRegex, 146 bytes

```
( *)@(.)/$2$1 @/@$/%/(\w)( *)( +) %\2(?! )/$2$3% $2$1/(.*?)(\w) ( +)%\3(.*)/!$1>$2!$4>/^(\w*?)( +)%\2(.*)/!$1>!$3>/!(\w*?)(\w)>/$2!$1>/!>//@#input

```

## Explained

```
( *)@(.)/$2$1 @/                    # Count characters. Add a space for every character in the string.
@$/%/                               # Once counting is done, move to dividing
(\w)( *)( +) %\2(?! )/$2$3% $2$1/   # Push character an space pairs over to the other side until it's roughly equal to the lefti n length
(.*?)(\w) ( +)%\3(.*)/!$1>$2!$4>/   # When they're roughly equal, split odd groups into !left>mid!right>
^(\w*?)( +)%\2(.*)/!$1>!$3>/        # Same as above but without the mid character.
!(\w*?)(\w)>/$2!$1>/                # Push the last character of a !> group right behind it, effectively reversing the string.
!>//                                # Clear up any emtpy !> groups
@#input                             # Format the input with a @ counter behind it.

```

Try it online!
> 1 votes

# Answer
# Japt, 11 bytes

```
Ôñ@Ê*½-½ gY

```

Try it
> 1 votes

# Answer
# Nibbles, ~~8~~ 6.5 bytes (13 nibbles)

*Saved 1.5 bytes by porting xigoi's Jelly solution like lyxal did*

```
+`'.`'`\~\@\$

```

Attempt This Online!

### Explanation

```
+`'.`'`\~\@\$
          @    First line of stdin
         \     Reverse
      `\~      Split into two parts
    `'         Transpose
   .           Map this function to each string in that list:
           \$   Reverse it
 `'            Transpose
+              Concatenate together

```
> 1 votes

# Answer
# Java (JDK), 274 bytes

```
class A{public static void main(String[]a){System.out.print(new StringBuilder(a[0].substring(0,a[0].length()/2)).reverse().toString()+(a[0].length()%2==1?a[0].charAt(a[0].length()/2):"")+new StringBuilder(a[0].substring((int)(a[0].length()/2D+.5D))).reverse().toString());}}

```

Try it online!
> 0 votes

# Answer
# Lua, 69 bytes

```
s=...n=#s//2print((s:sub(-n)..s:sub(n+1,-n-1)..s:sub(1,n)):reverse())

```

Try it online!
> 0 votes

# Answer
# C (gcc), ~~106 105~~ 99 bytes

First `for` loop iterates over each half, and the second `for` loop does the reversing.

*-7 bytes thanks to ceilingcat for a bit inversion hack and for optimizing out an unnecessary variable*

```
#define S s[i]^=s[L/2+~i]
i,o,L;f(char*s){L=strlen(s);for(o=0;o<L;s+=o+=L-L/2)for(i=L/4;i--;)S^=S;}

```

Try it online!
> 0 votes

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


# Question
Title: Representing a number as an unordered list of smaller numbers
Suppose we want to encode a large integer \\$x\\$ as a list of words in such a way that the decoder can recover \\$x\\$ regardless of the order in which the words are received. Using lists of length \\$k\\$ and a dictionary of \\$n\\$ words, there are \\$\binom{n+k-1}k\\$ different multisets possible (why?), so we should be able to represent values of \\$x\\$ from \\$1\\$ through \\$\binom{n+k-1}k\\$.

This is a code golf challenge to implement such an encoder and decoder (as separate programs or functions); your golf score is the total code length. Any sensible/conventional input & output formats are allowed.

Encode: Given positive integers \\$n,k,x\\$ with \\$x\le\binom{n+k-1}k\\$, encode \\$x\\$ as a list of \\$k\\$ integers between \\$1\\$ and \\$n\\$ (inclusive).

Decode: Given \\$n\\$ and a list of \\$k\\$ integers between \\$1\\$ and \\$n\\$, output the decoded message \\$x\\$.

Correctness requirement: If `encode(n,k,x)` outputs \\$L\\$ and \\$\operatorname{sort}(L)=\operatorname{sort}(M)\\$, then `decode(n,M)` outputs \\$x\\$.

**Runtime requirement**: Both operations must run in polynomial time with respect to the length of \\$x\\$ in bits. This is meant to rule out impractical brute-force solutions that just enumerate all the multisets.

# Answer
> 3 votes
# Python, 258 bytes

```
from numpy import*
P=cumprod;p=prod
def e(x,k):r=r_[:k]+1;f=p(r);X=x*f-f;i=int(X**(1/k));Q=P([1,*i+r]);Q[-2::-1]*=P(i+1-r);j=sum(Q<=X);x-=Q[j-1]//f;k-=1;return*(1//k*[x]or e(x,k)),j+i-k
d=lambda L,j=1:1+sum([p(s-1+r_[:j])//p(r_[1:(j:=j+1)])for s in sort(L)])

```

Attempt This Online!

Two functions `e` and `d` for encoding and decoding: We do not use or accept parameter `n` since it is not needed (because using the "natural" encoding different `n` will give the same result provided they are large enough).

Multisets are represented as sorted sequences; the decoder also accepts unsorted input.

With `n` eliminated it actually makes sense to talk about complexity in `x` because now `x` can grow without bound.

I'll assume fixed `k` and that all basic operations including taking the `kth` root are polynomial in the bit length of their operands. As `k` is fixed this will also hold for all factorials and binomial coefficients the functions use.

### How?

Decoding is easy since it amounts to summing a couple of binomial coefficients.

Encoding is a bit more tricky as we need to invert binomial coefficients (in `n`, `k` is fixed) to make this constant in terms of basic operations we use the simple inequality

\\$n^\underline k \le n^k \le n^\overline k\\$

where the underline and overline denote falling and rising factorials.

To find the largest `n` such that

\\$\begin{pmatrix}n+k-1 \\ k \end{pmatrix}\le x\\$

we take the `kth` root of `k!x` and then brute force check all rising factorials whose terms "pass" through the value obtained, `k` in total.

# Answer
> 1 votes
# Charcoal, 80 + 31 = 111 bytes

## Encoder, 80 bytes

```
ＮθＮη≔⁰ζ≔⁰ε≔¹δＷ¬›δη«≔δε≦⊕ζ≔÷×δ⁺ζθζδ»Ｆ⮌…⁰θ«Ｗ›εη«≦⊖ζ≔÷×εζ⁺ζ⊕ιε»⟦Ｉζ⟧≧⁻εη¿ι≔÷×ε⊕ι⁺ζιε

```

Try it online! Link is to verbose version of code. 0-indexed. Takes `k` and `x` as inputs. Explanation: Port of the `sord` function from this Math.SE answer, but outputs the values in reverse order since it's golfier.

## Decoder, 31 bytes

```
Ｗ⁻θυＦ№θ⌊ι⊞υ⌊ιＩΣＥυ÷Π…·ι⁺ικΠ…·¹⊕κ

```

Try it online! Link is to verbose version of code. 0-indexed. Takes a list of `k` integers as input. Explanation:

```
Ｗ⁻θυＦ№θ⌊ι⊞υ⌊ι

```

Sort the integers.

```
ＩΣＥυ÷Π…·ι⁺ικΠ…·¹⊕κ

```

Apply the `ords` algorithm from this Math.SE answer.

# Answer
> 0 votes
# Haskell, 283 bytes

```
import Data.List
i=fromIntegral
p=product
m=map
s=succ
t=pred
f n=p[1..n]
a k n=p[n..n+k-1]`div`f k
b k x=t$until((>x).a k)s$floor((i$x*f k)**(1/i k))
d _ _[]=0
d k n(e:f)=a k e+d(k-1)e f
e 1 n x=[x]
e k n x|let m=b k x=m:e(k-1)m(x-a k m)
c k n=(m s.e k n.t,s.d k n.m t.reverse.sort)

```

Try it online!

---
Tags: code-golf, math, combinatorics, restricted-complexity, encoding
---