title: "Early bird" squares

text:
# Question
Title: "Early bird" squares
## Definition

If you take the sequence of positive integer squares, and concatenate them into a string of digits (i.e. `149162536496481100...`), an "early bird" square is one that can be found in this string ahead of its natural position.

For example, 72 (the number `49`), can be found at an offset of 2 in the string, although the natural position is at offset 10. Thus 7 is the first "early bird" square.

Note that for it to be considered an "early bird" square, all the digits in the square must occur before the start of the natural position. A match that partially overlaps the natural position does not count.

`a(n)` is the nth positive integer k such that k2 is an "early bird" square.

## Task

Given a positive integer `n`, output `a(n)`.

You can use 1-based or 0-based indexing, but if you use 0-based indexing, please say so in your answer.

You solution should be able to handle at least as high as `a(53)` (or if you're using 0-based indexing, `a(52)`).

## Testcases

```
n     a(n)
1     7
2     8
3     21
4     25
5     46
6     97
7     129
8     161
9     196
10    221
...
13    277
...
50    30015
51    35000
52    39250
53    46111

```

## References

# Answer
# 05AB1E, ~~10~~ 9 bytes

Saved 1 byte thanks to *Adnan*.

```
µNL<nJNnå

```

Try it online!

**Explanation**

```
µ           # loop until counter equals the input
 NL         # push the range [1 ... iteration_no]
   <        # decrement each
    n       # square each
     J      # join to string
      Nnå   # is iteration_no in the string?
            # if true, increase counter

```
> 5 votes

# Answer
# JavaScript (ES6), ~~51~~ ~~49~~ 45 bytes

1-indexed.

```
f=(n,s=k='')=>n?f(n-!!s.match(++k*k),s+k*k):k

```

### Demo

```
f=(n,s=k='')=>n?f(n-!!s.match(++k*k),s+k*k):k

for(n = 1; n <= 20; n++) {
  console.log('a(' + n + ') = ' + f(n))
}
```

### Formatted and commented

```
f = (                         // f = recursive function taking:
  n,                          //   n = input
  s = k = ''                  //   s = string of concatenated squares, k = counter
) =>                          //
  n ?                         // if we haven't reached the n-th term yet:
    f(                        //   do a recursive call with:
      n - !!s.match(++k * k), //     n decremented if k² is an early bird square
      s + k * k               //     s updated
    )                         //   end of recursive call
  :                           // else:
    k                         //   return k

```

# Non-recursive version, 53 bytes

This one does not depend on your engine stack size.

```
n=>{for(k=s='';n-=!!(s+=k*k).match(++k*k););return k}

```

Try it online!
> 7 votes

# Answer
# Pyth, 12 bytes

```
e.f/jk^R2Z`*

```

**Try it here!**

## How it works

```
e.f/jk^R2Z`* ~ Full program. Let Q be our input.

 .f          ~ First Q positive integers with truthy results. Uses the variable Z.
      ^R2Z   ~ Square each integer in the range [0, Z).
    jk       ~ Concatenate into a single string.
   /         ~ Count the occurrences of...
          `* ~ The string representation of Z squared.
               Yields 0 if falsy and ≥ 1 if truthy.
e            ~ Get the last element (Qth truthy integer). Output implicitly.

```
> 6 votes

# Answer
# APL (Dyalog), ~~53~~ 42 bytes

```
{{0<+/(⍕×⍨⍵+1)⍷' '~⍨⍕×⍨⍳⍵:⍵+1⋄∇⍵+1}⍣⍵⊢0}

```

Try it online!

**How?**

\- find occurrences of

`⍕×⍨⍵+1` \- stringified square of `x+1` in the

`⍕×⍨⍳⍵` \- stringified range of squares `x`

`' '~⍨` \- without spaces

`+/` \- sum

`0<` \- if the sum is positive (occurrences exist), then it returns `x+1`, otherwise,

`∇⍵+1` \- recurse with `x+1`.

`⍣⍵` \- apply `n` times.
> 4 votes

# Answer
# Perl 5, 34 bytes

**33 bytes code + 1 for `-p`.**

```
$s.=$\*$\while$_-=$s=~(++$\*$\)}{

```

Try it online!
> 4 votes

# Answer
# Haskell, 73 bytes

```
import Data.List
([n|n<-[7..],isInfixOf(g n)$g=<<[1..n-1]]!!)
g=show.(^2)

```

Try it online! Zero-indexed.

**Explanation**

Auxiliaries:

```
import Data.List -- import needed for isInfixOf
g=show.(^2)      -- function short cut to square an int and get the string representation

```

Main function:

```
(                                 !!) -- Index into the infinite sequence
 [n|n<-[7..],                    ]    -- of all numbers n greater equal 7
      isInfixOf(g n)$                 -- whose square appears in the string
                     g=<<[1..n-1]     -- of all squares from 1 up to n-1 concatenated.

```
> 3 votes

# Answer
# Jelly, ~~13~~ 11 bytes

```
R²DµṪẇF
Ç#Ṫ

```

Try it online!

Alternatively this is a 10 bytes solution that prints `n` first values of the sequence: Try it online!
> 2 votes

# Answer
# Python 2, ~~62~~ 61 bytes

```
n=input();i=0;s=''
while n:i+=1;n-=`i*i`in s;s+=`i*i`
print i

```

Try it online!
> 2 votes

# Answer
# Jelly, 11 bytes

```
Ḷ²DFɓ²ẇ
Ç#Ṫ

```

Try it online!

An alternative to user202729's solution.

### How it works

```
C#Ṫ ~ Main Link.

Ç#  ~ First N positive integers with truthy results.
  Ṫ ~ Tail. Take the last one.

-----------------------------------------------------------

Ḷ²DFɓ²ẇ ~ Helper link. This is the filtering condition.

Ḷ       ~ Lowered range. Yields {x | x ∊ Z and x ∊ [0, N)}.
 ²      ~ Square each.
  D     ~ Convert each to decimal (this gets the list of digits).
   F    ~ Flatten.
    ɓ   ~ Starts a new monadic chain with swapped arguments.
     ²  ~ N²; Yields N squared.
      ẇ ~ Is ^ sublist of ^^^?

```
> 2 votes

# Answer
## Alice, 32 bytes

```
/
\io/&wd.*\@! d ? ~ ? F $ /WKdt

```

Try it online!

The wasteful layout of that stretch of Ordinal mode is really bugging me, but everything I try to save some bytes there comes out longer...

### Explanation

```
/
\io/...@...

```

Just the usual decimal I/O framework, with the `o` and `@` in slightly unusual positions. The meat of the program is this:

```
&w    Push the current IP address to the return address stack n times.
      This gives us an easy way to write a loop which repeats until we
      explicitly decrement the loop counter n times.

  d     Push the stack depth, which acts as our running iterator through
        the natural numbers.
  .*    Square it.
  \     Switch to Ordinal mode.
  !     Store the square (as a string) on the tape.
  d     Push the concatenation of the entire stack (i.e. of all squares before
        the current one).
  ?~    Retrieve a copy of the current square and put it underneath.
  ?     Retrieve another copy.
  F     Find. If the current square is a substring of the previous squares,
        this results in the current square. Otherwise, this gives an empty
        string.
  $     If the previous string was empty (not an early bird) skip the next
        command.
  /     Switch back to Cardinal. This is NOT a command.
  W     Discard one address from the return address stack, decrementing our
        main loop counter if we've encountered an early bird.
K     Jump back to the beginning of the loop if any copies of the return
      address are left. Otherwise do nothing and exit the loop.

dt    Push the stack depth and decrement it, to get the final result.

```
> 2 votes

# Answer
## Husk, 13 bytes

```
!f§€oṁ₁ŀ₁N
d□

```

Try it online!

### Explanation

The second line is a helper function which gives us the decimal digits of a number's square:

```
 □    Square.
d     Base-10 digits.

```

We can invoke this function on the main program using .

```
!f§€oṁ₁ŀ₁N
 f§      N    Filter the list of natural numbers by the following fork g(n).
       ŀ        Get [0, 1, ... n-1]
     ṁ₁         Get the decimal digits of each value's square and concatenate
                them into one list. (A)
        ₁       And get the decimal digits of n² itself. (B)
    €           Check whether (A) contains (B) as a sublist.
!             Use the programs input as an index into this filtered list.

```
> 1 votes

# Answer
# Kotlin, 79 bytes

```
{n->var m=n;var i=0;var s="";while(m>0){val k="${++i*i}";if(k in s)m--;s+=k};i}

```

Try it online!
> 1 votes

# Answer
# REXX, 66 bytes

```
arg n,a
k=0
do i=1 until k=n
  k=k+(pos(i*i,a)>0)
  a=a||i*i
  end
say i

```

Try it online!
> 1 votes

# Answer
# Wolfram Language (Mathematica), 75 bytes

```
(n=k=0;s="";While[n<#,If[!StringFreeQ[s,t=ToString[++k^2]],n++];s=s<>t];k)&

```

Try it online!

## How it works

`n` keeps the number of early birds found so far, `k` the last number checked, `s` the string `"1491625..."`. While `n` is too small, if `s` contains the next square, another early bird has been found, so we increment `n`. In any case, we extend `s`.

Once `n` reaches the input `#`, we return `k`, the last number checked and therefore the last early bird found.

On my laptop, takes about 53 seconds to compute the 53rd term of the sequence.
> 1 votes

# Answer
# Bash, ~~76~~ 69 bytes

Assume `n` is given into variable (i.e. `n=10 foo.sh`). Uses package `grep`. Any middle value is output (if allowed, -3 bytes).

```
while((n));do((b=++a*a));grep -q $b<<<$s&&((n--));s=$s$b;done;echo $a

```

How does it work?

```
while ((n)); do  # while n != 0 (C-style arithmetic)
  ((b = ++a*a))  # Increment a and let b = a*a
    # Non-existent value is treated as zero
  grep $b<<<$s   # Search for b in s
    && ((n--))   # If found, decrement n
  s=$s$b         # Append b to s
done
echo $a

```
> 1 votes

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


title: Prime sieve and sort (x86 asm)

text:
# Question
Title: Prime sieve and sort (x86 asm)
Your challenge is to write a routine, in x86 assembly, which takes a buffer containing 32-bit signed integers and writes a sorted list of the prime values to another buffer, then returns the number of values written to the output buffer. The winning solution is the one that uses the **least instructions**.

Here's a pseudo-C example of the process:

```
int __stdcall SortedPrimes(DWORD* input, DWORD* output)
{
    int ctr_in = 0;
    int ctr_out = 0;
    int val = 0;
    // copy primes to output buffer
    while((val = input[ctr_in]) != 0)
    {
        ctr_in++;
        if(isPrime(val))
            output[ctr_out++] = val;
    }
    // you must implement this sort, too!
    sort(output);
    return ctr_out;
}

// for testing/illustration purposes only
// you don't need to implement this part!
void test()
{
    int count = 0;
    int i = 0;
    int v = 0;

    // allocate buffers
    DWORD* input = (DWORD*)calloc(1024, sizeof(DWORD));
    DWORD* output = (DWORD*)calloc(1024, sizeof(DWORD));

    // fill input buffer with data
    input[0] = 0x12345678;
    input[1] = 0x57AC0F10;
    ...
    input[1022] = 0x13371337;
    input[1023] = 0; // terminating value is zero!

    // invoke your function! :]
    count = SortedPrimes(input, output);

    // dump output
    printf("Found %n primes.\n", count);
    while((v = output[i++]) != 0)
        printf("0x%x\n", v);

    free(input);
    free(output);
}

```

Rules:

* Assume a modern Intel CPU (e.g. Core i3) running in x86-32 mode.
* Assume `__stdcall`, i.e. parameters pushed from right to left, `esp+4` is a pointer to `input`, `esp+8` is a pointer to `output`, callee is responsible for cleaning stack.
* You cannot call any APIs or library functions - the solution must be in pure assembly.
* The input buffer consists of 32-bit non-zero signed integers, followed by `0x00000000`.
* The output buffer is allocated and zero'd before being passed to the function, and its size is the same as the input buffer.
* Assume there are no negative inputs, i.e. the range is `0x00000001` to `0x7FFFFFFF`.
* The sort must be lowest to highest, such that `output[0]` is the lowest value in the list.
* Must give an empty output buffer when given an empty input buffer.
* Must properly handle cases where all values are prime / no values are prime.
* You may not use compiler macros.
* The code must be able to process 1000 inputs in 60 seconds or less.
* I'll accept answers in AT&T syntax, but I'd prefer Intel syntax for uniformity.
* Winner is the code that has the **least number of instructions** (i.e. lowest number of lines of code), not the least number of characters.

Assembly is pretty terse, so please add comments to your code where necessary.

Enjoy :)

# Answer
## 26 instructions

I found this task for the first time only yesterday. sigh.

I took @Sir\_Lagsalot's code and removed one xchg. The changes are too significant for a comment, so I've placed it here for review.

```
    pushad
    mov     ecx, -1              ; will zero output count and position using next instruction
count_prime:
    inc     ecx                  ; increment output & count if prime
    mov     esi, [esp + 8+32]    ; load output array
find_smallest:
    mov     eax,-3               ; 0xfffffffd is larger than any valid input
    mov     edi, [esp + 4+32]    ; load input array
    db      3dh, 50h             ; mask next instruction on first pass
find_smallest_loop2:
    xchg    eax,[edi-4]          ; swap ecx with values that are smaller, values
                                 ; get replaced with 0xfffffffd as they are used
find_smallest_loop:
    scasd
    jbe     find_smallest_loop
    mov     ebx,1                ; ebx is divisor, will start it at 2 later
                                 ; but we need 1 right now
    cmp     [edi-4],ebx
    je      find_smallest        ; skip inputs of 1
    ja      find_smallest_loop2  ; exit loop if a 0 is reached
    mov     [esi+ecx*4],eax      ; store value in next output position
test_next_divisor:               ; primality test
    mov     eax,[esi+ecx*4]
    cdq
    inc     ebx                  ; 2+
    idiv    ebx                  ; use signed division
    cmp     eax,ebx
    jb      count_prime
    test    edx,edx
    jz      find_smallest
    jns     test_next_divisor    ; exit if remainder is negative
exit_function:
    mov     [esp+28],ecx         ; move count to eax position
    popad
    ret 8
```
> 3 votes

# Answer
# 32 30 29 28 27 Instructions

Changed my algorithm so we're not all trying to implement the same thing, and it's a little smaller than my earlier attempt. The code repeatedly searches through the input array, finding the smallest value, and replacing it with 0xfffffffd. It then tests if the found value is prime and outputs it if so. The code exits when the input has been completely replaced with 0xfffffffd.

```
    pushad
    mov     ecx, 0              ; zero output count and position
    mov     esi, [esp + 8+32]   ; load output array
find_smallest:
    mov     eax,-3              ; 0xfffffffd is larger than any valid input
    mov     edi, [esp + 4+32]   ; load input array
find_smallest_loop:
    scasd
    jbe     find_smallest_loop
    xchg    eax,[edi-4]          ; swap ecx with values that are smaller, values
                                 ; get replaced with 0xfffffffd as they are used
    cmp     eax,1
    je      find_smallest        ; skip inputs of 1
    ja      find_smallest_loop   ; exit loop if a 0 is reached
    xchg    eax,[edi-4]          ; swap 0 with lowest value found
    mov     [esi+ecx*4],eax      ; store value in next output position
    mov     ebx,2                ; ebx is divisor, start it at 2
test_next_divisor:               ; primality test
    mov     eax,[esi+ecx*4]
    cdq
    idiv    ebx                  ; use signed division
    cmp     eax,ebx
    cmovb   edx,[edi-4]          ; zero edx if prime to exit loop later on
    adc     ecx,0                ; increment output & count if prime
    inc     ebx
    test    edx,edx
    jz      find_smallest
    jns     test_next_divisor    ; exit if remainder is negative
exit_function:
    mov     [esp+28],ecx         ; move count to eax position
    popad
    ret 8

```
> 5 votes

# Answer
## ~~41~~ 29 instructions

The code itself, NASM syntax:

```
global primes
    section .code
primes:
    pushad
    mov     esi, [esp + 32 + 4]
    mov     dword [esp + 28], 0 ; primes counter
read:
    add     esi, 4
    mov     ecx, [esi - 4]
    jecxz   return          ; zero terminator
    cmp     ecx, 1
    je      read            ; omit 1
    mov     ebx, 2          ; initial divisor
try_divisor:
    mov     eax, ecx        ; get original number from ecx
    mov     edx, 0
    div     ebx             ; divide
    cmp     ebx, eax
    jg      save            ; divisor exceeds sqrt(n), so n is prime
    cmp     edx, 0
    je      read            ; not prime
    inc     ebx             ; next divisor
    jmp     try_divisor
save:                        ; prime number to store is in ecx
    inc     dword [esp + 28] ; increase prime counter
    mov     edi, [esp + 32 + 8]
bubble:                     ; insert prime into output array
    add     edi, 4
    xchg    ecx, [edi - 4]
    jecxz   read
    cmp     ecx, [edi - 4]
    jge     bubble
    xchg    ecx, [edi - 4]
    jmp     bubble
return:
    popad
    ret     8

```

I borrowed a lot from Keith Randall's solution, but improved prime saving code. So, I guess, my code should be out of competition since it's not completely mine.
> 3 votes

# Answer
## 35 31 instructions

```
        .globl  _primesort
_primesort:
        pushal
        mov     36(%esp),%esi           # load input ptr
        mov     40(%esp),%edi           # load output ptr
        movl    $0,28(%esp)             # count primes in saved eax slot
inputloop:
        add     $4,%esi
        cmp     $1,-4(%esi)
        jl      return                  # 0 = input end marker
        je      inputloop               # special case for 1
        mov     $2,%ecx                 # trial divisor
testloop:
        mov     -4(%esi),%eax
        mov     $0,%edx
        div     %ecx
        cmp     %ecx,%eax
        jl      saveprime               # n/d < d => d > sqrt(n) => no more trial division
        cmp     $0,%edx
        je      inputloop               # found a divisor
        inc     %ecx                    # next trial divisor
        jmp     testloop
saveprime:
        mov     -4(%esi),%eax           # prime
        mov     28(%esp),%ecx           # index of new last element
        jecxz   storeprime              # at start of output array, just store it
bubbledown:
        cmp     %eax,-4(%edi,%ecx,4)
        jl      storeprime              # found spot to store it
        mov     -4(%edi,%ecx,4),%edx
        mov     %edx,(%edi,%ecx,4)      # move larger element up one
        loop    bubbledown              # repeat until start of output array
storeprime:
        mov     %eax,(%edi,%ecx,4)
        incl    28(%esp)
        jmp     inputloop
return:
        popal
        ret

```

This code is AT&T syntax, and it uses `cdecl` instead of `stdcall`, but I think the only difference for the latter would be to replace the `ret` with `ret 0x8`.
> 2 votes

# Answer
## 28 instructions

Build with `nasm -f elf32`:

```
BITS 32
GLOBAL sortedprimes

;; int sortedprimes(int const *input, int *output)
;; Read a zero-terminated list of numbers from input. Copy only the prime
;; numbers to the buffer output, returning the count of numbers so
;; copied. The numbers in output are returned in sorted order.

sortedprimes:

;; Within this function:
;; eax = the number currently being tested for primality;
;; ecx = the potential divisor being tested;
;; esi = the pointer to the next number to test for primality;
;; edi = a pointer into the output buffer; and
;; (eax on the stack) = how many numbers are in the output buffer.

;; Initialize the return value to zero, and point esi at the input buffer.

                xor     eax, eax
                pusha
                mov     esi, [byte esp + 36]

;; Retrieve the next number to be tested. If the number is one, it is
;; skipped. If the number is zero, the program has reached the end of
;; the buffer and exits. Otherwise the program starts testing
;; potential divisors, starting with 2.

.nextnumber:    lodsd
                mov     ecx, 2
                cmp     eax, byte 1
                jz      .nextnumber
                jns     .divloop
                popa
                ret     8

;; Divide the number by a candidate divisor. If the quotient is less
;; than the candidate, the list of; potential divisors has been
;; exhausted, and the program jumps forward. If the remainder is
;; zero, however, then the number is composite, and it is discarded
;; and the program jumps back to get the next number. If neither is
;; true, then ecx is incremented and the next candidate is tested.

.divloop:       xor     edx, edx
                div     ecx
                cmp     eax, ecx
                mov     eax, [byte esi - 4]
                jl      .prime
                inc     ecx
                or      edx, edx
                jnz     .divloop
                jmp     short .nextnumber

;; eax contains a prime. The count of primes is incremented, and eax
;; is temporarily placed into the output buffer at the initial position,
;; displacing whatever number was already there. This number is then
;; restored, edi is advanced and eax displaces the number at at the
;; next position. Thus continues until (a) a number higher than eax
;; is reached, in which case it is left there and the displaced
;; number is left in eax, to become the displacing number going
;; forward, or (b) the end of the list is reached, in which case the
;; last number displaced is just zero-padding, and it is discarded as
;; the program jumps back to test the next input number.

.prime:         inc     dword [byte esp + 28]
                mov     edi, [byte esp + 40]
.insertloop:    xchg    eax, [edi]
                or      eax, eax
                jz      .nextnumber
                scasd
                jg      .insertloop
                xchg    eax, [byte edi - 4]
                jmp     short .insertloop

```

@Sir\_Lagsalot is right that all of our solutions are starting to look the same. I was actually a bit dismayed when I finally read Alexander Bakulin's solution at how closely it resembled my own. I guess that's a side effect of targeting the challenge to a single language/platform.
> 2 votes

---
Tags: code-golf, assembly
---


title: A bank for less Trustworthy Friends

text:
# Question
Title: A bank for less Trustworthy Friends
## Introduction

You have gotten a job as the minister of finance in your made-up country in your back yard. You have decided to make your own bank in your country for you and your less trustworthy friends. Since you don't trust your friends, you have decided to write a program to validate all transactions to stop your friends from overspending your made-up currency and ruining your economy.

## Task

Given the starting balance and all transactions, filter out all transactions where someone tries to overspend and block anyone who tries to overspend (this includes trying to overspend to a closed account) from ever using your bank again by filtering out future transactions to or from his/her bank account.

## Input/Output

Two lists `A` and `B` as input and a list `C` as output. `A` is the starting balance of each account with the format `[["Alice", 5], ["Bob", 8], ["Charlie", 2], ...]`. `B` is a list of transactions with the format `[["Bob", "Alice", 3], ["Charlie", "Bob", 5], ...]` where `["Bob", "Alice", 3]` means that Bob wants to pay Alice 3 currency units. `C` should have the same format as `B`. `A`, `B` and `C` may be in any reasonable format.

## Test Cases

```
A: [["Alice", 5], ["Bob", 2]]
B: [["Alice", "Bob", 5], ["Bob", "Alice" 7]]
C: [["Alice", "Bob", 5], ["Bob", "Alice" 7]]

A: [["A", 2], ["B", 3], ["C", 5]]
B: [["C", "A", 2], ["B", "C", 4], ["A", "B", 2]]
C: [["C", "A", 2]]

A: [["A", 2], ["B", 3]]
B: [["A", "B", 2], ["A", "B", 2]]
C: [["A", "B", 2]]

A: [["A", 4], ["B", 0]]
B: [["A", "B", 1], ["A", "B", 5], ["A", "B", 2]]
C: [["A", "B", 1]]

A: [["A", 2], ["B", 3], ["C", 4]]
B: [["A", "B", 3], ["C", "B", 4]]
C: [["C", "B", 4]]

A: [["A", 2], ["B", 3], ["C", 4]]
B: [["A", "B", 3], ["B", "A", 4], ["C", "B" 2]]
C: []

```

## Scoring

This is , the shortest code in bytes in each language wins.

# Answer
# JavaScript (ES6), ~~91~~ ~~88~~ 79 bytes

*Saved 8 bytes thanks to @NahuelFouilleul*

Takes input in currying syntax `(a)(b)`.

```
a=>b=>b.filter(([x,y,z])=>(a[x]+=z)<0&a[y]<0?a[y]-=z:0,a.map(([x,y])=>a[x]=~y))

```

### Test cases

```
let f =

a=>b=>b.filter(([x,y,z])=>(a[x]+=z)<0&a[y]<0?a[y]-=z:0,a.map(([x,y])=>a[x]=~y))

console.log(JSON.stringify(f(
  [["Alice", 5], ["Bob", 2]]
)(
  [["Alice", "Bob", 5], ["Bob", "Alice", 7]]
)))

console.log(JSON.stringify(f(
  [["A", 2], ["B", 3], ["C", 5]]
)(
  [["C", "A", 2], ["B", "C", 4], ["A", "B", 2]]
)))

console.log(JSON.stringify(f(
  [["A", 2], ["B", 3]]
)(
  [["A", "B", 2], ["A", "B", 2]]
)))

console.log(JSON.stringify(f(
  [["A", 4], ["B", 0]]
)(
  [["A", "B", 1], ["A", "B", 5], ["A", "B", 2]]
)))

console.log(JSON.stringify(f(
  [["A", 2], ["B", 3], ["C", 4]]
)(
  [["A", "B", 3], ["C", "B", 4]]
)))
```

### Beautified and commented

```
a => b =>                 // given the two lists a and b
  b.filter(([x, y, z]) => // for each (x = payer, y = payee, z = amount) in b:
    (a[x] += z) < 0 &     //   update the payer's account; if it's still valid
    a[y] < 0 ?            //   and the payee's account is also valid:
      a[y] -= z           //     update the payee's account
    :                     //   else:
      0,                  //     do nothing
    a.map(([x, y]) =>     //   initialization: for each (x = owner, y = amount) in a:
      a[x] = ~y           //     set up this account (>= 0: closed, -1: $0, -2: $1, etc.)
    )                     //   end of map()
  )                       // end of filter()

```
> 5 votes

# Answer
# Perl 5, 72 + 2 (-ap) = 74 bytes

```
%h=@F;$_=<>;s/(\S+) (\S+) (\S+)/($h{$1}-=$3)<0||($h{$2}+=$3)<$3?"":$&/ge

```

try it online
> 4 votes

# Answer
# Python 2, 103 bytes

```
A,B=input()
C=[]
for i in B:
 N,P,M=i
 if M>A[N]:A[N]=-1
 if A[N]>-1<A[P]:A[N]-=M;A[P]+=M;C+=i,
print C

```

Try it online!

-12 thanks to ovs.

Longer due to output format restrictions:

> `C` should have the same format as `B`.

Otherwise I could've done this for 92 bytes:

```
A,B=input()
for(N,P,M)in B:
 if M>A[N]:A[N]=-1
 if A[N]>-1<A[P]:A[N]-=M;A[P]+=M;print(N,P,M)

```
> 2 votes

# Answer
# Ruby, 57 bytes

```
->a,b{b.select{|(s,r,x)|a[r]+=x if[a[s]-=x,a[r]].min>-1}}

```

Try it online!

Takes input `A` as a `Hash` in the format `{"A"=>2, "B"=>3}`. Input `B` and output `C` are in the suggested format.

## Explanation

```
->a,b{                      # lambda function taking arguments A and B
b.select{|(s,r,x)|              # select items in B that return truthy (s = sender, r = receiver, x = amount)
            a[s]-=x,                # subtract amount from sender
        if [         a[r]].min>-1   # check if the smaller of the balances is non-negative
                                    # (true if both values are non-negative)
a[r]+=x                             # if so, add to the receiver's balance
}                               # the select function returns truthy when the above if statement passes
}

```
> 2 votes

# Answer
# C++, 193 bytes

Input A as `std::map`, B as `std::list`.

```
#import<bits/stdc++.h>
using s=std::string;struct p{s a,b;int c;};using t=std::list<p>;t f(std::map<s,int>A,t B){t C;for(p&i:B)(A[i.a]-=i.c)<0|A[i.b]<0?0:(C.push_back(i),A[i.b]+=i.c);return C;}

```

Try it online!
> 1 votes

---
Tags: code-golf
---


title: The Shield Wall

text:
# Question
Title: The Shield Wall
### Historical Background

The shield wall is a tactical war formation that dates back to *at least* 2500 BC. It consisted of warriors overlapping their shields with those of their companions to form a 'wall'. The appeal of the tactic comes from the fact that even the most unskilled warrior could fight in a wall as long as they had a shield and a weapon. Because of the proximity of the walls, there was little space to move around, and the battle usually became a shoving match fought with sharp weapons.

## The Challenge

Your task is to create a program or function that, given two arrays/lists/vectors of warriors as input, decides the outcome of the battle. The lists will represent a single-line wall of shields, and they will follow a specific notation:

### Vikings:

The nordic warriors had a fierce drive for battle. During the late 8th through the mid 11th centuries, Danish vikings invaded the kingdoms of Britain looking for riches and farmable land. For the purpose of this challenge, these are the vikings' warriors:

* The `J`arl: Usually found leading his men from the center of the wall, jarls were the leaders of the viking hordes. Takes 15 damage to die, and deals 2 damage per round.
* The `B`erserker: Although fantasy has greatly twisted the image of the berserkers, these warriors were known to fight in a trance-like fury without any kind of protection other than their shields. Takes 6 damage to die, and deals 3 damage per round.
* The `C`hieftain: Chieftains were rich men who had free men at their service. They'd usually have earned great glory and riches in battle. Takes 10 damage to die, and deals 2 damage per round.
* The Free `M`en: Warriors that served a chieftain. They were sworn to fight for their lords until death. Takes 8 damage to die, and deals 1 damage per round.
* The `S`kald: Skalds, usually translated as bards, were free men who were hired to write poems, stories or songs about the great deeds of the nordic warriors. Takes 8 damage to die, and gives each adjacent warrior 1 bonus damage. Skalds deal **no** damage. Warriors **cannot** gain more than 1 bonus damage this way.

### Saxons:

The Saxons came to settle in Britain from continental Europe following the demise of the Roman Empire in the 5th century. For the purposes of this challenge, there are the saxons' warriors:

* The `E`arl: *Ealdormen*, commonly called Earls, were members of the higher nobility. They usually held great streches of land and had hundreds or even thousands of sworn men. Takes 20 damage to die, and deals 1 damage per round.
* The `K`night: For lack of a better term, the *knights* were minor noblemen who owned some land. In most cases, knights were sworn servants to an Earl. Takes 10 damage to die, and deals 2 damage per round.
* The `W`arrior: Common men, usually minor noblemen without land or peasants who served a knight. When adjacent to a Knight or Earl, warriors have a +1 damage bonus. Takes 8 damage to die, and deals 2 damage per round.
* The `F`yrd: The Fyrd was a militia-like group of free men, usually poor farmers, who'd bring any weapon (or weapon-like farming implement) they had to fight in the wall. Takes 5 damage to die, and deals 1 damage per round.
* The `P`riest: Priests were highly valued in early Saxon culture, being heralds of the words of God. Priests take 15 damage to die, and prevent up to 1 damage each adjacent warrior would be dealt. Priests deal **no** damage. Priests **cannot** prevent more than 1 damage to a warrior.

### The Wall

Walls meet each other at their centers. Each round, each warrior assigns damage to the warrior directly in front of it or, if there's no living warrior in front of it, the diagonally adjacent living warrior with least health remaining. If there is a tie, choose the warrior closer to the edge of the wall.

Example:

```
Vikings
[M,M,M,B,B,C,J,C,B,B,M,M,M]
[F,F,F,W,W,K,E,K,W,W,F,F,F]
Saxons

To make matters easier, let's convert these walls into numbers:
Round 0:
 M M M B B C  J  C  B B M M M
[8,8,8,6,6,10,15,10,6,6,8,8,8]
[5,5,5,8,8,10,20,10,8,8,5,5,5]
 F F F W W K  E  K  W W F F F

Round 1: Notice that 2 of the Saxons' warriors are adjacent to Knights, so they have a +1 damage bonus.
 M M M B B C J  C B B M M M
[7,7,7,4,3,8,14,8,3,4,7,7,7]
 | | | | | | || | | | | | |
[4,4,4,5,5,8,18,8,5,5,4,4,4]
 F F F W W K E  K W W F F F

Round 2:
 M M M B B C J  C B B M M M
[6,6,6,2,0,6,13,6,0,2,6,6,6]
 | | | | | | || | | | | | |
[3,3,3,2,2,6,16,6,2,2,3,3,3]
 F F F W W K E  K W W F F F

Round 3: Remember to collapse the arrays to account for dead warriors. Also, notice that the 2 outermost Fyrd are now attacking the diagonally adjacent viking.
   M M M B C J  C B M M M
  [4,5,4,0,4,12,4,0,4,5,4]
  /| | | | | || | | | | |\
[2,2,2,1,0,4,14,4,0,1,2,2,2]
 F F F W W K E  K W W F F F

Round 4: Notice once again the saxon Warriors next to the Knights dealing 3 damage:
   M M M C J  C M M M
  [2,4,1,2,11,2,1,4,2]
  /| | | | || | | | |\
[2,1,1,0,2,12,2,0,1,1,2]
 F F F W K E  K W F F F
Round 5:
 M M M C J  C M M M
[1,3,0,0,10,0,0,3,1]
 | | | | || | | | |
[1,0,0,0,10,0,0,0,1]
 F F F K E  K F F F

Round 6:
    M M J M M
   [1,2,9,2,1]
     \| | |/
     [0,8,0]
      F E F
Rounds 7 and 8:
      M M J M M         M M J M M
     [1,2,8,2,1]       [1,2,8,2,1]
         \|/               \|/
         [4]               [0]
          E                 E

Output: Viking victory.

```

### Rules:

* Default Loopholes apply.
* You can use any convenient IO method.
* This is , so shortest code (in bytes, per language) wins.
* You **may not** assume the lists will have the same length, but they will **always** be alignable at their centers (there will always be an odd number of warriors in each list if the lists are of different sizes).
* You may output any truthy/falsey value. *Please specify in your answer* the equivalents of "Viking/Saxon victory".
* The loser is determined when all the warriors of a wall are dead.
* If you ever end up with walls that are not alignable during the code execution, align them as centrally as possible, leaving one extra warrior on the longer wall to the right side. E.g.:

```
  [M,M,M,J,M,M,M]
    [K,E,K,W];

      [B,B,B,J]
[K,K,W,W,K,E,K,W,W,K,K]

```
* Feel free to try and test your code with any setup of walls, not just the ones in the test cases.

### Test Cases:

```
V: [M,M,B,C,B,C,J,C,B,C,B,M,M]
S: [F,F,W,K,W,K,E,K,W,K,W,F,F]
O: Viking victory.
------------------------------
V: [M,M,M,M,M,M,M,M,M,M]
S: [W,W,W,W,W,W,W,W,W,W]
O: Saxon victory.
------------------------------
V: [B,C,M,B,C,M,M,C,B,M,C,B,M]
S:   [W,F,W,F,E,E,E,F,W,F,W]
O: Viking victory.
------------------------------
V:         [B,B,B,J,B,B,B]
S: [W,W,W,W,K,K,K,E,K,K,K,W,W,W,W]
O: Saxon victory.
------------------------------
V: [J]
S: [E]
O: Viking victory.
------------------------------
V: [C,C,C,C,B,B,M,M,M,M,J,J,J,M,M,M,M,B,B,C,C,C,C]
S: [K,K,K,K,K,K,K,K,K,K,W,E,W,K,K,K,K,K,K,K,K,K,K]
O: Saxon victory.
------------------------------
V: [M,M,S,C,B,J,B,C,S,M,M]
S: [F,K,P,W,K,E,K,W,P,K,F]
O: Saxon victory.
------------------------------
V: [S,S,S,...,S]
S: [P,P,P,...,P]
O: UNDEFINED (since both priests and skalds deal no damage, you can output anything here.)
------------------------------

```

There are some historical inaccuracies. Feel free to point them out and I'll do my best to fix them.

# Answer
# Python 2, ~~576~~ ~~573~~ ~~565~~ ~~554~~ ~~540~~ 549 bytes

```
O=[(0,0)]
g=lambda D,W,i:D[i-1]*(W[i-1]<1)+D[i]+D[i+1]*(W[i+1]<1)
h=lambda*V:[v for v in zip(*V)if v[1]>0]
def f(v,s):
 l,L=len(v),len(s);m=max(l,L);a,b=(L-l)/2,(l-L)/2;V,U=zip(*O+O*a+v+O*a+O+O);S,T=zip(*O+O*b+s+O*b+O+O);z=[0]*(m+2);w=z[:];r=range(1,m+1);U=list(U);T=list(T)
 for i in r:w[i]=[0,2,3,2,1,0][V[i]]+(5in V[i-1:i+2:2])*(V[i]<5);z[i]=[0,1,2,2+({1,2}&set(S[i-1:i+2:2])>set()),1,0][S[i]]
 for i in r:U[i]-=g(z,V,i);d=g(w,S,i);T[i]-=d-(d>0)*(5in S[i-1:i+2:2])
 V=h(V,U);S=h(S,T)
 if([],[])<(V,S)!=(v,s):return(f(V,S)if S else'V')if V else'S'

```

Try it online!
> 3 votes

# Answer
# APL (Dyalog Classic), 128 bytes

```
{t l d b p←(-⌊2÷⍨+/0=⊃⍵)∘⌽¨⍵⋄l+←e+3+/0,0,⍨(0=t)×e←(×≢¨p∩¨h)-⊖d+×≢¨b∩¨h←3,/0,t,0⋄⍵≡a←↑¨(⊂↓l>0)/¨¨↓¨t l d b p:0⋄0∊s←+/l>0:×-/s⋄∇a}

```

Try it online!

There are two functions in the TIO link: `g` is the golfed function above and `f` is an ungolfed function that accepts a pair of strings, converts them to a suitable representation and calls the golfed function.

The input is five matrices: `t` warrior types as ints; `l` life; `d` damage; `b` what warrior types give bonus when adjacent; `p` same for protection. The matrices consist of two rows - Vikings and Saxons. If their warriors are not the same number, the matrices must be 0-padded, though not necessarily centred. The result is `1`/`¯1` for Viking/Saxon victory or `0` for a draw.

```
{
  t l d b p←(-⌊2÷⍨+/0=⊃⍵)∘⌽¨⍵ ⍝ centre the matrices
  ⍝ (-⌊2÷⍨+/0=⊃⍵) is a pair of numbers - by how much we should rotate (⌽) the rows
  ⍝       +/0=⊃⍵  how many dead? (⊃⍵ is the types, dead warriors have type 0)
  ⍝  -⌊2÷⍨        negated floor of half

  l+←e+3+/0,0,⍨(0=t)×e←(×≢¨p∩¨h)-⊖d+×≢¨b∩¨h←3,/0,t,0 ⍝ compute and apply effective damage
  ⍝ h←3,/0,t,0  are triples of types - self and the two neighbours
  ⍝ b∩¨h        for each warrior intersect (∩) h with his bonus-giving set b
  ⍝ ×≢¨         non-empty? 0 or 1
  ⍝ d+          add to the damage normally inflicted
  ⍝ ⊖           reverse vertically (harm the enemy, not self)
  ⍝ (×≢¨p∩¨h)   same technique for protections (neighbouring priests)
  ⍝ e←          remember as "e" for "effective damage"; we still need to do the diagonal attacks
  ⍝ (0=t)×      zero out the attacks on living warriors
  ⍝ 3+/0,0,⍨    sum triples - each warrior suffers the damage intended for his dead neigbours
  ⍝ e+          add that to the effective damage
  ⍝ l+←         decrease life ("e" is actually negative)

  ⍵≡a←↑¨(⊂↓l>0)/¨¨↓¨t l d b p:0 ⍝ remove dead; if no data changed, it's a draw
  ⍝ ↓¨          split each matrix into two row-vectors
  ⍝ (⊂↓l>0)     boolean mask of warrios with any life left, split in two and enclosed
  ⍝ /¨¨         keep only the survivors
  ⍝ ↑¨          mix the pairs of rows into matrices again, implicitly padding with 0-s
  ⍝ a←          call that "a" - our new arguments
  ⍝ ⍵≡a ... :0  is "a" the same as our original arguments? - nothing's changed, it's a draw

  0∊s←+/l>0:×-/s ⍝ if one team has no members left, they lost
  ⍝ l>0         bitmask of survivors
  ⍝ s←+/l>0     how many in each camp
  ⍝ 0∊          has any of the two armies been annihilated?
  ⍝ :×-/s       if yes, which one? return sign of the difference: ¯1 or 1, or maybe 0

  ∇a ⍝ repeat
}

```
> 2 votes

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


title: Build this pyramid

text:
# Question
Title: Build this pyramid
# Your pyramid

The pyramid I want you to build is made entirely of cubes. It has 24 layers, and the Nth layer from the top contains N2 cubes arranged in an N by N square. The pyramid looks like this:

To build the pyramid, you will need a supply of cubes. You are given 4900 cubes arranged in a 70 by 70 square that looks like this:

(Okay, I admit that the picture of the square is entirely unnecessary.)

Since 12 \+ 22 \+ 32 \+ ... + 242 = 702, you have exactly the right number of cubes to build the pyramid. All you have to do is tell me where each cube should go.

# Your task

You should pick an arbitrary bijection between the cubes in the square and the cubes in the pyramid. (It would be nice if your answer said which of the 4900! different bijections you're using.)

Then, write a function or program that does the following:

* Given the location of a cube in the 70 by 70 square (as a pair of coordinates `(X,Y)`),
* Output its location in the pyramid (as a triple of coordinates `(A,B,C)`).

The input and output coordinates can all be either 0-indexed or 1-indexed. Assuming 1-indexed, your input `(X,Y)` will be a pair of integers between 1 and 70. Your output `(A,B,C)` will be a triple of integers; `A` should be the layer counting from the top (between 1 and 24) and `(B,C)` should be the coordinates of that cube within that layer (between 1 and `A`).

For example:

* the top cube of the pyramid has coordinates `(1,1,1)`.
* The four corners of the base of the pyramid have coordinates `(24,1,1)`, `(24,1,24)`, `(24,24,1)`, and `(24,24,24)`.
* If you decide to place the corners of the square at the corners of the pyramid, then on input `(70,1)` you might give the output `(24,24,1)`.

You may assume you will only be given valid coordinates `(X,Y)` as input. Correctness is entirely determined by the following rule: two different valid inputs should always give two different valid onputs.

This is : the shortest code wins.

# Answer
> 7 votes
# Jelly, ~~15~~ 14 bytes

```
24p;€$€Ẏ
ḅ70ị¢

```

Try it online!

This is fairly simple: we construct the list of coordinates of cubes within the pyramid as an actual list. Then all we need to do is biject the input coordinates within the square into an index within the list, which is trivial to do via base conversion.

This submission works either as a full program (taking the coordinates as `[x, y]` via the first command line argument and outputting on standard output), or as a function, implicitly named `2Ŀ`.

## Explanation

### Constructing the list

We start with the number `24`, which is interpreted as a range from 1 to 24 inclusive (because we're trying to use it as though it were a list). Then we iterate over it; that's what the last  in the program does. For each element *n* of the list:

* We construct the list of pairs *x*, *y* where each element comes from 1..*n*; `p` constructs a list of pairs given two sets of elements, and because only one value is available here (*n*), it's implicitly used for both sets, which both therefore become a list from 1..*n*.
* We append *n* (again, the only value we have available) to each element of the list (`;€`).
* In order to make the second  apply both of these operations to each *n* (i.e. to create a loop containing two instructions), we use `$` to group the two instructions into one.

Finally, we use  to flatten the list by one stage, in order to get a list that simply contains all the coordinates in order. It starts like this:

> \[1, 1, 1\], \[1, 1, 2\], \[1, 2, 2\], \[2, 1, 2\], \[2, 2, 2\], \[1, 1, 3\], \[1, 2, 3\], \[1, 3, 3\], \[2, 1, 3\], \[2, 2, 3\], \[2, 3, 3\], \[3, 1, 3\], \[3, 2, 3\], \[3, 3, 3\], \[1, 1, 4\], \[1, 2, 4\], \[1, 3, 4\], \[1, 4, 4\], \[2, 1, 4\], \[2, 2, 4\], \[2, 3, 4\], \[2, 4, 4\], \[3, 1, 4\], \[3, 2, 4\], \[3, 3, 4\], \[3, 4, 4\], \[4, 1, 4\], \[4, 2, 4\], \[4, 3, 4\], \[4, 4, 4\], …

and ends with \[24, 24, 24\].

### Indexing the list

We start by converting the input coordinates to a number by interpreting them as a base 70 integer: ḅ70. This gives us a value in the range 71 to 4970 inclusive; all these values are unique mod 4900.  indexes into the list modulo the length of the list, so `[1, 1]` will give us the 71st element, `[1, 2]` the 72nd element, all the way up to `[70, 70]` which gives us the 70th element (i.e. the element before the answer for `[1, 1]`). Finally, we just need a `¢` to tell us which list to index (in this case, it's the list specified by the previous line; that's what `¢` does, run the previous line with no arguments).

# Answer
> 6 votes
# PHP, ~~75 82~~ 78 bytes

**0-indexed**:

set P=X\*70+Y then reduce P by A2 while walking down to the correct layer. A-1; P/A; P%A - done.

(reversed: while incrementing A to the correct layer: P=P+A2 then P=P+A\*B+C --\> X=P/70, Y=P%70)

```
for($p=$argv[1]*70+$argv[2];$p>=++$a**2;$p-=$a**2);echo$a-1,_,$p/$a|0,_,$p%$a;

```

Run with `php -nr '<code>' <X> <Y>`; prints A\_B\_C.

**1-indexed, 82 bytes**:

```
for($p=$argv[1]*70+$argv[2]-71;$p>++$a**2;$p-=$a**2);echo$a,_,$p/$a+1|0,_,$p%$a+1;

```

# Answer
> 4 votes
# Python, ~~80~~ ~~73~~ 72 bytes

First submission, don't be too harsh q:

0-indexed

```
lambda x,y:[(a-1,b//a,b%a)for a in range(25)for b in range(a*a)][70*x+y]

```

Creates a list of length 4900 with all pyramind coordinates and returns a different list entry for each input.

Try it online!

# Answer
> 3 votes
# C ~~89~~ , ~~87~~ , ~~82~~ , 71 bytes

Took xnor's Python solution, and removed the linebreak

```
p(x,y){for(x=-70*y-x,y=1;x<0;x+=++y*y);printf("%d %d %d",~-y,x/y,x%y);}

```

0-indexed

```
z;p(x,y){for(x+=y*70+1,y=z=0;z<x;z+=++y*y);z-=x;printf("%d %d %d\n",y-1,z/y,z%y);}

```

1-indexed

```
z;p(x,y){for(x+=~-y*70,y=z=1;z<x;z+=++y*y);z-=x-y;printf("%d %d %d\n",y,z/y,z%y+1);}

```

# Answer
> 3 votes
# Python 2, 64 bytes

```
x,y=input()
n=-70*x-y
i=1
while n<0:i+=1;n+=i*i
print~-i,n/i,n%i

```

Try it online!

# Answer
> 2 votes
## Batch, 103 bytes

```
@set/an=%1*70+%2,i=0
:l
@set/an-=i*i,j=i,i+=1,k=n%%i,l=n/i
@if %l% geq %i% goto l
@echo %j% %k% %l%

```

0-indexed. Works through each layer starting from the top.

# Answer
> 2 votes
# J, 37 bytes

*-4 bytes thanks to FrownyFrog*

```
(a:-.~,(<:,&.>{@;~&i.)"0 i.25){~70&#.

```

Fairly straightforward translation of the Jelly method into J. Uses 0 indexing. The top pyramid square is the first. The bottom right corner of the base is the last.

The majority of the code is boilerplate to produce the triple indexed list as a constant. Finding the correct element within that list based on the 2 element input is simply a matter of translating from base 70 with `70&#.`

Try it online!

# Answer
> 1 votes
# Husk, 13 bytes

```
!foEG▲π3Π4B70

```

Try it online! Indices start from 1.

## Explanation

Like some other answers, I construct the full list of pyramid coordinates and simply index into it. I do this by listing all triples `[A,B,C]` where the numbers are between 1 and 24 (expressed as 4! to save a byte) and keeping those for which `A >= max(B,C)`.

```
!foEG▲π3Π4B70  Implicit input: a list of two numbers.
          B70  Interpret in base 70.
!              Modular index into the following list:
        Π4      Factorial of 4: 24
      π3        Take range and 3-fold Cartesian power: [[1,1,1],[1,1,2],..,[24,24,24]]
 f              Filter by
  oE            all values are equal
    G▲          in cumulative reduce by maximum.

```

---
Tags: code-golf, permutations
---


title: Write a self-replicating program.

text:
# Question
Title: Write a self-replicating program.
Write a simple program that copies itself when executed.

Your program should be some kind of executable file on Windows, Linux, etc.., should generate new executable file, which is identical to your original executable file, with random name, and quits.

Your program **shouldn't** involve any kind of file reading or copying. Only file writing for generating new executable file is permitted.

(PS. I was quite embarrassed when at Wikipedia, `Self-replicating program` redirects to `Computer virus` article... :/...)

Smallest executable file size wins. Your answer may be a programming code with proper OS & compiler, assembly code, or HEX dump of a executable file.

# Answer
## Bash, 236

Longer than strictly necessary, but I hate long lines. The trailing newline is non-optional.

```
b=\\ q=\' r=\> d=\$
s='exec >$$; echo b=$b$b q=$b$q r=$b$r d=$b$d; echo s=$q$s$q'
t='echo t=$q$t$q; echo $s; echo $t; chmod 777 $$'
exec >$$; echo b=$b$b q=$b$q r=$b$r d=$b$d; echo s=$q$s$q
echo t=$q$t$q; echo $s; echo $t; chmod 777 $$

```
> 4 votes

# Answer
## Assembly for x86 Linux, 106 bytes

```
BITS 32
                org     0x2E620000
                db      0x7F, "ELF", 1, 1, 1, 0 ; e_ident
                dd      0, 0
                dw      2                       ; e_type
                dw      3                       ; e_machine
                dd      1                       ; e_version
                dd      _start                  ; e_entry
                dd      phdr - $$               ; e_phoff
                dd      0                       ; e_shoff
                dd      0                       ; e_flags
                dw      0x34                    ; e_ehsize
                dw      0x20                    ; e_phentsize
phdr:           dd      1                       ; e_phnum       ; p_type
                                                ; e_shentsize
                dd      0                       ; e_shnum       ; p_offset
                                                ; e_shstrndx
                dd      $$                                      ; p_vaddr
fname           equ     $ - 2
                db      'out', 0                                ; p_paddr
                dd      filesize                                ; p_filesz
                dd      filesize                                ; p_memsz
                dd      5                                       ; p_flags
                dd      0x1000                                  ; p_align
_start:         mov     al, 5                   ; 5 = open syscall
                mov     ebx, fname
                mov     cl, 65                  ; 65 = O_WRONLY | O_CREAT
                mov     dx, 666q
                int     0x80
                lea     edx, [byte ecx + filesize - 65]
                xchg    eax, ebx
                xchg    eax, ecx
                mov     cl, 0
                mov     al, 4                   ; 4 = write syscall
                int     0x80
                mov     al, 1                   ; 1 = exit syscall
                int     0x80
filesize        equ     $ - $$

```

This is for the nasm assembler. Build the binary with the command line: `nasm -f bin -o a.out selfrep.asm && chmod +x a.out`

Here's the same file as a hex dump: `7F 45 4C 46 01 01 01 00 00 00 00 00 00 00 00 00 02 00 03 00 01 00 00 00 4C 00 62 2E 2C 00 00 00 00 00 00 00 00 00 00 00 34 00 20 00 01 00 00 00 00 00 00 00 00 00 62 2E 6F 75 74 00 6A 00 00 00 6A 00 00 00 05 00 00 00 00 10 00 00 B0 05 BB 36 00 62 2E B1 41 66 BA B6 01 CD 80 8D 51 29 93 91 B1 00 B0 04 CD 80 B0 01 CD 80`

As requested, the program copies itself to a separate file. (The program could have been significantly shorter if it had been allowed to just write to stdout and let the user redirect to a file.)

I avoided using any borderline tricks to reduce the size. This should be a fully conformant 32-bit ELF binary.

**Edited to add**: In the above version the created file is just a plain file, but it occurs to me that for a couple of bytes (and a tiny bend of the rules), you can create something a little more interesting. This version is only two bytes longer, at 108 bytes:

```
BITS 32
                org     0x00010000
                db      0x7F, "ELF", 1, 1, 1, 0 ; e_ident
                dd      0, 0
                dw      2                       ; e_type
                dw      3                       ; e_machine
                dd      1                       ; e_version
                dd      _start                  ; e_entry
                dd      phdr - $$               ; e_phoff
                dd      0                       ; e_shoff
                dd      0                       ; e_flags
                dw      0x34                    ; e_ehsize
                dw      0x20                    ; e_phentsize
phdr:           dd      1                       ; e_phnum       ; p_type
                                                ; e_shentsize
                dd      0                       ; e_shnum       ; p_offset
                                                ; e_shstrndx
                dd      $$                                      ; p_vaddr
fname:          db      'asr', 0                                ; p_paddr
                dd      filesize                                ; p_filesz
                dd      filesize                                ; p_memsz
                dd      7                                       ; p_flags
                dd      0x1000                                  ; p_align
_start:         mov     al, 5                   ; 5 = open syscall
                mov     ebx, fname
                inc     byte [ebx]
                mov     cl, 65                  ; 65 = O_WRONLY | O_CREAT
                mov     dx, 777q
                int     0x80
                lea     edx, [byte ecx + filesize - 65]
                xchg    eax, ebx
                xchg    eax, ecx
                mov     cl, 0
                mov     al, 4                   ; 4 = write syscall
                int     0x80
                mov     al, 1                   ; 1 = exit syscall
                int     0x80
filesize        equ     $ - $$

```

Name this version `asr`, for "a self-replicator": `nasm -f bin -o asr asr.asm && chmod +x asr`

Hex dump version for the nasm-impaired: `7F 45 4C 46 01 01 01 00 00 00 00 00 00 00 00 00 02 00 03 00 01 00 00 00 4C 00 01 00 2C 00 00 00 00 00 00 00 00 00 00 00 34 00 20 00 01 00 00 00 00 00 00 00 00 00 01 00 61 73 72 00 6C 00 00 00 6C 00 00 00 07 00 00 00 00 10 00 00 B0 05 BB 38 00 01 00 FE 03 B1 41 66 BA FF 01 CD 80 8D 51 2B 93 91 B1 00 B0 04 CD 80 B0 01 CD 80`

When you run it, it creates an almost-identical file named `bsr`, but one that is itself executable. Running it will create another binary file named `csr`. And so on.

(Note that annoying things start to happen after `zsr`. I considered making a version that would cascade the name change to `atr` and so on, but I think most people will get bored well before then, so it probably isn't worth all the extra bytes.)
> 12 votes

# Answer
Here is a proof-of-concept (ungolfed) that shows how the Compilation services in .NET might be used to compile the source code on-the-fly to generate an identical output. The first copy is not identical to the original, but subsequent copies from subsequent runs are exactly identical with random file names:

```
using System;
using Microsoft.CSharp;
using System.CodeDom.Compiler;

namespace _2947
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello world!");

            var s = @"
using System;
using System.CodeDom.Compiler;
using Microsoft.CSharp;

namespace _2947
{{
    class Program
    {{
        static void Main(string[] args)
        {{
            Console.WriteLine({1}Hello world!{1});

            var s = @{1}{0}{1};
            s = string.Format(s, s, '{1}');

            string exeName = Environment.CurrentDirectory + @{1}\{1} + new Random().Next(1000, 9999) + {1}.exe{1};

            CompilerParameters cp = new CompilerParameters();
            cp.GenerateExecutable = true;
            cp.OutputAssembly = exeName;
            cp.GenerateInMemory = false;
            cp.TreatWarningsAsErrors = false;
            cp.ReferencedAssemblies.Add({1}System.dll{1});

            var c = CSharpCodeProvider.CreateProvider({1}cs{1});
            var cr = c.CompileAssemblyFromSource(cp, s);
        }}
    }}
}}
";
            s = string.Format(s, s, '"');

            string exeName = Environment.CurrentDirectory + @"\" + new Random().Next(1000, 9999) + ".exe";

            CompilerParameters cp = new CompilerParameters();
            cp.GenerateExecutable = true;
            cp.OutputAssembly = exeName;
            cp.GenerateInMemory = false;
            cp.TreatWarningsAsErrors = false;
            cp.ReferencedAssemblies.Add("System.dll");

            var c = CSharpCodeProvider.CreateProvider("cs");
            var cr = c.CompileAssemblyFromSource(cp, s);
        }
    }
}

```

Demonstration output on command-line:

```
C:\projects\codegolf\2947\2947\bin\Debug>2947
Hello world!

C:\projects\codegolf\2947\2947\bin\Debug>dir
 Volume in drive C has no label.
 Volume Serial Number is 361D-4479

 Directory of C:\projects\codegolf\2947\2947\bin\Debug

09/27/2011  02:17 PM    <DIR>          .
09/27/2011  02:17 PM    <DIR>          ..
09/27/2011  02:17 PM             7,680 2947.exe
09/27/2011  02:17 PM            13,824 2947.pdb
09/27/2011  01:33 PM            11,600 2947.vshost.exe
09/27/2011  02:17 PM             6,656 8425.exe
               4 File(s)         39,760 bytes
               2 Dir(s)   6,486,368,256 bytes free

C:\projects\codegolf\2947\2947\bin\Debug>8425
Hello world!

C:\projects\codegolf\2947\2947\bin\Debug>dir
 Volume in drive C has no label.
 Volume Serial Number is 361D-4479

 Directory of C:\projects\codegolf\2947\2947\bin\Debug

09/27/2011  02:17 PM    <DIR>          .
09/27/2011  02:17 PM    <DIR>          ..
09/27/2011  02:17 PM             7,680 2947.exe
09/27/2011  02:17 PM            13,824 2947.pdb
09/27/2011  01:33 PM            11,600 2947.vshost.exe
09/27/2011  02:17 PM             6,656 7538.exe
09/27/2011  02:17 PM             6,656 8425.exe
               5 File(s)         46,416 bytes
               2 Dir(s)   6,486,360,064 bytes free

C:\projects\codegolf\2947\2947\bin\Debug>7538
Hello world!

C:\projects\codegolf\2947\2947\bin\Debug>dir
 Volume in drive C has no label.
 Volume Serial Number is 361D-4479

 Directory of C:\projects\codegolf\2947\2947\bin\Debug

09/27/2011  02:17 PM    <DIR>          .
09/27/2011  02:17 PM    <DIR>          ..
09/27/2011  02:17 PM             7,680 2947.exe
09/27/2011  02:17 PM            13,824 2947.pdb
09/27/2011  01:33 PM            11,600 2947.vshost.exe
09/27/2011  02:17 PM             6,656 4127.exe
09/27/2011  02:17 PM             6,656 7538.exe
09/27/2011  02:17 PM             6,656 8425.exe
               6 File(s)         53,072 bytes
               2 Dir(s)   6,486,351,872 bytes free

C:\projects\codegolf\2947\2947\bin\Debug>

```
> 2 votes

# Answer
# Batch

## Version 1 (30 bytes)

```
type%0>%random%.bat&type%0>con

```

I win! :)
> 2 votes

# Answer
## DOS COM file - 50 bytes

Creates a file `X.COM` where `X` is replaced with the ones digit of the current time. COM files are simply loaded into memory at offset `100h` of the data segment (CS and DS are set to be the same) so we can simply write this memory out to a file.

```
0000000: b402 cd1a 80e6 0f80 ce30 8836 2c01 31c9  .........0.6,.1.
0000010: ba2c 01b4 3ccd 21c6 062c 0178 89c3 b440  .,..<.!..,.x...@
0000020: ba00 01b9 3200 cd21 b44c cd21 782e 636f  ....2..!.L.!x.co
0000030: 6d00                                     m.

```

nasm source

```
org 100h ; this is a COM file
mov ah,02h ; fn=get time
int 1ah ; rtc interrupt
; convert to ascii - dh gets ones digit of seconds
and dh,0fh
or dh,30h
mov [fname],dh ; move time into filename
xor cx,cx ; clear attributes
mov dx,fname ; load filename
mov ah,3ch ; fn=create file
int 21h ; dos interrupt
mov byte [fname],'x' ; reset filename
mov bx,ax ; set filehandle
mov ah,40h ; fn=write to file
mov dx,100h ; offset is the loaded binary
mov cx,len ; length of write
int 21h ; dos iterrupt
mov ah,4ch ; fn=exit
int 21h ; dos interrupt
fname: db 'x.com',0
len equ $-$$

```
> 1 votes

# Answer
## DOS .COM file, 29 bytes

The '@' is replaced randomly by an odd letter in the first half+ part of the alphabet (A, C, E, G, etc). Output files are either 255 or 256 bytes. Initial registers in real DOS (as opposed to a debugger) are that AX=0000, CX=00FF, SI=0100.

```
40       INC  AX         ;"@"
2E       CS:             ;"."
43       INC  BX         ;"C"
4F       DEC  DI         ;"O"
4D       DEC  BP         ;"M"
00 20    ADD  [BX+SI],AH ;"\0" and dummy parm
E4 40    IN   AL,40
24 0F    AND  AL,0F
0C 41    OR   AL,41
88 04    MOV  [SI],AL
B4 3C    MOV  AH,3C
41       INC  CX
89 F2    MOV  DX,SI
CD 21    INT  21
93       XCHG BX,AX
B4 40    MOV  AH,40
49       DEC  CX
CD 21    INT  21
C3       RET
```
> 1 votes

# Answer
DOS COM File - 36 bytes

```
56 BE 80 00 AD FE C8 A2 10 01 7E 17 89 F2 88 74
02 B4 3C 33 C9 CD 21 72 0A 8B D8 B4 40 5A B9 24
00 CD 21 C3

```

Output file name is specified on the command line, truncated to 8.3 format, spaces OK (spaces in DOS filenames are legal). Tested using WinXP command prompt.
> 0 votes

---
Tags: code-golf, quine
---


title: Decode Faux Braille

text:
# Question
Title: Decode Faux Braille
```
⢣⠃⢎⠆⣇⡇⡯⡂⠈⡏⢰⢵⢐⡭⢸⠪⡀⢸⢐⡭⠀⢹⠁⢎⠆⢸⣱⢸⡃⢎⠰⡱⢸⣱⢸⡃⠈⡏⢸⡃⡱⡁⢹⠁⢸⡀⡇⡗⢅⢸⡃⠈⡏⢸⢼⢸⢐⡭

⣇⢸⡃⢹⠁⢹⠁⣟⢸⢕⢐⡭⠀⡮⡆⡯⡂⣟⠀⡯⠰⡱⢸⣸⢸⢕⠀⣏⡆⢎⠆⢹⠁⣪⠅⢸⢼⢸⠰⣩⢸⢼⠀⡮⡆⡗⢼⢸⣱⠀⢎⠆⡯⠀⢇⠇⡮⡆⡯⡂⡇⡮⡆⣟⡆⣇⢸⡃⠸⡰⡸⢸⢸⣱⠈⡏⢸⢼

⢎⠆⡗⢼⢸⡃⢸⡃⡗⠔⡇⡯⠂⢹⠁⢣⠃⠸⡸⢸⡃⡯⡂⢹⠁⡇⢎⢰⢵⢸⡀⢸⡀⡇⡗⢼⢸⡃⢐⡭⢸⡃⡯⠂⡮⡆⡯⡂⡮⡆⢹⠁⣟⢐⡭⠀⢎⢸⢼⢰⢵⢸⢕⢰⢵⠰⡁⢹⠁⣟⢸⢕⢐⡭

⡮⡆⢐⡭⢸⠕⢰⢵⠰⡁⣟⠀⡇⣪⠅⢈⣝⢸⡃⡯⡂⢎⠆⠸⡰⡸⢸⢸⣱⠈⡏⢸⢼

⣪⠅⢎⠆⢸⠈⡏⠀⣇⠰⡱⠰⡱⢸⠪⡀⣪⠅⢸⡀⡇⡗⢅⢸⡃⠸⡰⡸⠰⡱⢸⢕⢸⣱⢐⡭⠀⡮⡆⡯⡂⣟⠀⣪⠅⣟⢸⠕⢰⢵⢸⢕⢰⢵⠈⡏⢸⡃⣏⡆⢸⣳⠘⡜⠀⢹⠁⢇⢆⠇⢎⠆⢸⡀⡇⡗⢼⢸⡃⣪⠅

⡇⡗⢼⢸⠕⢸⣸⠈⡏⠀⡇⣪⠅⢰⢵⠀⣪⠅⢹⠁⡯⡂⡇⡗⢼⠰⣩⠀⢎⠰⡱⢸⠢⡇⢹⠁⡮⡆⡇⡗⢼⢸⢸⠢⡇⢎⡅⢸⠅⡮⡆⣇⡇⡱⡁⢸⣳⢸⢕⢰⢵⢸⢸⡀⣇⢸⡃⠰⡱⢸⠅

⢎⠆⡗⢼⢸⡀⢣⠃⢸⡃⡗⢼⠰⣩⢸⡀⡇⣪⠅⡧⡇⢸⣸⢸⠕⢸⠕⢸⡃⡯⡂⢎⢰⢵⢐⡭⢸⡃⢸⡀⣟⠈⡏⠈⡏⢸⡃⡯⡂⣪⠅⢰⢵⢸⠢⡇⣏⡆⢐⡭⢸⠕⢰⢵⠰⡁⣟⢐⡭

⡮⡆⣟⡆⢎⢸⣱⢸⡃⡯⠰⣩⢸⢼⢸⢀⠇⡗⢅⢸⡀⡗⠔⡇⡗⢼⠰⡱⢸⠕⠰⣩⡆⡯⡂⣪⠅⢹⠁⣇⡇⢇⠇⢇⢆⠇⡱⡁⢣⠃⣩⡃

⢎⠆⣇⡇⢹⠁⡯⠂⣇⡇⢹⠁⢸⠢⢺⢰⢵⠘⡜⠀⣟⡆⣟⠀⣇⡇⡯⠂⡯⠂⣟⢸⢕⠀⢎⠆⡯⡂⢸⡀⢎⠆⢇⢆⠇⣟⢸⢕⠰⡁⡮⡆⣪⠅⣟

⣪⠅⡧⡇⢎⠆⡯⡂⢹⠁⣟⢐⡭⠈⡏⠀⢇⢆⠇⡇⡗⢼⢐⡭

⡗⢼⠰⡱⠀⣇⠰⡱⠰⡱⢸⠕⢸⢼⠰⡱⢸⡀⣟⢐⡭

```

ASCII version of the above

`⡯⡂⣟⢸⡀⡮⡆⢹⠁⣟⢸⣱⠀`

# About Braille characters

A Braille character packs a 4 by 2 rectangle of dots, which can be viewed as a Boolean matrix.

The concatenation of all such matrices is a 4 by 2\*n boolean matrix, where n is the length of the input string.

You should look for vertical lines without any dots in them, and use those as separators to split the big matrix into smaller matrices for each character.

Then, look for patterns to convert them to letters of the English alphabet or spaces. Note that after removing the separators (vertical empty lines), a space is a 4 by 0 matrix.

Below is a description of the alphabet in ASCII:

```
A   | B   | C  | D   | E  | F  | G   | H   | I | J  | K    | L  | M     | N    | O   | P   | Q    | R   | S   | T   | U   | V   | W     | X   | Y   | Z
----+-----+----+-----+----+----+-----+-----+---+----+------+----+-------+------+-----+-----+------+-----+-----+-----+-----+-----+-------+-----+-----+----
.#. | ##. | .# | ##. | ## | ## | .## | #.# | # | .# | #.#. | #. | #...# | #..# | .#. | ##. | .##. | ##. | .## | ### | #.# | #.# | #...# | #.# | #.# | ###
#.# | ### | #. | #.# | ## | #. | #.. | #.# | # | .# | ##.. | #. | ##.## | ##.# | #.# | #.# | #..# | #.# | #.. | .#. | #.# | #.# | #.#.# | .#. | #.# | ..#
### | #.# | #. | #.# | #. | ## | #.# | ### | # | .# | #.#. | #. | #.#.# | #.## | #.# | ##. | #.## | ##. | .## | .#. | #.# | #.# | #.#.# | .#. | .#. | .#.
#.# | ### | .# | ### | ## | #. | .## | #.# | # | #. | #..# | ## | #...# | #..# | .#. | #.. | .### | #.# | ##. | .#. | ### | .#. | .#.#. | #.# | .#. | ###

```

# Specification

* The input is a sequence of Unicode code points in the range U+2800..U+28FF represented as the usual string type in your language (e.g. char array, char pointer) in any popular encoding supported (UTF-8, UCS-2, etc).
* Trailing spaces in the output are fine.

---

*EDIT:* apologies to those whose browsers misrender the dots, it's supposed to look like this (image):

# Answer
# Python 3, ~~181~~ ~~179~~ ~~171~~ ~~167~~ ~~161~~ 159 bytes

Input by UTF-16 little-endian bytes without BOM. First decompose into columns using bit shifts, split by empty column, then hash them into a lookup table.

*-2 bytes thanks to ngn.<br>-5 bytes thanks to Mr. Xcoder.*

```
lambda h,j=''.join:j(' ZAQV;JWP;MBOS;YRKCGXDF;ILHUENT'[int('0'+i,27)%544%135%32]for i in j(chr(64|i&7|i>>3&8)+chr(64|i>>3&7|i>>4&8)for i in h[::2]).split('@'))

```

Try it online!
> 14 votes

# Answer
# JavaScript (ES6),  ~~148 146 143~~  142 bytes

*Saved 1 byte thanks to @ngn*

```
s=>[...s].map(c=>g((k=c.charCodeAt()/8)&8|k*8&7)&g(k&7|k/2&8),o=x='',g=n=>x=n?x*27+n:!(o+=' DZQGYWXNHJ.CSTIO.AFB.LPVE..KUMR'[x%854%89%35]))&&o

```

Try it online!
> 12 votes

# Answer
# Python 3, ~~305~~ ~~302~~ ~~301~~ ~~286~~ ~~251~~ ~~198~~ 182 bytes

```
def f(s,A=''):
 for c in s:l=bin(ord(c))[-8:];A+='7'+l[5:]+l[1]+'7'+l[2:5]+l[0]
 print(''.join('K.L.SXC PRU.NYEOGZVJIW..HFBTAQDM'[int('7'+c,22)%141%109%35]for c in A.split('70000')))

```

Try it online!
> 4 votes

---
Tags: code-golf, ascii-art, unicode, binary-matrix
---


title: Which Row is the Key On?

text:
# Question
Title: Which Row is the Key On?
Given any of the following characters (or a newline):

```
`1234567890-=~!@#$%^&*()_+qwertyuiop[]\QWERTYUIOP{}|asdfghjkl;'ASDFGHJKL:"zxcvbnm,./ZXCVBNM<>?

```

Your program must output the row that it is on the keyboard

---

Because my keyboard is (almost) out of battery, your code must be as short as possible

---

The keyboard your program should use (for the row lookup), should look like:

``Row 1:``~`</sub>` `!1``@2` `#3``$4` `%5``^6` `&7``*8` `(9``)0` `_-``+=`
`Row 2:` `Q` `W` `E` `R` `T` `Y` `U` `I` `O` `P` `<sup>{</sup><sub>[</sub>` `<sup>}</sup><sub>]</sub>` `<sup>|</sup><sub>\</sub>`
`Row 3:` `A` `S` `D` `F` `G` `H` `J` `K` `L` `<sup>:</sup><sub>;</sub>` `<sup>"</sup><sub>'</sub>` `<sub> return</sub>`
`Row 4:` `Z` `X` `C` `V` `B` `N` `M` `<sup><</sup><sub>,</sub>` `<sup>></sup><sub>.</sub>` `<sup>?</sup><sub>/</sub>`
`Row 5:`   `space``

Where `return` is a newline. Empty keys don't mean anything.

## Examples

```
"$"
1

"R"
2

"a"
3

"?"
4

"\n"
3

" "
5

```

where `\n` is a newline character.

## Specifications

* Your program should be case insensitive
* Your program only needs to handle the characters on the keyboard shown

# Answer
> 6 votes
# Pyth, ~~62~~ ~~66~~ 65 bytes

```
?zh@+,4Zmid2c.Bi."0fÀÓ¸[9Ñ¶¤KïLäHÉðbÀ`]ü©¬vS"16 2-CzCd3

```

Try it online.

Uses a packed string representing a number in hex which, when chopped into two-bit chunks, represents the row of every character except  and `!` as a value from 0 to 3. We leave out  and `!` so we don't have to store 4 or have a 0 at the start of this number, then add their row values using `+,4Z`. Once we've turned the string into row values, all we have to do is use the character code of the input to index into the array of values, and then add 1.

Newline is handled separately because it's interpreted by Pyth as an empty string and so has a character code of 0.

This would be shorter if I could figure out how to use base 256 in Pyth, but I can't quite make it work.

# Answer
> 12 votes
# JavaScript (ES6), ~~105~~ ~~102~~ 101 bytes

```
c=>/[~`0-9!@#-&^(-+_=-]/.test(c)+/[asdfghjkl;:'"\n]/i.test(c)*3+/[zxcvbnm,<.>/?]/i.test(c)*4||++c*7^2

```

## Explanation

In JavaScript `test` returns a boolean which acts the same as `1` or `0` so I multiply them by their row. Testing for row 2 took the most bytes so I used that one as the default if no others matched.

```
c=>
  /[~`0-9!@#-&^(-+_=-]/.test(c)   // row 1 regex
  +/[asdfghjkl;:'"\n]/i.test(c)*3 // row 3 regex
  +/[zxcvbnm,<.>/?]/i.test(c)*4   // row 4 regex
  ||++c                           // space ++ = 1, any character on row 2 ++ = NaN
    *7^2                          // 7 XOR 2 = 5, NaN XOR 2 = 2

```

## Test

```
var solution = c=>/[~`0-9!@#-&^(-+_=-]/.test(c)+/[asdfghjkl;:'"\n]/i.test(c)*3+/[zxcvbnm,<.>/?]/i.test(c)*4||++c*7^2
```

```
<textarea id="input">-</textarea><br />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```

# Answer
> 5 votes
## Glava 1.5, 164 bytes

Glava is a dialect of Java that makes Java code shorter. This code is unfortunately non-competitive as the commit (2 hours late...) used was made after this challenge, which fixed some vital bugs that would not allow this program to work.

```
p(A[0].matches("[`0-9-=~!@#$%^&*()_+]")?1:A[0].replace("\\n","\n").matches("(?i)[asdfghjkl;':\"\n]")?3:A[0].matches("(?i)[zxcvbnm,.\\/<>?]")?4:A[0].matches(" ")?5:2

```

This is a full program that takes input via command-line arguments. Works by simply testing for which row regex it matches, then outputs the corresponding number.

# Answer
> 4 votes
# Python 3, 142

```
print(int(("~`!1@2#3$4%5^6&7*8(9)0_-+=""qwertyuiop{[}\|"+"]"*11+'asdfghjkl;:"\n'"'"*13+"zxcvbnm,<.>/""?"*14+" ").index(input().lower())/26)+1)

```

There is probably a shorter way that I am overlooking ¯\\\_(ツ)\_/¯

# Answer
> 4 votes
# Pyth, 98

```
|+++l:"~`0123456789!@#$%^&*()_-=+"z1*l:"asdfghjkl;:'\"\n"rz0 1 3*l:"zxcvbnm,<.>/? "rz0 1 4 l:dz1 2

```

not sure how to get the 0-9 range working for some reason :|, inspired by user81655's answer

# Answer
> 4 votes
## Japt, ~~73~~ ~~70~~ 66 bytes

```
2+`qØÆyuiop\{}[]|\\1dfghjkl;:
'1zxcvbnm,.<>?/\"1 `q1 ®bUv)<0} b!1

```

Try it online! (in the example, the input is literally a newline)

# Answer
> 4 votes
# Bash, 108

No Bash answer? Bash answer. `grep -Fin` is definitely the right tool for this job.

This program is in two files.

## `k`, 73 bytes

```
`1234567890-=~!@#$%^&*()_+
qwertyuiop[]\{}|
asdfghjkl;':"
zxcvbnm,./<>?

```

There are 5 lines, the last one is a space. If you have trouble reproducing the file, the base64 is:

```
YDEyMzQ1Njc4OTAtPX4hQCMkJV4mKigpXysKcXdlcnR5dWlvcFtdXHt9fAphc2RmZ2hqa2w7JzoiCnp4Y3Zibm0sLi88Pj8KIA==

```

## `b`, 34 bytes

This is the program itself, it takes input as the only command line argument.

```
grep -Fin "$1" k|tail -n3|head -c1

```

Score: 34 + 73 + 1 (for `k`'s filename) = 108 bytes

## Ungolfed

```
grep --fixed-strings --ignore-case --line-number "$1" k|tail --lines=3|head --bytes=1

```

## Explanation

* `grep` \- search a file for lines matching a string or regular expression, output only those lines
* `-F` aka `--fixed-strings` \- disable regular expressions so `[` etc. are handled correctly
* `-i` aka `-y` aka `--ignore-case` \- case-insensitive matching
* `-n` aka `--line-number` \- show the line number and : before every line (e.g. `4:zxcvbnm,./<>?`)
* `"$1"` \- search for the script's first command-line argument, the quotes are necessary to handle newline and space
* `k` \- search in file `k`
* This `grep` command will match all five lines if the input is a newline, and only one line otherwise.
* `|` \- pipe, send standard output of one command to standard input of the next
* `tail` \- output the last N lines or characters of standard input
* `-n3` aka `--lines=3` \- output the last 3 lines
* If the input wasn't a newline, there is only one line to process, which starts with the row number because of the `-n` flag on `grep`. Otherwise, this command takes only lines 3, 4 and 5 (the last 3 lines).
* `|` \- pipe
* `head` \- output the first N lines or characters of standard input
* `-c1` aka `--bytes=1` \- output the first character
* If the input wasn't a newline, this takes the first character, which is the line number where the input is found. If the input is a newline, it takes the first character of lines 3, 4 and 5 combined, which is 3, which happens to be the correct row number for newline.

# Answer
> 4 votes
# Java, 300 bytes

```
import java.util.Scanner;public class A{public static void main(String[] args){String g="~`!1@2#3$4%5^6&7*8(9)0_-+=qQwWeErRtTyYuUiIoOpP[{]}\\|aAsSdDfFgGhHjJkKlL;:\'\"\r";Scanner i=new Scanner(System.in);int f=g.indexOf((i.nextLine().charAt(0)));System.out.print(f<0?4:(f<26?1:(f<53?2:(f<76?3:5))));}}

```

I'm not an expert, and this is my first attempt at golfing, but I figured, what the hell, why not? Above is the full program version, the actual code that goes into it would most likely take a decent amount of characters off.

# Answer
> 3 votes
## Pyth, 105 bytes

```
J?<l-c".^$*+?{}[]\|()"1]z14+\\zrz0?qJd5?:"qwertyuiop[]\|"J)2?:"asdfghjkl;':\"\n"J)3?:"zxcvbnm,./<>?"J)4 1

```

Explanation:

```
J?<l-c".^$*+?{}[]\|()"1]z14+\\zrz0     # Escape input if regex metachar
?qJd5                                  # Check space
?:"qwertyuiop[]\|"J)2                  # Check second row
?:"asdfghjkl;':\"\n"J)3                # Check third row
?:"zxcvbnm,./<>?"J)4                   # Check fourth row
1                                      # If none of these, must be on first row.

```

I decided to choose the first row as the "must be if nothing else" row because it required the most bytes to represent even after golfing.

# Answer
> 3 votes
# Perl 6, 128 bytes

```
say 1+(/<[-\d=~!@#$%^&*()_+/`]>/,/<[qwertyuiop[\]\\{}|]>/,/<[asdfghjkl;':"\n]>/,/<[zxcvbnm,./<>?]>/,' ').first: @*ARGS.lc~~*,:k

```

I make a list of regexes containing character classes along with a string literal space. I then call the `first` method on the list (which is just the method version of the `first` higher order function), using smartmatch to compare the argument passed to the program against the current item in the list. Note that smartmatch does "the right thing" for both regexes and a string literal. The `:k` optional parameter to `first` causes the method to return the index of the matching item in the list, which I then add 1 to and output via `say`.

Note that when using this program you will have to properly escape certain characters like \` and space in your shell. For instance: perl6 keyboard.p6 \\\`

# Answer
> 3 votes
## Python 3, 89 bytes

```
print("qwertyuiop{}[]\\|asdfghjkl;:\"\n'''zxcvbnm,.<>/???? ".find(input().lower())//16+2)

```

As I can't comment yet, I'm posting the improvement for the current Python 3 answer separately.

**Edit**: All code in `print` now and further tweaked.

# Answer
> 2 votes
# Perl, ~~96~~ ~~77~~ 76 bytes

Run using `perl -p`. Make sure you're feeding it just single characters; for example, to run it from a file `key.pl` (to avoid mucking around with shell escape sequences) `echo -n q|perl -p key.pl`.

```
$_=/[\d~`!@#-&(-+_=-]/+/[adfghjkls"':;
]/i*3+/[bcnmvxz<>,.?\/]/i*4+/ /*5||2

```

Abusing the regex range functionality is fun.

# Answer
> 2 votes
## JavaScript ES6, 114 bytes

```
n=>[`qwertyuiop{}[]|\\`,`asdfghjkl;:
'`,`zxcvbnm,.<>?/"`,` `].map(x=>+(x.indexOf(n.toLowerCase())<0)).indexOf(0)+2

```

Another JavaScript solution. The principle is to return the index of the input char in the array of rows plus 2 (so as the 0-9 row returns -1, i.e. not exists, -1+2=1. `q` is in the first string of the array, so it returns 0+2=2nd row).

# Answer
> 2 votes
# PHP, 173 bytes

The idea here was to use the regex capturing group number as the row index. Probably some more optimizations in the regex itself.

```
$i=$argv[1];preg_match("%([!#-&\(-+-0-9=@^-`~])|([EIO-RT-UWY[-]eio-rt-uwy{-}])|([\"':-;ADF-HJ-LSadf-hj-ls])|([,.-/<>-?B-CM-NVXZb-cm-nvxz])%",$i,$m);echo array_flip($m)[$i];

```

The `preg_match()` call will create an array `$m` of matches, and if we were to print that, it'd look something like this (assuming `z` was the input):

```
Array ( [0] => 'z', [1] => '', [2] => '', [3] => '', [4] => 'z' )

```

Flipping that array, by swapping keys and values, moves left to right and only keeps the last distinct key, so we end up with:

```
Array ( 'z' => 4, '' => 3 )

```

Then we use the input character as the index in the array to get our result.

Try it out here.

# Answer
> 2 votes
# C, ~~145 143 136 132 127 106~~ 104 bytes

```
#define c"\x7ea6a6f8\x5777595"
f(a){return a-32?L"\x200000\0\xf3008020\xf2a00000"c c[a>>4]>>a%16*2&3:4;}

```

Try it online!

~~This uses `index()` from POSIX.1-2001 and is deprecated in POSIX.1-2008.~~ This assumes ASCII and 32 bit ints.

# Answer
> 1 votes
# Ruby, 82 bytes

```
->i{1+((0>r=i.ord-33)?r%5:"bc7xdutvz4ind3bwqf6mcu5vxiahnmlfs93c".to_i(36)>>2*r&3)}

```

Try it online!

# Answer
> 0 votes
# C#6, 201 bytes

Nothing special here. I found it cheaper to just write both cases rather than use ToUpper() due to the string's fixed width.

```
using C=System.Console;class P{static void Main(string[]a)=>C.Write("`1234567890-=~!@#$%^&*()_+qwertyuiop[]\\QWERTYUIOP{}|asdfghjkl;'\raASDFGHJKL:\"\nazxcvbnm,./zzzZXCVBNM<>?zzz ".IndexOf(a[0])/26+1);}

```

Indented:

```
using C=System.Console;
class P{
    static void Main(string[]a)=>
        C.Write("`1234567890-=~!@#$%^&*()_+qwertyuiop[]\\QWERTYUIOP{}|asdfghjkl;'\raASDFGHJKL:\"\nazxcvbnm,./zzzZXCVBNM<>?zzz ".IndexOf(a[0])/26+1);
}

```

# Answer
> 0 votes
# CJam, 125 bytes

```
q_" "={;5}{"`1234567890-=~!@#$%^&*()_+qwertyuiop[]\QWERTYUIOP{}|asdfghjkl;'ASDFGHJKL:\"    zxcvbnm,./ZXCVBNM<>?    "\#26/1+}?

```

---

### Explanation

```
q                          e# read input
 _" "=                     e# decide if the input is a space
      {;5}                 e# if it is, push 5
          {"..."\#26/1+}?  e# if it isn't, push the correct row

```

# Answer
> 0 votes
# SpecBAS - 178 bytes

```
1 a$="~`!1@2#3$4%5^6&7*8(9)0-_+=qQwWeErRtTyYuUiIoOpP{[}]|\aaaaAsSdDfFgGhHjJkKlL:;'"#34#13"zzzzzzzZxXcCvVbBnNmM<,>.?/"+" "*26
2 INPUT k$: IF k$="" THEN k$=#13
3  ?CEIL(POS(k$,a$)/26)

```

I used a long string where each row is 26 characters long (#34 is code for double quote and #13 is code for return).

Then print the result of rounding position/26.

# Answer
> 0 votes
# Python 2, 146 bytes

```
e="\n";lambda x:("`1234567890-=~!@#$%^&*()_+qwertyuiop[]\\QWERTYUIOP{}|asdfghjkl;'ASDFGHJKL:\""+e*4+"zxcvbnm,./ZXCVBNM<>?"+e*13+" ").index(x)/26+1

```

# Answer
> 0 votes
# Excel, 132 bytes

`=INT((FIND(A1,"`1234567890-=~!@#$%^&*()_+qwertyuiop[]\QWERTYUIOP{}|asdfghjkl;'ASDFGHJKL:""aaa
zxcvbnm,./ZXCVBNM<>?zzzzzz ")-1)/26)+1`

Attempts to use the case in-sensitive `SEARCH()` instead of `FIND()` revealed that Excel matches `~`, `*` and `?` to `(tick). The matching of`?`means we can't use`SEARCH()\`, which would have shaved a massive 5 bytes...

---
Tags: code-golf, keyboard, classification
---


# Question
Title: The shortest code to tell if a number is even or odd
One of my colleagues proposed us a challenge: to write the shortest C/C++ program to determine if a number is even or odd.

These are the requirements:

* Get a number from keyboard, at run-time (not from command line)
* Output the string `pari` if the number is even
* Output the string `dispari` if the number is odd
* We can assume that the input is legal
* We can assume that the machine has a i386 architecture
* Code preprocessing is not allowed (e.g.: use `#define`s)
* \[edit after comments\] The code can be considered valid if it compiles with `gcc 4.x`

This is the best attempt we had so far (file test.c, 50B):

```
main(i){scanf("%d",&i);puts("dispari"+3*(~i&1));}

```

Do you think we can go further?

<sub>(\*): "dispari" is the italian for odd and "pari" is the italian for even</sub>

# Answer
## 39 bytes

Given you didn't specified the range of the number input, then here's a solution that handles 0..9 only:

```
main(){puts("dispari"-~getchar()%2*3);}

```
> 5 votes

# Answer
## 47 bytes (2 less)

```
main(i){scanf("%d",&i);puts("dispari"-~i%2*3);}

```

For a positive `i`, `~i` is negative, so `~i%2` is 0 or -1.
> 8 votes

# Answer
# 48 bytes

```
main(i){scanf("%d",&i);puts("dispari"+3-i%2*3);}

```
> 3 votes

# Answer
## 34 bytes

Build with

```
gcc -nostartfiles -Wl,-ea odd.c
```

Works in GCC 6.3.0.

```
a(){puts("dispari"-~getch()%2*3);}
```
> 1 votes

---
Tags: code-golf, c, c++
---


title: Minimal sparse rulers

text:
# Question
Title: Minimal sparse rulers
A standard ruler of length *n* has distance marks at positions 0, 1, ..., *n* (in whichever units). A sparse ruler has a subset of those marks. A ruler can measure the distance *k* if it has marks at positions *p* and *q* with *p**q*=*k*.

### The challenge

Given a positive integer *n*, output the minimum number of marks required in a sparse ruler of length *n* so that it can measure all distances 1, 2, ..., *n*.

This is OEIS A046693.

As an example, for input 6 the output is 4. Namely, a ruler with marks at 0, 1, 4, 6 works, as 1−0=1, 6−4=2, 4−1=3, 4−0=4, 6−1=5, and 6−0=6.

### Additional rules

### Test cases

```
1   ->   2
2   ->   3
3   ->   3
4   ->   4
5   ->   4
6   ->   4
7   ->   5
8   ->   5
9   ->   5
10  ->   6
11  ->   6
12  ->   6
13  ->   6
14  ->   7
15  ->   7
16  ->   7
17  ->   7
18  ->   8
19  ->   8
20  ->   8
21  ->   8
22  ->   8
23  ->   8
24  ->   9
25  ->   9
26  ->   9
27  ->   9
28  ->   9
29  ->   9
30  ->  10
31  ->  10
32  ->  10

```

# Answer
# Jelly, 14 bytes

```
ŒcIQL
‘ŒPÇÐṀḢL

```

A monadic link taking and returning non-negative integers.

**Try it online!** (first 15 values here \- not efficient)

### How?

Finds all the rulers one could make using marks 1 through to n+1 (the power-set of \[1,n+1\]) ordered by their marking-count, and keeps only those which create maximal measurable distances (the length of the set of differences between all ordered pairs of marks), then returns the length of the first (i.e. \[one of\] the shortest one\[s\]).

```
ŒcIQL - Link 1: number of measurable distances: list of numbers, ruler  e.g. [1,2,3,7]
Œc    - all pairs                                [[1,2],[1,3],[1,7],[2,3],[2,7],[3,7]]
  I   - incremental differences                                          [1,2,6,1,5,4]
   Q  - de-duplicate                                                       [1,2,6,5,4]
    L - length                                                                      5

‘ŒPÇÐṀḢL - Main link: number, n              e.g. 4
‘        - increment                              5
 ŒP      - power-set (implicit range of input)   [[],[1],[2],[3],[4],[5],[1,2],[1,3],[1,4],[1,5],[2,3],[2,4],[2,5],[3,4],[3,5],[4,5],[1,2,3],[1,2,4],[1,2,5],[1,3,4],[1,3,5],[1,4,5],[2,3,4],[2,3,5],[2,4,5],[3,4,5],[1,2,3,4],[1,2,3,5],[1,2,4,5],[1,3,4,5],[2,3,4,5],[1,2,3,4,5]]
    ÐṀ   - keep those maximal under:
   Ç     -   call the last link (1) as a monad   [[1,2,3,5],[1,2,4,5],[1,3,4,5],[1,2,3,4,5]]
      Ḣ  - head                                  [1,2,3,5]
       L - length                                 4

```
> 2 votes

# Answer
## Wolfram Language (Mathematica), 65 bytes

```
Tr[1^#]&@@Cases[Subsets[n=0~Range~#],k_/;Union@@Abs[k-#&/@k]==n]&

```

Try it online!
> 8 votes

# Answer
# Python 2, ~~129~~ ~~128~~ 126 bytes

*thanks to totallyhuman for -1 byte*

```
from itertools import*
r=range(1,input()+2)
[{a-b+1for a in l for b in l}>set(r)>exit(i)for i in r for l in combinations(r,i)]

```

Try it online!

output is via exit code
> 5 votes

# Answer
# Pyth, 14 bytes

```
lh.Ml{-M^Z2ySh

```

**Try it here!**

# Pyth, ~~21~~ 19 bytes

```
hlMf!-SQmaFd.cT2ySh

```

**Try it here!**

## How it works

I'll update this after golfing.

```
hSlMfqSQS{maFd.cT2ySh ~ Full program. Q = input.

                   Sh ~ The integer range [1, Q + 1].
                  y   ~ Powerset.
    f                 ~ Filter (uses a variable T).
              .cT2    ~ All two-element combinations of T.
          m           ~ Map.
           aFd        ~ Reduce by absolute difference.
        S{            ~ Deduplicate, sort.
     qSQ              ~ Is equal to the integer range [1, Q]?
  lM                  ~ Map with length.
hS                    ~ Minimum.

```

Thanks to isaacg for saving a byte for my second approach and inspiring me to golf 3 bytes off my current approach!
> 5 votes

# Answer
# Mathematica, 84 bytes

```
#&@@(l=Length)/@Select[(S=Subsets)@Range[0,d=#],l@Union[Differences/@S[#,{2}]]==d&]&

```

Try it online!
> 5 votes

# Answer
# Jelly, 17 bytes

```
‘ŒPµạþ`FQḊṫ³µÐfḢL

```

Try it online!

Saved 1 byte thanks to Jonathan Allan!
> 4 votes

# Answer
# Husk, ~~20~~ 18 bytes

```
λ▼mLfȯ≡⁰u´×≠tṖ⁰)…0

```

Thanks @H.PWiz for -2 bytes!

Try it online!

### Explanation

```
λ               )…0  -- lambda with argument ⁰ as [0..N]
              Ṗ⁰     -- all subsets of [0..N]
             t       -- tail (remove empty subset)
    f(      )        -- filter by following function:
           ≠         --   absolute differences
         ´×          --   of all pairs drawn from itself
        u            --   remove duplicates
      ≡⁰             --   "equal" to [0..N]
  mL                 -- map length
 ▼                   -- minimum

```
> 4 votes

# Answer
# Jelly, 17 bytes

```
_þ`ẎQṢw
‘ŒPçÐfRḢL

```

Try it online!

Borrowed a trick from Mr. Xcoder's answer for -1.
-1 thanks to Jonathan Allan.
> 3 votes

# Answer
# Pyth, 15 bytes

```
lhf!-SQ-M^T2yUh

```

Test suite

## How it works

```
lhf!-SQ-M^T2yUh
             Uh    [0, 1, ... n]
            y      Powerset - all possible rulers
  f                Filer rulers on
         ^T2       All pairs of marks, in both orders
       -M          Differences - (a)
     SQ            [1, ... n], the desired list of differences - (b)
    -              Remove (a) from (b)
   !               Check that there's nothing left.
 h                 The first remaining ruler (powerset is ordered by size)
l                  Length

```
> 3 votes

# Answer
# Ruby, 98 bytes

```
->n{(w=*0..n).find{|x|w.combination(x+1).find{|y|y.product(y).map{|a,b|(b-a).abs}.uniq.size>n}}+1}

```

Try it online!
> 1 votes

---
Tags: code-golf, math, sequence, number-theory, integer
---


# Question
Title: Branch differently in x86 / x86-64 using only printable visible ASCII characters in the machine code
The task is simple: write a program that branches differently in x86 (32-bit) and x86-64 (64-bit) using only printable visible ASCII characters 0x21...0x7e (space and del are not allowed) in the machine code.

* Conditional assembly is not allowed.
* Using API calls in not allowed.
* Using kernel-mode (ring 0) code is not allowed.
* The code must run without causing exceptions in both IA-32 and x86-64 in Linux or in some other protected mode OS.
* The functioning must not depend on command line parameters.
* All instructions must be encoded in machine code using only ASCII characters in the range 0x21...0x7e (33...126 decimal). So eg. `cpuid` is out of limits (it's `0f a2`), unless you use self-modifying code.
* The same binary code must run in x86 and x86-64, but as file headers (ELF/ELF64/etc.) may be different, you may need to assemble and link it again. However, the binary code must not change.
* Solutions should work on all processors between i386...Core i7, but I'm interested also in more limited solutions.
* The code must branch in 32-bit x86 but not in x86-64, or vice versa, but using conditional jumps is not a requirement (indirect jump or call is also accepted). The branch target address must be such that there is space for some code, at least 2 bytes of space in which a short jump (`jmp rel8`) fits in.

The winning answer is the one that uses least bytes in the machine code. The bytes in the file header (ELF/ELF64 for example) are not counted, and any bytes of code after the branch (for testing purposes etc.) aren't counted neither.

Please present your answer as ASCII, as hexadecimal bytes and as commented code.

My solution, 39 bytes:

ASCII: `fhotfhatfhitfhutfhotfhatfhitfhut_H3<$t!`

hexadecimal: `66 68 6F 74 66 68 61 74 66 68 69 74 66 68 75 74 66 68 6F 74 66 68 61 74 66 68 69 74 66 68 75 74 5F 48 33 3C 24 74 21`.

Code:

```
; can be compiled eg. with yasm.
; yasm & ld:
; yasm -f elf64 -m amd64 -g dwarf2 x86_x86_64_branch.asm -o x86_x86_64_branch.o; ld x86_x86_64_branch.o -o x86_x86_64_branch
; yasm & gcc:
; yasm -f elf64 -m amd64 -g dwarf2 x86_x86_64_branch.asm -o x86_x86_64_branch.o; gcc -o x86_x86_64_branch x86_x86_64_branch.o

section .text
global main
extern printf

main:
    push    word 0x746f     ; 66 68 6f 74 (x86, x86-64)
    push    word 0x7461     ; 66 68 61 74 (x86, x86-64)
    push    word 0x7469     ; 66 68 69 74 (x86, x86-64)
    push    word 0x7475     ; 66 68 75 74 (x86, x86-64)

    push    word 0x746f     ; 66 68 6f 74 (x86, x86-64)
    push    word 0x7461     ; 66 68 61 74 (x86, x86-64)
    push    word 0x7469     ; 66 68 69 74 (x86, x86-64)
    push    word 0x7475     ; 66 68 75 74 (x86, x86-64)

    db      0x5f            ; x86:    pop edi
                            ; x86-64: pop rdi

    db      0x48, 0x33, 0x3c, 0x24
                            ; x86:
                            ; 48          dec eax
                            ; 33 3c 24    xor edi,[esp]

                            ; x86-64:
                            ; 48 33 3c 24 xor rdi,[rsp]

    jz      @bits_64        ; 0x74 0x21
                            ; branch only if running in 64-bit mode.

; the code golf part ends here, 39 bytes so far.

; the rest is for testing only, and does not affect the answer.

    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop
    nop

    jmp     @bits_32

@bits_64:
    db      0x55                    ; push rbp

    db      0x48, 0x89, 0xe5        ; mov rbp,rsp
    db      0x48, 0x8d, 0x3c, 0x25  ; lea rdi,
    dd      printf_msg              ; [printf_msg]
    xor     eax,eax
    mov     esi,64

    call    printf
    db      0x5d                    ; pop rbp

    NR_exit equ 60

    xor     edi,edi
    mov     eax,NR_exit     ; number of syscall (60)
    syscall

@bits_32:
    lea     edi,[printf_msg]
    mov     esi,32
    call    printf

    mov     eax,NR_exit
    int     0x80

section .data

printf_msg: db "running in %d-bit system", 0x0a, 0

```

# Answer
# 7 bytes

```
0000000: 6641 2521 2173 21                        fA%!!s!

```

As 32 bit

```
00000000  6641              inc cx
00000002  2521217321        and eax,0x21732121

```

As 64 bit

```
00000000  6641252121        and ax,0x2121
00000005  7321              jnc 0x28

```

`and` clears the carry flag so the 64 bit version always jumps. For 64-bit the `6641` is the operand size override followed by `rex.b` so the operand size for the `and` comes out as 16 bit. On 32-bit the `6641` is a complete instruction so the `and` has no prefix and has a 32-bit operand size. This changes the number of immediate bytes consumed by the `and` giving two bytes of instructions that are only executed in 64-bit mode.
> 17 votes

# Answer
## 11 bytes

```
ascii: j6Xj3AX,3t!
hex: 6a 36 58 6a 33 41 58 2c 33 74 21

```

Uses the fact that in 32-bit, 0x41 is just `inc %ecx`, whereas in 64-bit it is the `rax` prefix that modifies the target register of the following `pop` instruction.

```
        .globl _check64
_check64:
        .byte   0x6a, 0x36      # push $0x36
        .byte   0x58            # pop %rax
        .byte   0x6a, 0x33      # push $0x33

        # this is either "inc %ecx; pop %eax" in 32-bit, or "pop %r8" in 64-bit.
        # so in 32-bit it sets eax to 0x33, in 64-bit it leaves rax unchanged at 0x36.
        .byte   0x41            # 32: "inc %ecx", 64: "rax prefix"
        .byte   0x58            # 32: "pop %eax", 64: "pop %r8"

        .byte   0x2c, 0x33      # sub $0x33,%al
        .byte   0x74, 0x21      # je (branches if 32 bit)

        mov     $1,%eax
        ret

        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        nop
        mov     $0,%eax
        ret

```

Wrote this on OSX, your assembler might be different.

Call it with this:

```
#include <stdio.h>
extern int check64(void);
int main(int argc, char *argv[]) {
  if (check64()) {
    printf("64-bit\n");
  } else {
    printf("32-bit\n");
  }
  return 0;
}

```
> 7 votes

# Answer
## 7 bytes

Not relying on 66 prefix.

```
$$@$Au!
```

32-bit:

```
00000000 24 24 and al,24h
00000002 40    inc eax
00000003 24 41 and al,41h
00000005 75 21 jne 00000028h
```

AL will have bit 0 set after the INC, the second AND will preserve it, the branch will be taken.

64-bit:

```
00000000 24 24    and al,24h
00000002 40 24 41 and al,41h
00000005 75 21    jne 00000028h
```

AL will have bit 0 clear after the first AND, the branch will not be taken.
> 4 votes

# Answer
If only C9h were printable...

32-bit:

```
00000000 33 C9 xor  ecx, ecx
00000002 63 C9 arpl ecx, ecx
00000004 74 21 je   00000027h
```

The ARPL will clear the Z flag, causing the branch to be taken.

64-bit:

```
00000000 33 C9 xor    ecx, ecx
00000002 63 C9 movsxd ecx, ecx
00000004 74 21 je     00000027h
```

The XOR will set the Z flag, the MOVSXD will not change it, the branch will not be taken.
> 0 votes

---
Tags: code-golf, restricted-source, machine-code, x86-family
---