# Question
Title: When does Santa enter the basement? (AOC Day 1)
I'm reproducing the second part of the first day of Advent of Code, with permission from the creator.

Santa is trying to deliver presents in a large apartment building, but he can't find the right floor - the directions he got are a little confusing. He starts on the ground floor (floor 0) and then follows the instructions one character at a time.

An opening parenthesis, `(`, means he should go up one floor, and a closing parenthesis, `)`, means he should go down one floor.

The apartment building is very tall, and the basement is very deep; he will never find the top or bottom floors.

Given a set of instructions, find the position of the first character that causes him to enter the basement (floor -1).

As examples:

input `)` causes him to enter the basement at character position 1.

input `()())` causes him to enter the basement at character position 5.

A long input is given here that should yield the solution 1797.

This is code golf, so the shortest solution wins!

# Answer
# Jelly, ~~8~~ 7 bytes

```
O-*+\i-

```

*Thanks to @Sp3000 for golfing off 1 byte!*

Try it online!

### How it works

```
O-*+\i-    Main link. Input: s (string)

O          Ordinal; replace each character with its code point.
           This maps "()" to [48, 49].
 -*        Apply x -> (-1) ** x.
           This maps [48, 49] to [1, -1].
   +\      Compute the cumulative sum, i.e., the list of partial sums.
     i-    Find the first index of -1.

```
> 17 votes

# Answer
## Python 2, 44 bytes

```
try:input()
except Exception,e:print e[1][2]

```

This clever solution was found by hallvabo, xsot, mitchs, and whatisgolf on this problem on Anarchy golf. If any of you want to post it instead, I'll remove this.

The trick is to let Python's parser do the work. The function `input()` tries to evaluate an input string, and throws an error on the first unmatched paren. This error, when caught, has form

```
SyntaxError('unexpected EOF while parsing', ('<string>', 1, 1, ')'))

```

which includes the character number where the error took place.
> 17 votes

# Answer
## Python, ~~79~~ 77 Bytes

```
lambda m:[sum([2*(z<')')-1for z in m][:g])for g in range(len(m)+1)].index(-1)

```

There is probably a better way to do this, but I'm out of ideas. Also this is my first post on codegolf.

Thanks to @Erwan. for golfing off 2 bytes.
> 8 votes

# Answer
## CJam, 10 bytes

```
0l'_*:~1#)

```

or

```
0l'_*~]1#)

```

or (credits to Dennis)

```
Wl+'_*:~1#

```

Test it here.

### Explanation

As A Simmons already noted, `()` is a lucky choice for CJam since those are the decrement/increment operators, respectively. That means if we're starting from zero we're looking for the step at which Santa reaches floor 1.

```
0   e# Push 0, the initial floor.
l   e# Read input.
'_* e# Riffle the input string with underscores, which duplicate the top of the stack.
:~  e# Evaluate each character, using a map which wraps the result in an array.
1#  e# Find the position of the first 1.
)   e# Increment because we're looking for a one-based index.

```
> 7 votes

# Answer
# C, 55 bytes

```
g;main(f){for(;f;g++)f+=81-getchar()*2;printf("%d",g);}

```

Try it here.

Edit: Not sure why I left an unused variable in there...
> 6 votes

# Answer
# MATL, ~~12~~ 11 bytes

*1 byte saved using Dennis' idea of computing -1 raised to the input string*

```
1_j^Ys0<f1)

```

**Try it online!**

```
1_         % number -1
j          % take string input
^          % element-wise power. This transforms '('  to 1 and ')' to -1
Ys         % cumulative sum
0<         % true for negative values
f          % find all such values
1)         % pick first. Implicit display

```
> 5 votes

# Answer
# Python 3, 59

Saved 3 bytes thanks to grc.

I really dislike doing manual string indexing in Python. It feels so wrong.

```
def f(x):
 c=q=0
 while-~c:c+=1-(x[q]>'(')*2;q+=1
 return q

```
> 5 votes

# Answer
## Labyrinth, 18 bytes

```
+(+"#(!@
:  :
%2_,

```

Try it online! This answer was the result of collaborating with @MartinBüttner.

### Explanation

The usual Labyrinth primer (I say "usual", but I actually rewrite this every time):

* Labyrinth is a stack-based 2D language, with execution starting from the first valid char (here the top left). At each junction, where there are two or more possible paths for the instruction pointer to take, the top of the stack is checked to determine where to go next. Negative is turn left, zero is go forward and positive is turn right.
* The stack is bottomless and filled with zeroes, so popping from an empty stack is not an error.
* Digits in the source code don't push the corresponding number – instead, they pop the top of the stack and push `n*10 + <digit>`. This allows the easy building up of large numbers. To start a new number, use `_`, which pushes zero.

This code is a bit weird since, for golfing purposes, the main loop combines two tasks into one. For the first half of the first pass, here's what happens:

```
+(+             Add two zeroes, decrement, add with zero
                This leaves -1 on the stack
"               NOP at a junction. -1 is negative so we try to turn left, fail, and
                turn right instead.
:               Duplicate -1

```

Now that the stack has been initialised with a -1 on top, the actual processing can start. Here's what the main loop does.

```
,               Read a byte of input
_2%             Take modulo 2.
:+              Duplicate and add, i.e. double
(               Decrement
                This maps "(" -> -1, ")" -> 1
+               Add to running total
"               NOP at a junction. Go forward if zero, otherwise turn right.
:               Duplicate the top of the stack

```

The last duplicate adds an element to the stack for every iteration we perform. This is important because, when we hit zero and go forward at the NOP, we do:

```
#               Push stack depth
(               Decrement
!               Output as num
@               Terminate

```
> 5 votes

# Answer
## Pyth, 13 bytes

```
f!hsm^_1Cd<zT

```

Explanation

```
              - autoassign z = input()
f             - First where V returns Truthy.
          <zT -     z[:T]
    m         -    [V for d in ^]
        Cd    -     ord(d)
     ^_1      -      -1**^
   s          -   sum(^)
 !h           -  not (^+1)

```

Try it here

### Old algorithm, 15 bytes

```
f!h-/J<zT\(/J\)

```

Explanation:

```
                - autoassign z = input()
f               - First where V returns Truthy.
      <zT       -      z[:T]
     J          -     autoassign J = ^
    /    \(     -    ^.count("(")
           /J\) -    J.count(")")
   -            -   ^-^
 !h             -  not (^+1)

```

Try it here

Or if allowed to use chars other than `(` and `)`, **9 bytes** (moving pre-processing to input)

```
f!.v+<zT1

```

Explanation

```
          - autoassign z = input()
f         - First where V returns Truthy.
     <zT  -     z[:T]
    +   1 -    ^+"1"
  .v      -   eval(^)
 !        -  not ^

```

Try it here
> 4 votes

# Answer
## JavaScript (ES6), 58 bytes

```
f=(s,t=s)=>s<')'?f(s.replace('()',''),t):t.length-s.length+1

```

Works by recursively removing a pair of matching `()`s until the first character is a `)`. Warning: Don't try this on strings that don't have enough `)`s. Example:

```
((()())()))
((())()))
(()()))
(()))
())
)

```

At this point it sees that 12 characters were deleted in total so that the answer is 13.
> 4 votes

# Answer
## Grep+AWK, 51 Bytes

```
grep -o .|awk '/\(/{s++}/)/{s--}s<0{print NR;exit}'

```

The `grep` command places each character on a new line.
> 4 votes

# Answer
# Oracle SQL 11.2, ~~160~~ 159 bytes

```
SELECT MIN(l)FROM(SELECT l,SUM(m)OVER(ORDER BY l)p FROM(SELECT LEVEL l,DECODE(SUBSTR(:1,LEVEL,1),'(',1,-1)m FROM DUAL CONNECT BY LEVEL<=LENGTH(:1)))WHERE p=-1;

```

Un-golfed

```
SELECT MIN(l) -- Keep the min level
FROM(
  SELECT l,SUM(m)OVER(ORDER BY l)p -- Sum the () up to the current row
  FROM(
    SELECT LEVEL l,DECODE(SUBSTR(:1,LEVEL,1),'(',1,-1)m -- ( equal 1 and ) equal -1
    FROM DUAL
    CONNECT BY LEVEL<= LENGTH(:1)
  )
)
WHERE p=-1 -- Keep the rows where the () sum is equal to -1

```
> 3 votes

# Answer
# Retina, ~~22~~ 21

```
!M`^((\()|(?<-2>.))+

```

Try it online or try the big test case. (The URL is large for the big test case, let me know if it breaks for you, seems OK in chrome.)

1 byte saved thanks to Martin!

We match the first set of balanced parentheses and extract it, then we count the number of times the empty string will match that result. I'm not sure if this is the nicest way to do this in Retina, particularly if PCRE mode makes it shorter, but using the `$#_` replacement seemed to be longer because of off by one errors and the problem of having more than one match.

This algorithm causes odd behaviour for invalid input, it essentially assumes that if Santa doesn't make it to the basement, he mysteriously teleports there after the other movements.
> 3 votes

# Answer
# Mathematica, ~~62~~ 55 bytes

```
Position[Accumulate[(-1)^ToCharacterCode@#],-1][[1,1]]&

```

All of the long function names! Works similarly to Simmons' CJam answer.
> 3 votes

# Answer
## Python, 44 bytes

```
f=lambda s,i=1:i and-~f(s[1:],i-1+2*(s<')'))

```

The floor `i` starts at `1` so that we terminate on `i` being the falsey value `0`. If not terminated, recursively add one to result with the first character removed and the floor number updated based on that character.
> 3 votes

# Answer
# Ruby, 47 bytes

Anonymous function.

```
->s{i,l=-1,0;l+=s[i+=1]>?(?-1:1 while l>-1;i+1}

```
> 3 votes

# Answer
## APL, 18 chars

```
{1⍳⍨¯1=+\¯1*')'=⍵}

```

In English:

* `¯1*')'=⍵`: -1 where input =")", 1 otherwise;
* `+\`: running sum;
* `1⍳⍨¯1=`: find the index of the first -1.
> 3 votes

# Answer
# Husk, ~~11~~ 10 bytes

neat backwards solution with 1/2 literal from @Dominic van Essen

```
€.∫mȯ-.%2c

```

```
            -- implicit last parameter (⁰ variable)
         c  -- get char code
       %2c  -- get the remainder of int div 2 `( => 0, ) => 1`
     -.%2c  -- subtract 1/2 from either that 1 or 0
    ȯ-.%2c  -- compose the 3 functions [-. %2 c] together (map only takes one function)
  ∫mȯ-.%2c  -- map over all the chars and get cumulative sum
€.∫mȯ-.%2c  -- find the first index where the element is equal to 1/2

```

old solution: https://pastebin.com/Ut8Wne6w

Try it online!
> 3 votes

# Answer
# CJam, ~~12~~ 10 Bytes

```
0q{~_}%1#)

```

Try it here.

Two bytes saved thanks to Martin.

Explanation:

```
0              Load 0 onto the stack
 q             Load input onto the stack without evaluating
  {  }       Code block
   ~_          Evaluate the next command and duplicate the top stack element. The format of the question is good for CJam and Golfscript since ) and ( are increment and decrement operators (though the wrong way round).
        %      Map this code block over the string. This yields an array of Santa's floor positions
         1#   Find the first instance of a 1, since decrement and increment are swapped
           )  Fix the off-by-1 error caused by zero-indexing

```
> 2 votes

# Answer
## Lua, ~~92~~ ~~89~~ 87 Bytes

It takes in a command-line argument.

**Edit: Saved 3 Bytes**

**Edit: Saved 2 bytes, and corrected a bug that could happen on edge cases, it now outputs via its exit code**

```
r=0i=0(...):gsub(".",function(c)i=i+1r=r+(c==")"and-1or 1)if r<0then os.exit(i)end end)

```

### Ungolfed

```
r,i=0,0                     -- set r (the actual floor), and i(the character count)
(...):gsub(".",function(c) -- apply an anonymous functions on each character of the input
  i,r=i+1,                  -- increment i
      r+(c==")"and -1 or 1) -- decrement r if c==")", increment it otherwise
  if r<0 then os.exit(i)end -- if r==-1, exit and output the current index
end)

```
> 2 votes

# Answer
### Perl, 34 + 1 = 35 bytes

```
$.+=s+.+++s+\)++while")"gt$_;$_=$.

```

Thanks to Dennis for some tips.

Run with the `-p` flag. It works in Perl 5.10, but later versions need a space here: `++ while`

Older, ungolfed version:

```
$_ = <>;                # get a line of input
while ($_ lt ')') {     # while it begins with a (
    s/.//;              # remove the first (
    s/\)//;             # remove the first )
    $i += 2;            # increase index by 2
}
print $i + 1;           # print the position

```
> 2 votes

# Answer
# Javascript, 117 bytes

```
o=f=0;i=prompt().split('');for(c in i){switch (i[c]){case '(':f++;break;case ')':f--;if(f<0){alert(o+1);i=[];}}o++;}
```

Ignores other characters. Uses `prompt` and `alert`.
> 2 votes

# Answer
# Befunge 25 bytes

Outputs in unary. This starts you on floor one, and will go until 0.

```
1<\1_v#:+-*2%2~
:#._@>$1>

```
> 2 votes

# Answer
## Javascript, 57 bytes

```
p=>{c=0;for(i in p){c+=p[i]==')'?-1:1;if(c<0)return+i+1}}

```

Pretty simple, just iterates over input, incs if '(' decs if ')'. Returns on first negative.
> 2 votes

# Answer
## Racket (102)

```
(λ(s)(let l((c 0)(b 0)(s(string->list s)))(if(> 0 b)c(l(+ 1 c)((if(eqv?(car s)#\()+ -)b 1)(cdr s)))))

```

**Ungolfed**

```
(λ (input)
  (let loop ((count 0) (balance 0) (chars (string->list input)))
    (if (> 0 balance)
        count
        (loop (+ 1 count)
              ((if (eqv? (car chars) #\() + -) balance 1)
              (cdr chars)))))

```
> 2 votes

# Answer
## /kona, ~~23~~ 21 bytes

2 bytes saved by removing unnecessary parentheses.

```
{1+(+\1 -1"()"?x)?-1}

```

Usage:

```
k){1+(+\1 -1"()"?x)?-1} "())"
3

```
> 2 votes

# Answer
# BQN, 14 bytes

```
1+0⊐˜1+`¯1⋆-⟜@

```

Anonymous tacit function that takes a string and returns an integer wrapped in a unit array. Prepend  to get a plain integer instead.

Run it online!

### Explanation

```
1+0⊐˜1+`¯1⋆-⟜@
           -⟜@  Subtract null character from each character (yields list of charcodes)
        ¯1⋆      Take -1 to the power of each
     1+`         Scan with addition (cumulative sum), starting at 1
  0⊐˜            Find the index of the first 0
1+               Add 1 because BQN uses 0-based indexing

```
> 2 votes

# Answer
## PowerShell, ~~75~~ ~~65~~ 62 bytes

```
[char[]]$args[0]|%{$c+=(1,-1)[$_%40];$d++;if($c-lt0){$d;exit}}

```

Uses a similar technique as on Parenthifiable binary numbers to loop through all the input characters, keeping a running `$c`ounter of `+1` for each `(` and `-1` for each `)`, then testing whether we've hit negative (i.e., we're in the basement).

Edit - saved 10 bytes by iterating over the actual characters rather than their indices
Edit 2 - saved 3 additional bytes by swapping equality check for modulo so casting is implicit
> 1 votes

# Answer
# C, 73 bytes

```
main(f,c){f=c=0;for(;f!=-1;c++){f+=1-((getchar()&1)<<1);}printf("%d",c);}

```

Expects input on STDIN; no characters other than `(` and `)` may appear in the input (at least until we've reached the answer). Input *must* be ASCII.

Emits the answer on STDOUT.

Uses the 1-bit difference between the ASCII for `(` and `)`.

```
/* old-style arguments, implicitly int */
main(x, f)
{
    /* c is our character counter, f is the floor*/
    c = f = 0;
    /* increase c while f is not -1 */
    for (;f != -1; c++) {
        /* use difference in LSB to add one for (, subtract one for ) */
        f += 1-((getchar()&1)<<1);
    }
    /* answer */
    printf("%d", c);
}

```

Nicely-formatted version:
> 1 votes

# Answer
## Python (3.5), ~~78~~ ~~71~~ 62 bytes

a recursive solution

```
f=lambda s,p=0,v=0:p if v<0else f(s[1:],p+1,v+2*(s[0]<')')-1)

```

it's similar to this solution for mini golf

we can assume santa always reach the basement
> 1 votes

# Answer
# Javascript (ES6), ~~68~~ 67 bytes

```
(s,r,f=0)=>s.split``.map((l,i)=>(f+=l=='('?1:-1,f<0?r=r||++i:0))&&r

```

Takes input as first argument

# Explanation

```
(s, r, f=0)                                  //Gets string, declares r and f to equal undefined and 0
         =>
            s.split``                        //Splits string into character array
            .map(                            //Loops over array
                 (l, i)=>(
                         f +=                //Increment f
                         l=='(' ? 1 : -1,    //By either 1 or -1 depending on character
                         f<0 ?               //If the floor is less than 0
                         r=r||++i            //And is first time below, r equals index (+1 to make it '1 indexed not 0')
                         : 0)
                         &&r                   //Return index

```
> 1 votes

# Answer
# Thunno 2 `B`, 6 bytes

```
u@ṡuȮ⁺

```

Try it online!

#### Explanation

```
u@ṡuȮ⁺  # Implicit input
        # Cast to ordinals
u@      # (-1) ** each
  ṡ     # Cumulative sums
   uȮ   # Index of -1
     ⁺  # Increment
        # Implicit output

```
> 1 votes

# Answer
## Perl, 40 + 1 = 41 bytes

```
$y++,($i+=/\(/*2-1)<0&&last for/./g;$_=$y

```

Requires the `-p` flag:

```
$ perl -pe'$y++,($i+=/\(/*2-1)<0&&last for/./g;$_=$y' <<< '()())'
5
$ perl -pe'$y++,($i+=/\(/*2-1)<0&&last for/./g;$_=$y' 1797.txt
1797

```

Assumes valid input.

How it works:

```
                                           # -p read line by line into $_ and auto prints at the end
        $y++,                              # Counter for steps taken
             ($i+=/\(/*2-1) < 0            # The match /\(/ will give 1 or 0 in a numeric context 1 for `(` and 0 for anything else
                                           # times it by 2 and subtracting -1 will yield 1 or -1
                               && last     # End the iteration if $i < 0
for/./g;                                   # Iterate over each items in the input
                                      $_=$y# Print the output

```
> 0 votes

# Answer
# Pip, 16 bytes

```
T0>Yy+vE APOaUoo

```

Attempt This Online! Or, here's a 17-byte equivalent in Pip Classic: Try it online!

### Explanation

```
T0>Yy+vE APOaUoo
                  y is "" (equal to 0 in numeric contexts); o is 1; a is cmdline arg
T                 Till the following condition is truthy...
          POa      Pop the first character from the argument
         A         Get its ASCII code
      vE           -1 to that power
    y+             Plus y
   Y               Yank back into y
 0>                Test if the new value of y is negative
                  ...loop:
             Uo    Increment o
               o  After the loop, autoprint the final value of o

```
> 0 votes

---
Tags: code-golf
---


title: Cutting a Circular Pizza Vertically

text:
# Question
Title: Cutting a Circular Pizza Vertically
Most people would cut circular pizzas into circular sectors to divide them up evenly, but it's also possible to divide them evenly by cutting them vertically like so, where each piece has the same area (assume the pizza has no crust):

# Challenge

Your task is to make a program or function that takes a positive integer \\$n\\$ where \\$2 \le n \le 100\\$ that represents how many vertical slices a circular pizza with a radius of \\$100\\$ will be cut into as input and outputs the horizontal distance from the center of each cut (which will make each slice have the same area) from left to right (or right to left, since the cuts are symmetrical), rounded to the nearest integer.

Note that this will probably require more than just a simple formula.

# Rules

* Input and output can be in any convenient format.
* This is , so the shortest code in bytes in each language wins.

# Test cases

| Input | Output |
| --- | --- |
| 2 | \[0\] |
| 3 | \[26, 26\] |
| 4 | \[40, 0, 40\] |
| 5 | \[49, 16, 16, 49\] |
| 6 | \[55, 26, 0, 26, 55\] |
| 7 | \[60, 34, 11, 11, 34, 60\] |
| 8 | \[63, 40, 20, 0, 20, 40, 63\] |
| 9 | \[66, 45, 26, 9, 9, 26, 45, 66\] |
| 10 | \[69, 49, 32, 16, 0, 16, 32, 49, 69\] |
| 50 | \[90, 83, 78, 73, 69, 64, 60, 57, 53, 49, 46, 42, 39, 35, 32, 29, 25, 22, 19, 16, 13, 9, 6, 3, 0, 3, 6, 9, 13, 16, 19, 22, 25, 29, 32, 35, 39, 42, 46, 49, 53, 57, 60, 64, 69, 73, 78, 83, 90\] |
| 82 | \[92, 88, 84, 81, 78, 75, 72, 69, 67, 64, 62, 59, 57, 55, 52, 50, 48, 46, 44, 41, 39, 37, 35, 33, 31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 12, 10, 8, 6, 4, 2, 0, 2, 4, 6, 8, 10, 12, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 44, 46, 48, 50, 52, 55, 57, 59, 62, 64, 67, 69, 72, 75, 78, 81, 84, 88, 92\] |
| 97 | \[93, 89, 86, 83, 80, 77, 75, 73, 70, 68, 66, 64, 62, 60, 58, 56, 54, 52, 50, 48, 46, 44, 43, 41, 39, 37, 36, 34, 32, 30, 29, 27, 25, 24, 22, 20, 19, 17, 15, 14, 12, 11, 9, 7, 6, 4, 2, 1, 1, 2, 4, 6, 7, 9, 11, 12, 14, 15, 17, 19, 20, 22, 24, 25, 27, 29, 30, 32, 34, 36, 37, 39, 41, 43, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 73, 75, 77, 80, 83, 86, 89, 93\] |
| 100 | \[93, 90, 86, 83, 81, 78, 76, 73, 71, 69, 67, 64, 62, 60, 59, 57, 55, 53, 51, 49, 47, 46, 44, 42, 40, 39, 37, 35, 34, 32, 30, 29, 27, 25, 24, 22, 21, 19, 17, 16, 14, 13, 11, 9, 8, 6, 5, 3, 2, 0, 2, 3, 5, 6, 8, 9, 11, 13, 14, 16, 17, 19, 21, 22, 24, 25, 27, 29, 30, 32, 34, 35, 37, 39, 40, 42, 44, 46, 47, 49, 51, 53, 55, 57, 59, 60, 62, 64, 67, 69, 71, 73, 76, 78, 81, 83, 86, 90, 93\] |

# Answer
# , 74 bytes (partial, probabilistic solution)

A bit of a silly Monte Carlo solution based on the fact that the histogram of eigenvalues of an \\$N \times N\\$ symmetric matrix with Gaussian entries converges to a semicircle with base \\$\[-2\sqrt{N}, 2\sqrt{N}\]\\$ as \\$N \rightarrow \infty\\$.

Taking \\$N = 50^2\\$, this is the semicircle with base \\$\[-100, 100\]\\$. By a result known as eigenvalue rigidity, the eigenvalue quantiles are all within \\$\sim 50/N\\$ of the corresponding quantiles of the semicircle.

Hence, we solve this problem by computing the eigenvalues of a \\$50^2 \times 50^2\\$ matrix with Gaussian entries and finding the quantiles from \\$1/n\\$ to \\$(n-1)/n\\$ of the sample:

```
\(n)round(abs(quantile(eigen(matrix(rnorm(50^4),50^2),T)[[1]],1:(n-1)/n)))

```

This is obviously not an exact solution, and when a true value is close to the form \\$k + 0.5\\$ for integer \\$k\\$, the estimate can be off the true rounded value by \\$\pm 1\\$.

It also takes a long time to find the eigenvalues of a \\$ 50^2 \times 50^2\\$ matrix, so in the demonstration I can only run two test cases before timing out.

Attempt This Online!
> 6 votes

# Answer
# JavaScript (V8), 87 bytes

Prints the results.

```
n=>{for(t=0,x=w=1e6;x--+w;t*n>15708e8&&print((x*x)**.5/1e4+.49|(t=0)))t+=(w*w-x*x)**.5}

```

Try it online!

**NB**: This gives the same results as the OP for all test cases. We may disagree for some other inputs, but I've no way of knowing.

### Commented

```
n => {                // n = input
  for(                // loop:
    t = 0,            //   start with t = 0
    x = w = 1e6;      //   and x = w = 1000000
    x-- + w;          //   stop when x = -w (decrement x afterwards)
    t * n > 15708e8   //   if t * n > round(pi / 2 * w² / 10^8) * 10^8 ...
    &&                //
    print(            //   ... print floor(abs(x) * 100 / w + 0.49)
      (x * x) ** .5   //
      / 1e4 + .49     //
      | (t = 0)       //   and reset t to 0
    )                 //
  )                   //
    t +=              //   at each iteration, add to t:
      (w * w - x * x) //     sqrt(w² - x²)
      ** .5           //
}                     //

```
> 5 votes

# Answer
# Python, ~~225~~ ~~202~~ 152 bytes

*-23 bytes thanks to @solid.py*

```
lambda n:[h(pi*abs(a/n-.5))//2for a in range(1,n)]
def h(a,p=0):
 while(d:=a-p*(r:=sqrt(1-p*p))-asin(p))>1E-9:p+=d/r/2
 return 200*p+1
from math import*

```

Attempt This Online!

Uses Newton's method to find the inverse of the formula \\$ \int\_0^h 2 \sqrt{1-h²} dh = h \sqrt{1-h²} + \sin^{-1}(h)\\$ for the area of a slice of height h from the center in a circle of radius 1.
> 3 votes

# Answer
# , ~~84~~ 83 bytes

```
\(n,r=2e8)for(x in -r:r)if((F=F+(r^2-x^2)^.5)>pi*2e16/n)F=!print(abs(round(x/2e6)))

```

Attempt This Online! (but it will time-out before completing), or Attempt a less-accurate version with only 4 million x-axis steps.

Straightforward loop-over-x-values approach, not as elegant as Damian Pavlyshyn's probabilistic approach in R, but produces a single defined output for any input `n`.

Calculates the area-so-far in 400 million x-axis steps across the pizza, outputting the rounded x-axis value each time it hits the intended slice-area, and resetting the area-so-far back to zero.
Setting the area-so-far back to zero, instead of subtracting the slice-area and keeping the remainder for the next slice, is rather inaccurate, and so necessitates the huge number of x-axis steps to match all the test-cases.
Subtracting the slice-area at each step would require ≈10,000x less steps to achieve the required accuracy, but costs 5 bytes more.
> 3 votes

# Answer
# JavaScript (V8), 93 bytes

```
n=>{q=2;for(S=x=1;S;x-=1e-6)q<(S+=(1-x*x)**.5/Math.PI*2e-6*n)&&q++*print((x*x)**.5*100+.5|0)}

```

Try it online!
> 2 votes

# Answer
# Charcoal, 69 bytes

```
Ｎθ≔ＸＥ⊗φ⁻⊕⊗ι⊗φ²ηＵＭηΣ⁻¹÷⁺ιηＸ⊗φ²≔ΣηζＵＭη↨…ηκ¹Ｉ↔÷⁻⁺⁴φ⌕ＡＥΦηκ⁻÷×θιζ÷×θ§ηκζ¹χ

```

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

```
Ｎθ

```

Input the desired number of slices.

```
ＸＥ⊗φ⁻⊕⊗ι⊗φ²η

```

Generate a list of odd numbers from `-1999` to `1999` and square them.

```
ＵＭηΣ⁻¹÷⁺ιηＸ⊗φ²

```

For each square odd number, add all of the square odd numbers to it, and count how many are less than 4 million.

```
≔Σηζ

```

Get the total "area".

```
ＵＭη↨…ηκ¹

```

Get the cumulative area at each potential slice point. Note that there are still `2000` points at this stage, with coordinates from `-99.95` to `99.95` in steps of `0.1`.

```
Ｉ↔÷⁻⁺⁴φ⌕ＡＥΦηκ⁻÷×θιζ÷×θ§ηκζ¹χ

```

Find the slice points where the area increases to the next fraction of the total area and calculate the nearest integer slice points.
> 2 votes

# Answer
# Perl 5, 95 bytes

```
sub{($n,$c,$s)=@_;map$-=.49+abs$_/100,grep$c<($s+=$n/15708*sqrt 1-$_**2/1e8)-1&&++$c,-1e4..1e4}

```

Try it online!
> 1 votes

# Answer
# Python, 146 bytes

```
lambda n:[round(min(range(900),key=lambda d:abs(tau/n*k+sin(a:=2*acos(d/900))-a))/9)for k in[[i,n-i][i>n/2]for i in range(1,n)]]
from math import*

```

Attempt This Online!
> 1 votes

# Answer
# Python, ~~126~~ 125 bytes

```
from math import*
def f(q,m=0):
 for i in range(1,q):exec('m=sin(pi/q*i-pi/2-m*sqrt(1-m*m));'*99999);print(abs(round(m*100)))

```

Attempt This Online!

Uses an iterative approach to converge to the true answer. This version is extremely slow and will time out.

---

# Python, ~~134~~ 133 bytes

```
from math import*
def f(q,m=0):
 for i in range(1,q):
  for j in[0]*99999:m=sin(pi/q*i-pi/2-m*sqrt(1-m*m))
  print(abs(round(m*100)))

```

Attempt This Online!

This version will not time out.
> 0 votes

---
Tags: code-golf, math, geometry, trigonometry
---


# Question
Title: Minimal maximum byte for Turing Completeness
## Summary

We already have a challenge for the minimal number of characters for Turing completeness. But what about the minimal maximum byte?

## Challenge

For a language of your choice, find a subset of characters that allows your language to be Turing complete with the minimal maximum byte value.

## Example

If your language is using the UTF8 code page and Turing complete using only the characters `abcd()`, these characters have the byte values `97, 98, 99, 100, 40, 41`, and the maximum there is `d = 100`, so your score would be 100.

## Scoring

Your score is the maximum byte value of your Turing complete subset, expressed in the code page of your language's interpreter. For most languages this will be either LATIN-1 or UTF8, but if your language uses a different code page (such as Jelly) use that to score instead.

In the unlikely event that you require multibyte characters to be Turing complete, just use the maximum byte in the multibyte sequence to score. For example, if your UTF8 language required `Ȧ`, this is encoded as the literal byte sequence `200, 166`, so it would score 200.

The lowest score wins.

## Notes

* The minimum score is 0, the maximum is 255.
* For some languages (cough) this challenge will be trivial to score low on. I urge you to upvote interesting answers over trivial ones.
* Provide an explanation of why your subset is Turing complete.
* Your subset only needs to be Turing complete, it does not need to be able to use every feature of the language.

# Answer
> 18 votes
# Haskell, score 61 (`=`)

Characters used: `!#$%&()=`

The SKI combinator calculus can be implemented in Haskell with nothing but basic function definition, using `!#%&` as identifiers. Infix function application `$` is used to save on parentheses and strip down one character from both **`S`** and **`fix`**. Finally, **`K`** only takes two arguments and can be more shortly defined as an infix operator.

### `S` combinator: `s x y z = x z (y z)`

```
(!)(#)(%)(&)=(#)(&)$(%)(&)

```

### `K` combinator: `k x y = x`

```
(!)#($)=(!)

```

### `fix` combinator: `fix f = f (fix f)`

```
(&)(!)=(!)$(&)(!)

```

Since Haskell is a strongly typed language, the fixed-point combinator **`fix`** is needed in order to make (typed) combinatory logic Turing-complete.

The **`I`** combinator is not strictly required since it is extensionally equivalent to **`SKK`**, but it can be defined as `(*)(!)=(!)`.

### Try it online!

# Answer
> 17 votes
# Python 2 with exit code, 102 (`f`)

```
def TM_SIM(TRANSITIONS, STATE, TAPE=[], HEAD_POS=0):
	TAPE += ["X"]
	HEAD_POS += HEAD_POS < 0

	SYMBOL = TAPE[HEAD_POS]
	STATE, NEW_SYMBOL, HEAD_DIRECTION = TRANSITIONS[(STATE, SYMBOL)]

	TAPE[HEAD_POS] = NEW_SYMBOL
	HEAD_POS += HEAD_DIRECTION

	STATE == "REJECT" < 1/0
	STATE != "ACCEPT" == TM_SIM(TRANSITIONS, STATE, TAPE, HEAD_POS)

```

Try it online!

This code limits itself to the keyword `def` for highest character `f`. The function definition is used for looping via recursion. Python's logical short-circuiting is used for control flow, avoiding the need for a keyword like `if`, `and`, `or`, or `while`. For example, the recursive call in `STATE != "ACCEPT" == TM_SIM(...)` does not happen if we're in the accept state -- because the first inequality already fails, Python moves on without evaluating further.

Because none of the usual output method work (`print`, `return`, `exit`, etc), we return via exit code by terminating with or without error. So, this code is limited to decision problems. In practice, large inputs will give a stack overflow ("maximum recursion depth exceeded").

The code shown is a function simulating an arbitrary Turing machine that's given as input, which is of course Turing complete. The TIO shows it tested with a Turing machine that checks palindromes.

We avoid all keywords except the `def`. Since the only characters bigger than lowercase in letters in byte value are `{|}~`, it was easy to do without them too. For clarity, the variables in the code have been given readable names, using uppercase since these are smaller than all lowercase letters. We could get rid of these and many other symbols, though this of course wouldn't affect the score.

# Answer
> 15 votes
# C (gcc), score=61 (`=`)

```
$01234567;=

```

This abuses the linker by forming a machine language program that spans several scalar variables and avoids array characters such as `[]{}`.

The following is an example of a "Hello, World!" "program" that should work on Linux and OSX for x86 and x86\_64.

```
$=01672007152;$$=011000000000;$$$=015733066145;$$$$=015725620054;$$$$$=04131066162;$$$$$$=010060030412;$$$$$$$=02141007620;$$$$$$$$=013100000000;$$$$$$$$$=015224251132;$$$$$$$$$$=026024655401;$$$$$$$$$$$=020063250004;$$$$$$$$$$$$=030304142203;$$$$$$$$$$$$$=037777630536;$$$$$$$$$$$$$$=012625655307;$$$$$$$$$$$$$$$=01134122;$$$$$$$$$$$$$$$$=0503601000;$$$$$$$$$$$$$$$$$=06127257132;$$$$$$$$$$$$$$$$$$=01700330300;$$$$$$$$$$$$$$$$$$$=0141405;

```

Try it online!

# Answer
> 10 votes
# Whitespace, score = 32

Characters:  `\t\n` (chrs 32 9 10)

The only legal chars in the language.

# Answer
> 10 votes
# PHP, Score = 82 (`R`).

## Rationale:

Let's start at the end of the ASCII range, and work backwards until we find a character that's required for PHP.

PHP is case-sensitive only for user-defined things (variable names, constants), and is case-insensitive for all other things, so we can ignore the lowercase range.

Other than lowercase characters, the only characters above the uppercase range are:

* 0x7f - unused.
* `~` \- used only for bitwise negation, unnecessary for Turing completeness.
* `{` and `}` \- used for blocks, but PHP has an "alternative syntax" for control structures that doesn't use characters above the uppercase range.
* `|` \- used for boolean OR (`|`, `|=`, etc), unnecessary for Turing completeness, and for logical OR (`||`, `||=`, etc), which has an alternate text form `OR`.
* ``` \- used only for external command execution, unnecessary for Turing completeness, and anyway there are alternatives (`EXEC()`, `PASSTHRU()`, `SYSTEM()`, etc)
* `_` \- used in many library function names and all compile-time constants, but not used by any keywords, so, since methods can be called dynamically, we can call methods that contain underscores by replacing them with `CHR(95)`.
* `^` \- used only for bitwise XOR, and in regexes, neither required for Turing completeness.
* `[` and `]` \- used for array indexing, which poses a problem, but `array_pop` and friends can be used instead.
* `\` is used for character escapes, unnecessary for Turing completeness, and escaped characters can be generated using `CHR()` and similar tricks anyway.

This means our max must lie in the uppercase characters.

We could trivially use `eval()` and `chr()` to evaluate any string of numbers as PHP code, which would give us a max character of `V`... but I think we can do better!

If we can do everything brainfsck can, then it'll be Turing complete, so let's write one. I'll replace the `[ ]` square braces of normal brainfsck with `( )` round braces, just so I can have the brainfsck program inline without using any high characters.

## Proof of concept:

```
<?PHP
// Create function refs, for those which have characters too high.
$FILL = 'ARRA' . CHR(89) . CHR(95) . 'FILL'; // Array_fill to create the tape.
$CHOP = 'ARRA' . CHR(89) . CHR(95) . CHR(83) . 'LICE'; // Array_slice for array indexing.
$POP = 'ARRA' . CHR(89) . CHR(95) . CHR(83) . 'HIF' . CHR(84); // Array_shift for array indexing.
$DEPOP = 'ARRA' . CHR(89) . CHR(95) . CHR(83) . 'PLICE'; // Array_splice for array inserting.

$LEN = CHR(83) . CHR(84) . 'RLEN'; // Strlen
$LOP = CHR(83) . CHR(84) . 'R' . CHR(95) . CHR(83) . 'PLI' . CHR(84); // Str_split

// "Hello world!" - note using round braces instead of square in the brainfsck code.
$IN =  (">+++++++++(<++++++++>-)<.>+++++++(<++++>-)<+.+++++++..+++.>>>++++++++(<++++>-)<.>>>++++++++++(<+++++++++>-)<---.<<<<.+++.------.--------.>>+.>++++++++++.");
$INLEN = $LEN($IN);
$IN = $LOP($IN);

// Init tape with 10 zeros (add more for longer tape).
$A = $FILL(0,10,0);

// Set $AA ptr to first cell of tape.
$AA = 0;

FOR ($I = 0; $I < $INLEN; $I++):
    // Extract element: $CH = $IN[$I].
    $CH = $CHOP($IN, $I);
    $CH = $POP($CH);
    // Increment element at $I.
    //$CH++;
    //$CH = $FN($AA, $I, 1, $CH);

    // Only need one of '+' or '-' for TC if memory wraps.
    IF ($CH == '>'):
        $AA++;
    ENDIF;
    IF ($CH == '<'):
        $AA--;
    ENDIF;

    // Only one of '+' or '-' is critical for Turing completeness.
    IF ($CH == '+'):
        // Increment element: $A[$AA]++;
        $ID = $CHOP($A, $AA);
        $ID = $POP($ID);
        $ID++;
        $DEPOP($A, $AA, 1, $ID);
    ENDIF;
    IF ($CH == '-'):
        // Decrement element: $A[$AA]--;
        $ID = $CHOP($A, $AA);
        $ID = $POP($ID);
        $ID--;
        $DEPOP($A, $AA, 1, $ID);
    ENDIF;

    IF ($CH == ')'):
        $ID = $CHOP($A, $AA);
        $ID = $POP($ID);
        IF ($ID):
            FOR ($LOOP = 1; $LOOP > 0; ):
                $CH = $CHOP($IN, --$I);
                $CH = $POP($CH);
                IF ($CH == '('):
                    $LOOP--;
                ENDIF;
                IF ($CH == ')'):
                    $LOOP++;
                ENDIF;
            ENDFOR;
        ENDIF;
    ENDIF;

    // I/O is non-critical for TC.
    IF ($CH == '.' ):
        $ID = $CHOP($A, $AA);
        $ID = $POP($ID);
        ECHO CHR($ID);
    ENDIF;
ENDFOR;

```

## Possible improvements:

I don't see a way to avoid using `CHR()` for array indexing without using something worse, like backslash, or string manipulation functions that use `S`.

And I don't see a way to avoid `FOR()` for looping back without using something worse like `GOTO`, `WHILE`, or the `{}` of a recursive function definition.

If we can get rid of those two keywords, the next highest is the P in `<?PHP`, which is required, at least in later versions of PHP that deprecate short open tags. However, they have made a commitment that the short echo tag, `<?=` will always be supported, so that could perhaps be exploited to execute arbitrary PHP. Then there are the O's in `ECHO`. However, I/O isn't critical for Turing completeness, so we could just remove that. Then there's the N in `ENDIF`, and the I and F in `IF`, which could be replaced by the ternary operator, `?:`.

But even if there's a way to avoid using any keywords or library functions by name, variables must begin with an alphabetic or underscore character, so I suspect we'll definitely need at least `A`.

# Answer
> 8 votes
# 05AB1E, score: 86

```
+1 .VB

```

These characters have the codepoints `[43,49,32,46,86,66]` in the 05AB1E codepage, of which `V=86` is the maximum.

My answer for the *Fewest (distinct) characters for Turing Completeness* challenge in 05AB1E which I posted just yet is: `+X.VB`. With these 5 bytes, `X=88` would have been the maximum. We avoid the `X` by using `1` and a space instead. After that `V=86` is the maximum.
With the remaining 6 bytes we can:

* `+`: Pops the top two items on the stack, and adds them together
* `1` : Push 1 to the stack
* `.V`: Pops and evaluates the top string as 05AB1E code
* `B`: Pops the top two items on the stack, and does base-conversion

I've tried to get rid of `V`, which would only be possible with `.E` (execute as Python code - `exec`). Now we're using `.V` to evaluate and execute as 05AB1E code, for which we can first create the entire strings with certain single-byte builtins like `J` (join), `«` (append), etc. But if we would use `.E` we can't do that anymore. A potential fix for this is switching from 05AB1E to 05AB1E (legacy). In the legacy version (which is built in Python) we can use `+` to concatenate characters, which isn't possible in the new version (which is built in Elixir). Unfortunately, the `.E` builtin is (evaluate as Python code - `eval`) in the legacy version, and `.e` is `exec`. With just `eval` we unfortunately can't do everything we want, like checking if the input is a prime number. (Maybe we can, but my Python knowledge is too limited for that. If someone knows a piece of Python 3 code which can be wrapped within `eval("...")` and will check if the `input()` is a prime number, lmk.) And the `e` in `.e` would be even higher than `.V`, so it's pointless to use that instead.

**Try it online:**

Here a few example programs using these six bytes:

Try it online: 2+2.
Try it online: Check if the input is a prime number.
Try it online: Print "Hello, World!".
Try it online: Print the infinite Fibonacci sequence.

# Answer
> 8 votes
# Lenguage, score = 1 ()

```

```

Lenguage only cares about the length of the file, so we can use any character (in this case U+0001).

Yes, I am aware that I can use null bytes, but I wanted to give a fair chance to other people, so I made it 1.

# Answer
> 6 votes
# JavaScript (Node.js), score 62 (`>`)

```
$=>()

```

Check the score online!

Untyped lambda calculus again.

```
I = $=>$
K = $=>$$=>$
S = $=>$$=>$$$=>$($$$)($$($$$))

```

I think this is optimal, because *all* built-ins and keywords are banned now.

# Answer
> 6 votes
# Brainfuck, Score = 93 (`]`).

```
>   Move the pointer to the right.
<   Move the pointer to the left.
+   Increment the memory cell at the pointer.
-   Decrement the memory cell at the pointer.
.   Output the character signified by the cell at the pointer.
,   Input a character and store it in the cell at the pointer.
[   Jump past the matching ] if the cell at the pointer is 0.
]   Jump back to the matching [ if the cell at the pointer is nonzero.

```

I/O is not required for Turing completeness, so `.` and `,` are optional: a canonical Turing machine leaves its calculated answer on the tape. However, I believe all other commands are required, so the highest codepoint the language uses, `]`, *is* required.

There are a number of trivially-similar languages. I'll cover these here as well, unless people feel they are genuinely worthy of separate answers. I have assumed for each language that their commands are case-sensitive unless otherwise stated.

You only need one of the two BF instructions `-` and `+` for Turing completeness. And if the tape/memory is limited and wraps around, then we only require one of `<` and `>`, too. I've updated the below lists to take these into account.

## Identical to BF for our purposes:

### ASCII art-, Score = 93 (`]`).

### BFFB, Score = 93 (`]`) Requires code be a palindrome but uses the same characters as BF.

### LolKek, Score = 93 (`]`).

### Pi, Score = 93 (`]`).

### ReverseFuck, Score = 93 (`]`).

### RRF, Score = 93 (`]`).

### BF-, Score = 93 (`]`).

.

## TrivialBrainfuckSubstitutions:

### ???, Score = 59 (`;`) 45 (`-`) Not quite a trivial substitution, but close enough. Omitted `?`, `;` and `.` as unnecessary for TC.

### Alphuck!, Score = 115 (`s`).

### And then, Score = 122 (`z` from required preamble).

### Anguish, Score = 98 (`U+2062`) 97 (`U+2061`). Omitted `U+2062` as unnecessary for TC.

### ASCII art, Score = 124 (`|`).

### Blub, Score = 117 (`u` from `Blub? Blub!`).

### BrainFNORD, Score = 115 (`s` in `eris`) 112 (`p` in `pineal`). Omitted `eris` and `fnord` as unnecessary for TC.

### btjzxgquartfrqifjlv , Score = 90 (`Z` of `ZXG`).

### Colonoscopy, Score = 123 (`}` of `}}`).

### Fluffle Puff, Score = 116 (`t`) 115 (`s` of `*gasp*`).

### FuckbeEs, Score = 115 (`s`).

### Fuckfuck, Score = 116 (`t` of `b..t`).

### GERMAN, Score = 85 (`U` of `ADDITION` or `SUBTRAKTION`).

### Headsecks, Score = 7 (`U+07`).

### Integral, Score = 120 (`x` of the polynomial expressions).

### LMBC, Score = 125 (`}` of `n\n\\n\>\<" }*/ continue;`).

### Morsefuck, Score = 46 (`.`).

### Omam, Score = 46 (`y` of `this ship will carry`).

### Oof, Score = 111 (`o` of `oooooof`).

### Ook!, Score = 107 (`k` of `Ook? Ook!`).

### oOo CODE, Score = 111 (`o` of `OOo`).

### Pikalang, Score = 117 (`u` from `chu`).

### POGAACK, Score = 112 (`p` from `poock?`).

### PPAP++, Score = 86 (`V` from `I HAVE AN APPLE,` or `I HAVE PINEAPPLE,`).

### Revolution 9, Score = 121 (`y` from `if you become naked`)  118 (`v` from `Revolution 1`).

### RISBF, Score = 47 (`/` of `/+`)

### Roadrunner, Score = 112 (`p` from `MEEp`).

### Ternary, Score = 50 (`2` from `02`).

### There Once was a Fish Named Fred, Score = 119 (`w` from `was`) 114 (`r` from `Fred`).

### tinyBF, Score = 124 (`|`).

### Unibrain, Score = 48 (`0`, needs at least 1 alphanumeric).

### VerboseFuck, Score = 125 (`}` of `}; [... etc]`).

### wepmlrio, Score = 119 (`w`).

### Wordfuck, Score = 32 ( space) or 33 (`!`) depends if chars \< 32 are considered words.

### ZZZ, Score = 122 (`z` from `z-z`).

.

## Turing tarpits:

### Braincrash, Score = 33 (`!`).

### Placement, Score = 63 (`?`).

.

## Binary:

### Binaryfuck, Score = 255 (`U+FF`) *or better???*

### Brainfoctal, Score = 255 (`U+FF`) *or better???*

### CompressedFuck, Score = 255 (`U+FF`) *or better???*

### ShaFuck, Score = 255 (`U+FF`) *or better???*

### Triplet, Score = 255 (`U+FF`) *or better???*

### ZeroBF, Score = 255 (`U+FF`) *or better???*

Now, arguably, the score could be 49 (`1`), or 1 (`U+01`), or 255 (`U+FF`), or whatever. I pick 255.

These each replace the 8 BF command characters with their 3-bit binary equivalents, to give an octal number from 0 to 8. This converts the program to a binary stream of ones and zeroes, which can be represented as ASCII `1` and `0` characters, or as byte values, or as bit values, or as any base you like, hence the three possible scores.

The reason for my score of 255 for the bit-values version of binary BF programs is that `]` typically maps to `111`, so three of them in a row gives you a byte of all 1s, or 255.

It could be argued that you COULD write a Turing machine in these languages which never used three `]` commands in a row. So my score may be less generous than it need be. You can prove this, if you like! :D Until then, I'm scoring them 255.

Well, in the case of ShaFuck, it's more complicated, but still... I don't have proof that it doesn't require a 0xFF byte somewhere, so I'm giving it a score of 255 until proven otherwise.

### Golunar, Score = 59 (`9`) *or better???*

So this is an interesting one. It takes a Unary program (well, any of the above "single character" solutions, and converts it to a decimal string. In this way it is much like the other "binary" options, except it's explicitly stated to be a decimal number, one presumes in ascii.

That means that, if it could be proven that any program (or at least *a* Turing machine program) could be written in Unary that had a length that was describable without any 9s, the score would be able to drop, perhaps even as low as 49 (`1`).

## Replacement by sequences of a single character:

### , Score = 65 (`A`).

### Ecstatic, Score = 33 (`!`).

### Ellipsis, Score = 46 (`.`) or 38 (`U+2026` ellipsis).

### Lenguage, Score = 0 (`U+00`).

### MGIFOS, Score = 42 (`*`).

### Unary, Score = 48 (`0`) or 0 (`U+00`).

These are really just the binary options above, taken as a number that describes the length of a string made by repeating a single character.

## Other weird stuff:

### BF-RLE, Score = 93 (`]`) to 247 (U+F7BFBFBF).

Run-length encoded BF. There are various methods. Base-10 prefix or suffix methods, or indeed any standard base up to 36 gets the same score as regular BF (because `]` is above the uppercase range). Base 37 then typically uses the lowercase range, for a score of 97, and each additional base up to base 62 gets one worse. Bases above 62 need additional non-alphanumeric characters, but these can be selected from those below the lowercase range until those run out at base 114 (assuming 8 characters remain reserved for the BF code itself), and they then get worse by one for each base increase to base-128. After that point, UTF-8 can be used to slow the rise of the limit so that it never hits 255 for any base within the limit for UTF-8's ability to represent (some 4 million).

## I dunno:

### K-on Fuck

### ( ͡° ͜ʖ ͡°)fuck

These use extended characters I can't be arsed to look up.

# Answer
> 5 votes
# Python 3, score 109 (`m`)

```
lambd :()

```

Check the score online!

We can implement untyped lambda calculus using just these chars:

```
I = lambda a:a
K = lambda a:lambda b:a
S = lambda a:lambda b:lambda d:a(d)(b(d))

```

With the known bound of `m`, we can't use any of `exec`, `eval`, `import`, `for`, `while`, `yield`. `def` is still available, but I doubt it will improve the score because I think making it Turing-complete necessitates the use of `return`.

# Answer
> 5 votes
# Haskell, score ~~95 (`_`)~~ 92 (`\`)

```
i = (\_A -> _A)
k = (\_A -> \_AA -> _A)
s = (\_A -> \_AA -> \_AAA -> (_A _AAA)(_AA _AAA))

```

```
i = (\(!) -> (!))
k = (\(!) -> \(!!) -> (!))
s = (\(!) -> \(!!) -> \(!!!) -> ((!) (!!!))((!!) (!!!)))

```

Untyped lambda calculus. Annoying that Haskell can't have uppercase variable names, oh well.

-3 thanks to xnor

Try it online!

# Answer
> 4 votes
# , score 94 (`^`)

```
 "#%()*+.0123456789:<=]^

```

Check the score online!

The winning J answer for least unique chars uses `u:` (convert charcodes to chars) to construct arbitrary string from integers. I decided to avoid `u` and find a more proper way for TC-ness.

Assuming `^:_` (repeat until converges) is hard to avoid, I decided to build a translation from FRACTRAN, as it looked easy enough to translate to `(number_manipulation)^:_(starting_num)`.

A FRACTRAN program is defined as a sequence of fractions, and it runs like this: given a program `5/3 3/2` and some starting number `n`,

* If `n` is divisible by 3, multiply `n` by 5/3.
* Otherwise, if `n` is divisible by 2, multiply `n` by 3/2.
* (The "otherwise" chain continues for longer programs)
* If `n` did not change in this iteration, halt. Otherwise, move to the start of the program and continue with the updated value of `n`.

The if-then-else constructs can be translated to arithmetic:

```
If a then b else c = (a>0) * b + (a==0) * c
J: (b*(0<a))+c*0=a

```

The if-part says "`n` is divisible by a constant `m`". One would normally use the modulo function `|` for this, but it's way too high in ASCII, so I devised a way to simulate modulo using base conversion:

```
n modulo m = convert n into base m, interpret as base 0 and get an integer back
J: 0#.0 m#:n

```

The then- and else-parts are easy, because they can be simulated using multiply `*`, divide `%`, and self `]`.

So the translation of two-fraction FRACTRAN program `5/3 3/2` looks like this:

```
(((]%3"0)*5*0=0#.0 3#:])+((((]%2"0)*3*0=0#.0 2#:])+(]*0<0#.0 2#:]))*0<0#.0 3#:]))^:(%0)(starting_value)

```

I later changed the `_` (infinity literal) to `(%0)` (reciprocal of zero), getting rid of `_`. Since I can't avoid `^:` itself, the score of `^` is optimal in this approach.

# Answer
> 4 votes
# Julia, Score 63 (`?`)

we can actually get away with no letters, by abusing the fact that === is assignable for some reason. however, without a way to index or create arrays, this is not enough. What gets us closer is tuple unpacking. this allows us to create a sort of "stack" with our one variable. `(===) = (2,(===))` `(===) = (3,(===))` one problem is that we need another variable to unpack the argument into. luckily \ is also assignable, so we can use that as a "register" `(\,===) = (===)` we can then perform some operation on these values and store the result `(===) = (7+\==10,===)`

`(\,===) = (===)` we can conditionaly execute code (and drop some parenthesies) `====(\ ? 1 : 0,===)`

we can reuse names via shadowing, but this comes at the cost of recursion `\ = (\) -> (\) + 3`

fortunately, there's another assignable value `^ = (\) -> (\) < 2 ? (\) : ^((\)-1) + ^((\)-2)`

functions can go on the stack `====(^,===)`

we also have NAND logic via && and ! (curried)
`^ = (^) -> (/) -> !((^)&&(/))`

the biggest problem is I/O, as we can't call any Core or Base functions like print, but luckily we can use the -E flag or the REPL to print the result

# Answer
> 4 votes
# PHP \+ `-r`, score 65 (`A`)

## Explanation

I saw the other PHP answer and felt like it should be possible to reduce that using `create_function` and again abusing the fact that PHP allows functions to be called in a case-insensitive way.

Provided below is a compiler that should compile enough of a subset of PHP (maybe any PHP? I haven't tested exhaustively) using only `$()+.;=A`. This relies on the fact that `$A=A;$A++;print($A);` yields `B` and that `$A=A;$A++;$A++;$A.=A;$A++;$A++;$A++;$A++;$A++;$A++;$A++;print($A);` yields `CH`, any variable that isn't set that is incremented will produce `1` followed by the rest of the natural numbers, and that a function can be called using this string representation of its name (e.g. `$A=CHR;$B=$A(95);` stores `_` in `$B`).

This process means that first `CHR` is stored in `$A`, then the function name `CREATE_FUNCTION` is stored in `$AA` (utilising `$A(...)`) and the body of the function created by `CREATE_FUNCTION` is also built using `$A`.

The TIO link below allows you to provide PHP code to be compiled to this subset (and also executes it via `eval` to confirm it's working).

Try it online!

# Answer
> 3 votes
# Keg, Score = 58

Characters:

`0+-*/():`

Simply the standard subset of TC chars

# Answer
> 3 votes
# C (gcc), score: 110 (`n`)

```
<space>!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmn

```

Because of the trigraphs:

```
??= #
??( [
??/ \
??) ]
??' ^
??< {
??! |
??> }
??- ~

```

and the `main` function has to be defined so, no matter what, `n` has to be used. The ubiquitous semicolon (`;`) is there. And `return` is easily avoided through use of assignment (`=`) since gcc will return the last value assigned of the same type as the function return value. Type `int` is inferred by default for any variable or function definition.

# Answer
> 3 votes
# Wolfram Language (Mathematica), score 62 (`>`)

```
#$&()-./>

```

Using these characters we can implement the SKI combinators:

```
i = #&
k = $&/.$->#&
s = (#//$$//(#//$))&/.$$->#&/.$->#&

```

Try it online!

# Answer
> 3 votes
# Dreaderef (`-1` flag), score 42 (`*`)

Dreaderef is a ZISC; the program is a description of the initial tape contents. Dreaderef programs are typically written with an assembly-like syntax that is then run through a preprocessor to produce a list of integers, but quotes (`"`) can also be used to embed arbitrary data in the form of ASCII values.

The only restrictions on the contents of string literals are that:

* They can't contain newlines.
* For our purposes, they can't contain numbers greater than 42.
* They can't contain negative numbers.

The first two aren't a problem, but the third is. Dreaderef's only arithmetic operators are addition and multiplication, so we have no way to obtain negative numbers without including them when initializing. Additionally, the instruction pointer is stored in cell `-1`, and without accessing it we have no way to do control flow. Thus to achieve Turing-completeness we need to include the `*` byte (which is replaced with an integer from the command-line arguments at initialization time) and stipulate that the user always pass `-1` as an argument.

# Answer
> 2 votes
# Unary, score = 48 (`0`)

Unary only cares about number of `0` in the file.

Inspired by the Lenguage answer

# Answer
> 1 votes
# Java, score: 117 (`u`)

```
0123456789ABCDEF\u

```

In Java, there are a few ways to create a full program:

```
// Regular class with main method (Java 1+):
class M{public static void main(String[]a){/*CODE GOES HERE*/}}

// Interface with main method, where we can remove public (Java 8+):
interface M{static void main(String[]a){/*CODE GOES HERE*/}}

// Exploiting a bug with enum (Java 5 or 6):
enum M{A;{/*CODE GOES HERE*/}}

// Creating a Java AWT GUI application with Applet:
class M extends java.applet.Applet{public void paint(java.awt.Graphics x){/*CODE GOES HERE*/}}

// Creating a JavaFX GUI application with Application:
class M extends javafx.application.Application{public void start(Stage stage){/*CODE GOES HERE*/}}

// Any of the above, but with \uHEXA escaped characters - i.e. here is the interface (excluding the comment within the main-method):
\u0069\u006E\u0074\u0065\u0072\u0066\u0061\u0063\u0065\u0020\u004D\u007B\u0073\u0074\u0061\u0074\u0069\u0063\u0020\u0076\u006F\u0069\u0064\u0020\u006D\u0061\u0069\u006E\u0028\u0053\u0074\u0072\u0069\u006E\u0067\u005B\u005D\u0061\u0029\u007B\u007D\u007D

```

Since all of them contain `}` (125), except for the last one with unicode escapes where `u` (117) is the maximum, that is our best score available in Java.

**Try it online:**

Here a few example programs using these eighteen bytes:

Try it online: 2+2.
Try it online: Check if the program argument is a prime number.
Try it online: Print "Hello, World!".

# Answer
> 1 votes
## Batch, score = 84 (`T`)

Batch is mostly case insensitive, so we don't need any lowercase letters. We need `T` in `SET` in order to be able to do any arithmetic. It also conveniently gives us `GOTO`, which makes arbitrary looping easier. What we don't get:

* `U` \- `PAUSE` (can use `SET/P` to a similar effect); `PUSHD` (can use `CD` and `%CD%` to a similar effect)
* `X` \- `EXIT` (can still `GOTO :EOF` but that doesn't set the error level)
* `Y` \- `TYPE` (can still use `MORE` for small files)
* `^` \- Quote single character (can still wrap most special characters in double quotes)
* `|` \- bitwise OR (can be emulated using `A+B-(A&B)`); logical OR (can be emulated using `&&` and `GOTO`)
* `~` \- bitwise NOT (can be emulated using `-1-X`); string slicing (not needed for arithmetic); parameter expansion (e.g. extracting the extension or size of a file), which needs lowercase letters anyway.
* Any executables whose names include the letters `U`..`Z`.

# Answer
> 1 votes
# MMIX, score 160 (`STB`)

Without some means of memory manipulation, it can't be Turing complete. The lowest-numbered instruction that allows touching memory is `STBU`, at `#A0`. (Well, that's not entirely true, there's also `CSWAP` at `#94`, but that's useless without being able to touch `rP`, which requires `PUT` at `#F6`.)

There's plenty of other stuff below, like branches from `#40` to `#5F`, plenty of arithmetic, floating-point arithmetic, shifts, conditional sets (and zero-or-set according to condition), and even (just barely) computed jumps!

The only things that aren't accessible are stores of anything longer than a byte (or of unsigned bytes), bitwise operations, MMIX's weird ops (`?DIF`, `MUX`, `SADD`, `M[X]OR`), immediate wyde operations, special register handling, unconditional 24-bit relative jumps, subroutine linkage, resumption from traps, user trips, saving/loading the register stack, and syncing memory. Even OS traps are available (though they are probably useless, since the traditional positioning for their arguments and results is `$255`).

# Answer
> 1 votes
# Binary Lambda Calculus, Score: 244.

It is known that S and K are enough for lambda calculus (or combinatory logic) to be Turing-complete.

S and K are represented as following bits, respectively:

```
00000001 01111010 0111010
0000110

```

They have 23 and 7 bits respectively.

In worst case where you must use maximum octet value, an octet sequence 11110100 (which is 244) appears to your program.

# Answer
> 1 votes
# Python 3, score 102 (`f`)

```
def():
 []=-1

```

Bubbler observes:

> With the known bound of `m`, \[...\] `def` is still available, but I doubt it will improve the score because I think making it Turing-complete necessitates the use of `return`.

With awkward and careful use of implicit globals, we can do without `return` by rolling our own stack! Using it is considerably more difficult, but it can still be used to implement SKI combinator calculus:

```
STACK = []
def RETURN(A):
 STACK[:] = STACK + [A]
def POP():
 STACK[-1:] = []

def I(A):
 RETURN(A)
def K(A):
 def INNER_K(B):
  RETURN(A)
 RETURN(INNER_K)
def S(A):
 def INNER_S(B):
  def INNER_INNER_S(C):
   A(C)
   R1 = STACK[-1]
   POP()
   B(C)
   R2 = STACK[-1]
   POP()
   R1(R2)
  RETURN(INNER_INNER_S)
 RETURN(INNER_S)

```

For example, the infinite loop `S(I)(I)(S(I)(I))` can be expressed as

```
S(I)
*STACK, R = STACK
R(I)
*STACK, R = STACK
R(R)

```

Attempt This Online!

I suspect this is optimal.

# Answer
> 0 votes
# perl -MAcme::Bleach, score = 32

`Acme::Bleach` takes a program encoded using white space, and runs it after decoding.

# Answer
> 0 votes
# Pxem, `W`: 87.

Characters are: `!-.01ACDOVW` (but `!` can be any others, and `O` can be anything that works as `pop one and discard it`).

Here's how to emulate cyclic tag system program `(101,001,10)` with input `1`, for example, in Pxem (`??.z ... .a` is pseudo-comment; can be erased):

```
??.z
# input is 1
# then loop begin
.a!1.W??.z

  # exit if empty
  .a.C.C.-.W.D.A??.z
  # append 101 if top is NOT 0
  .a.C0.-.W.V101.VWW.-.A??.z
  # erase top (by printing it)
  .a.O??.z

  # exit if empty
  .a.C.C.-.W.D.A??.z
  # append 001 if top is NOT 0
  .a.C0.-.W.V100.VWW.-.A??.z
  # erase top (by printing it)
  .a.O??.z

  # exit if empty
  .a.C.C.-.W.D.A??.z
  # append 10 if top is NOT 0
  .a.C0.-.W.V10.VWW.-.A??.z
  # erase top (by printing it)
  .a.O??.z

# end of loop
.a!.A

```

Try it online!

# Answer
> 0 votes
# AAAAAAAAAAAAAA!!!!, Score: 65 (`A`).

Characters are `! ,A`.

Proven as in this.

---
Tags: code-challenge, restricted-source
---


title: Swap the Endianness

text:
# Question
Title: Swap the Endianness
As most of you probably know, (byte-addressable) hardware memories can be divided into two categories - *little-endian* and *big-endian*. In little-endian memories the bytes are numbered starting with 0 at the little (least significant) end and in big-endian ones the other way round.

**Fun fact**: These terms are based on Jonathan Swift's book Gulliver's Travels where the Lilliputian king ordered his citizens to break their eggs on the little end (thus the little-endians) and the rebels would break theirs on the big end.

## How swapping works

Suppose we have an unsigned integer (32bit) `12648430` in memory, in a big-endian machine that might look as follows:

```
  addr: 0  1  2  3
memory: 00 C0 FF EE

```

By inverting the byte-order we get the hexadecimal integer `0xEEFFC000` which is `4009738240` in decimal.

## Your task

Write a program/function that receives an unsigned 32bit integer in decimal and outputs the resulting integer when swapping the endianness as described above.

## Rules

* Input will always be in the range `0` to `4294967295`
* Output can be printed to STDOUT (trailing newlines/spaces are fine) or returned
* Input and output are in decimal
* Behavior on invalid input is left undefined

## Test cases

```
0 -> 0
1 -> 16777216
42 -> 704643072
128 -> 2147483648
12648430 -> 4009738240
16885952 -> 3232235777
704643072 -> 42
3735928559 -> 4022250974
4009738240 -> 12648430
4026531839 -> 4294967279
4294967295 -> 4294967295

```

# Answer
# x86\_32 machine language, 3 bytes

```
endian_swap:        # to be called with PASCAL REGISTER calling convention
0f c8    bswap eax
c3       ret

```

This is a bit of a cheat. The Pascal register calling convention (see Wikipedia) is a bit like \__fastcall, except it passes the first parameter in eax, and eax also contains the return value. It's also callee-cleanup, but since we don't use the stack for anything other than the return pointer we don't need to do anything. This allows us to avoid a mov or xchg and just use bswap directly.
> 27 votes

# Answer
# x86\_64 machine language Linux, ~~5~~ 4 bytes

```
0:       0f cf                   bswap  %edi
2:       97                      xchg   %eax,%edi
3:       c3                      retq

```

Thanks to @peter ferrie for -1.

Try it online!
> 11 votes

# Answer
# C (gcc) , ~~20~~, ~~29~~ 17 bytes

@hvd's suggestion.

```
__builtin_bswap32

```

Try it online!

Old answer;

```
#include<byteswap.h>
bswap_32

```

include should be import.
> 8 votes

# Answer
# Japt, ~~10~~ 14 bytes

```
sG ùT8 ò w ¬nG

```

Try it

---

## Explanation

Convert input integer to a base-16 string (`sG`), use `0` to pad the start to length 8 (`ùT8`), split to an array of 2 character strings (`ò`), reverse (`w`), rejoin to a string (`¬`) and convert back to base-10 (`nG`).
> 6 votes

# Answer
# Jelly, 10 bytes

```
⁴4*+b⁹ḊṚḅ⁹

```

Try it online!
> 5 votes

# Answer
# C#, 70 68 bytes

This is probably not optimal.

**68:**

```
Func<uint,uint>f=n=>((n=n>>16|n<<16)&0xFF00FF00)>>8|(n&0xFF00FF)<<8;

```

**70:**

```
uint e(uint n){n=n>>16|n<<16;return(n&0xFF00FF00)>>8|(n&0xFF00FF)<<8;}
```

Try it online!
> 5 votes

# Answer
# Python 2, 44 bytes

```
f=lambda x,i=3:x and(x%256)<<8*i|f(x>>8,i-1)

```

Try it online!
> 5 votes

# Answer
# APL+WIN 14 bytes

```
256⊥⌽(4⍴256)⊤⎕

```

Explanation

```
⎕ prompt for screen input
(4⍴256)⊤ 4 byte representation in base 256
⌽ reverse bytes
256⊥ bytes from base 256 to integer

```
> 5 votes

# Answer
# Wolfram Language (Mathematica), 24 bytes

```
IntegerReverse[#,256,4]&

```

Try it online!

Reverses the input interpreted as an integer in base 256 with 4 digits.
> 5 votes

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

```
3F₁‰R`})₁β

```

Try it online! Explanation:

```
  ₁         Integer constant 256
   ‰        [Div, Mod]
    R       Reverse
     `      Flatten to stack
3F    }     Repeat 3 times
       )    Collect results
        ₁β  Convert from base 256

```
> 4 votes

# Answer
# MATL, ~~12~~ 10 bytes

```
7Y%1Z%P7Z%

```

Try it online! Or verify all test cases.

### Explanation

```
        % Implicitly input a number, read as a double
7Y%     % Cast to uint32
1Z%     % Convert to uint8 without changing underlying data. The result is
        % an array of four uint8 numbers, each corresponding to a byte of
        % the original number's representation
P       % Flip array
7Z%     % Convert back to uint32 without changing underlying data. The array
        % of four uint8 numbers is interpreted as one uint32 number.
        % Implicitly display

```
> 3 votes

# Answer
# 05AB1E, 9 bytes

```
žJ+₁в¦R₁β

```

Try it online!

-1 thanks to Neil.

Port of my Jelly answer.
> 3 votes

# Answer
## JavaScript (ES6), ~~45~~ 43 bytes

```
f=(n,p=0,t=4)=>t?f(n>>>8,p*256+n%256,t-1):p

```
> 3 votes

# Answer
# PPC Assembly (32-bit), 8 bytes

```
endian_swap:    # WORD endian_swap(WORD)
7c 60 1c 2c     LWBRX 3,0,3
4e 80 00 20     BLR

```

How this works:

* PPC calling convention puts the first 32-bit word parameter into SP+24, and shadows that address into GPR3.
* LWBRX takes load GPR3 (third operand) and zero-extends it (second operand) into EA, then reads 4 bytes in reverse order and stores it into GPR3 (first operand).
* GPR3 holds the return value.
* BLR returns from the function (branches to the address in the LR register)

Unfortunately there aren't any online PPC assembly emulators that I could find to demonstrate. Sorry!
> 3 votes

# Answer
# Befunge, ~~62~~ 61 or 49 bytes

```
0&0v!p22:/3g22/*:*82\+%*:*82+<
@.$_:28*:*%00p\28*:**00g28*:*^

```

Try it online!

This is using standard Befunge on the reference interpreter, and we thus need to account for the fact that memory cells are 8-bit signed, and correct for possible signed overflow.

On implementations with unsigned memory cells (e.g. PyFunge), or where the range is greater than 8 bits (e.g. FBBI), we can get away without those checks, saving 12 bytes.

```
0&0v!p22:/3g22/*:*82\+g<
@.$_:28*:*%00p\28*:**00^

```

Try FBBI online!
Try PyFunge online!

Although note that PyFunge has a bug processing integer input, so when testing on TIO you need to follow the number in the input field with a space or line break.
> 3 votes

# Answer
# C, 50 bytes

```
#define f(i) (i>>24|i>>8&65280|(i&65280)<<8|i<<24)

```

Try it online!

To be more portable, I didn't want to use any functions that aren't in ANSI C. :-)

Like @hvd, I also cribbed Polynomial's answer. Due to C's operator precedence, I had to add parentheses around the third term.
> 3 votes

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

*Saved 6 bytes with @Neil's help*

```
n=>(n>>>24|n>>8&65280|(n&65280)<<8|n<<24)>>>0

```

### Test cases

```
let f=

n=>(n>>>24|n>>8&65280|(n&65280)<<8|n<<24)>>>0

console.log(f(0         )) // -> 0
console.log(f(1         )) // -> 16777216
console.log(f(42        )) // -> 704643072
console.log(f(128       )) // -> 2147483648
console.log(f(16885952  )) // -> 3232235777
console.log(f(704643072 )) // -> 42
console.log(f(3735928559)) // -> 4022250974
console.log(f(4009738240)) // -> 12648430
console.log(f(4026531839)) // -> 4294967279
console.log(f(4294967295)) // -> 4294967295
```
> 2 votes

# Answer
# Excel VBA, <sub>~~103~~</sub> 92 Bytes

Anonymous VBE immediate window function that takes input from range `[A1]` converts to hex, reverses bytes, and outputs to the VBE immediate window

```
h=[Right(Rept(0,8)&Dec2Hex(A1),8)]:For i=0To 3:s=s+Mid(h,7-2*i,2):Next:[B1]=s:?[Hex2Dec(B1)]

```
> 2 votes

# Answer
# J, 16 bytes

```
|.&.((4#256)#:])

```

Try it online!

Working on shortening the right-hand expression. I think I can shave off a few bytes by making this work with a beta J version. I swear I saw on here that you can end a train with a noun in a new beta version...

# Explanation

```
|.&.((4#256)#:])
    ((4#256)#:])  Convert to 4 two-byte blocks
            #:      Debase to
      4#256         4 digits base 256
  &.              Apply right function, left function, then inverse of right
|.                Reverse digits

```

Convert to 4 digits base 256, reverse the digits, then convert back to decimal. Basically, perform the algorithm that is provided in the OP. This is perhaps the one time where it's helpful that J's mixed base conversion requires you to specify the number of digits, although it would be 2 fewer bytes if I could end the train in a noun (`(#:~4#256)` instead).
> 2 votes

# Answer
# CP-1610 assembly, 6 DECLEs = 8 bytes

This code is intended to be run on an Intellivision.

A CP-1610 opcode is encoded with a 10-bit value, known as a 'DECLE'. This function is 6 DECLEs long, starting at $480C and ending at $4811.

The CP-1610 has 16-bit registers, so we're using two of them (R0 and R1) to store a 32-bit value.

```
                               ROMW  10           ; use 10-bit ROM

                               ORG   $4800        ; start program at address $4800

                               ;; example call
4800  0001                     SDBD               ; load 0xDEAD into R0
4801  02B8 00AD 00DE           MVII  #$DEAD, R0
4804  0001                     SDBD               ; load 0xBEEF into R1
4805  02B9 00EF 00BE           MVII  #$BEEF, R1

4808  0004 0148 000C           CALL  swap32       ; call our function

480B  0017                     DECR  PC           ; loop forever

                               ;; swap32 function
                       swap32  PROC

480C  0040                     SWAP  R0           ; 16-bit SWAP of R0
480D  0041                     SWAP  R1           ; 16-bit SWAP of R1

480E  01C1                     XORR  R0, R1       ; exchange R0 and R1
480F  01C8                     XORR  R1, R0       ; using 3 consecutive eXclusive OR
4810  01C1                     XORR  R0, R1

4811  00AF                     JR    R5           ; return

                               ENDP

```

### Execution dump

```
 R0   R1   R2   R3   R4   R5   R6   R7    CPU flags  instruction
 ------------------------------------------------------------------
 0000 4800 0000 0000 01FE 1041 02F1 4800  ------iq   SDBD
 0000 4800 0000 0000 01FE 1041 02F1 4801  -----D-q   MVII #$DEAD,R0
 DEAD 4800 0000 0000 01FE 1041 02F1 4804  ------iq   SDBD
 DEAD 4800 0000 0000 01FE 1041 02F1 4805  -----D-q   MVII #$BEEF,R1
[DEAD BEEF]0000 0000 01FE 1041 02F1 4808  ------iq   JSR  R5,$480C

 DEAD BEEF 0000 0000 01FE 480B 02F1 480C  ------iq   SWAP R0
 ADDE BEEF 0000 0000 01FE 480B 02F1 480D  S------q   SWAP R1
 ADDE EFBE 0000 0000 01FE 480B 02F1 480E  S------q   XORR R0,R1
 ADDE 4260 0000 0000 01FE 480B 02F1 480F  ------iq   XORR R1,R0
 EFBE 4260 0000 0000 01FE 480B 02F1 4810  S-----iq   XORR R0,R1
[EFBE ADDE]0000 0000 01FE 480B 02F1 4811  S-----iq   MOVR R5,R7

 EFBE ADDE 0000 0000 01FE 480B 02F1 480B  ------iq   DECR R7

```
> 2 votes

# Answer
# Octave, 10 bytes

```
@swapbytes

```

Try it online!

This may be the first time that Octave has the exact same score as its golfing derivative, MATL. Of course, in this case, it's Octave that has the built-in, rather than MATL, making it a lot easier.

Defines a handle to the built-in `swapbytes`, which takes any data type, swaps the endianness and outputs the result. In this case, the input is a 32-bit unsigned integer.
> 2 votes

# Answer
# C#,  ~~44~~  36 bytes

```
n=>n>>24|n>>8&65280|n&65280<<8|n<<24

```

Try it online!

This was originally based on Polynomial's C# answer, who suggested I post a new answer with my improvements on it, but the approach taken in Arnauld's JavaScript answer turned out to be even shorter in C#.
> 2 votes

# Answer
# , 86 bytes

I thought there was already an answer (or two) in R for this question, but I must have been mistaken or they had the same issues that I had with R not doing signed ints. That issue took out any builtins that could have helped. I tried the 256 base conversion, but it ended up being to long, but I think there is still room for someone smarter than me to do that. Then I ended up with the following which it a base 2 conversion swapping the order in a recursive function.

```
f=function(x,y=0,i=31)'if'(i+1,f(x-(2^i*z),y+(2^((3-i%/%8)*8+i%%8)*(z=2^i<=x)),i-1),y)

```

Try it online!

```
f=function(x,y=0,i=31)       # set up the function and initial values
  'if'(i+1,                  # test for i >= 0
    f(                       # recursively call the function
      x-(2^i*z),             # remove 2^i from x when 2^i <= x
      y+(2^                  # add to y 2 to the power of
        ((3-i%/%8)*8+i%%8)   # calc to swap the order of the bytes
        *(z=2^i<=x)),        # when 2^i <= x
      i-1),                  # decrement i
   y)                        # return y

```
> 2 votes

# Answer
# , 41 bytes

```
function(n)n%/%256^(0:3)%%256%*%256^(3:0)

```

Try it online!

Verify all test cases!

Uses a base-256 conversion as MickyT suggested here. R does not have unsigned 32-bit integers, nor does it have 64-bit integers. This prevents us from using bitwise operations but this approach (and likely MickyT's) is probably still shorter since R's bitwise operators are quite verbose.

Utilizes number 4 of this tip, taking into account that we're never getting a number as large as `256^4`.

`n%/%256^(0:3)%%256` extracts the bytes, and `%*%`, the matrix product, is the dot product in this situation, with `256^(3:0)` effecting the reversed order of bytes. `%*%` will return a 1x1 `matrix` containing the endian-reversed value.
> 2 votes

# Answer
# ARM machine language Linux, 8 bytes

```
0:       e6bf0f30       rev     r0, r0
4:       e12fff1e       bx      lr

```

To try this yourself, compile and run the following on a Raspberry Pi or Android device running GNUroot

```
#include<stdio.h>
#define f(x) ((unsigned int(*)(unsigned int))"0\xf\xbf\xe6\x1e\xff/\xe1")(x)
int main(){
  printf( "%u %u\n", 0, f(0) );
  printf( "%u %u\n", 1, f(1) );
  printf( "%u %u\n", 42, f(42) );
  printf( "%u %u\n", 128, f(128) );
  printf( "%u %u\n", 16885952, f(16885952) );
  printf( "%u %u\n", 704643072, f(704643072) );
  printf( "%u %u\n", 3735928559U, f(3735928559U) );
  printf( "%u %u\n", 4009738240U, f(4009738240U) );
  printf( "%u %u\n", 4026531839U, f(4026531839U) );
  printf( "%u %u\n", 4294967295U, f(4294967295U) );
}

```
> 2 votes

# Answer
# Perl 5 `-p`, 21 bytes

```
$_=unpack V,pack N,$_

```

Try it online!
> 2 votes

# Answer
# C# (.NET Core), 72+31=103 bytes

```
m=>BitConverter.ToUInt32(BitConverter.GetBytes(m).Reverse().ToArray(),0)

```

Try it online!

+31 for `using System;using System.Linq;`

I was hoping to use `Array.Reverse` inline, but it wasn't to be (see alternative below).

# C# (.NET Core), 87+13=100 bytes

```
m=>{var a=BitConverter.GetBytes(m);Array.Reverse(a);return BitConverter.ToUInt32(a,0);}

```

Try it online!

+13 for `using System;`

This solution care of @JeppeStigNielsen; removing the restriction of having everything inline saved 3 bytes.
> 1 votes

# Answer
# REXX, 42 bytes

```
say c2d(left(reverse(d2c(arg(1))),4,'0'x))

```

Try it online!

Ungolfed:

```
n=arg(1) -- take n as argument
n=d2c(n) -- convert from decimal to character (bytes)
n=reverse(n) -- reverse characters
n=left(n,4,'0'x) -- extend to four bytes, padding with zeros
n=c2d(n) -- convert from bytes to decimal again
say n -- output result

```
> 1 votes

# Answer
## Swift, 28 bytes

```
{(n:UInt32)in n.byteSwapped}

```
> 1 votes

# Answer
# Perl 5, 27 bytes

```
say hex unpack H8,pack I,<>

```

Try it online!
> 1 votes

# Answer
# K4, 18 bytes

**Solution:**

```
0b/:,/8#|12 8#0b\:

```

**Examples:**

```
q)\
  0b/:,/8#|12 8#0b\:0
0
  0b/:,/8#|12 8#0b\:1
16777216
  0b/:,/8#|12 8#0b\:42
704643072
  0b/:,/8#|12 8#0b\:4294967295
4294967295
  0b/:,/8#|12 8#0b\:4026531839
4294967279

```

**Explanation:**

There are no unsigned ints, so takes input as a long.

Convert into boolean array (64bits), reshape, reverse, take first 8 bytes, convert back to long.

```
0b/:,/8#|12 8#0b\: / the solution
              0b\: / convert to bits
         12 8#     / reshape into 12x8 grid (wraps)
        |          / reverse
      8#           / take first 8
    ,/             / flatten
0b/:               / convert to long

```

**Bonus:**

**19 byte** version in oK which you can Try online!

```
2/,/8#|12 8#(64#2)\

```
> 1 votes

# Answer
# SmileBASIC, 34 bytes

```
INPUT N
RGBREAD N OUT A,B,C,D?RGB(D,C,A,B)

```

`RGBREAD`/`RGB` are functions that convert between a 32-bit integer and four 8-bit values. They're designed for use with (A)RGB color data but you can use them for other things too.
> 1 votes

# Answer
# Thunno 2, 9 bytes

```
ɠ⁴+ɠBḣrɠḋ

```

Try it online!

#### Explanation

```
ɠ⁴+ɠBḣrɠḋ  # Implicit input
ɠ⁴         # Push 256 ** 4
  +        # Add to the input
   ɠB      # Convert to base 256
     ḣ     # Remove the leading 1
      r    # Reverse the list
       ɠḋ  # Convert from base 256
           # Implicit output

```
> 1 votes

# Answer
### **x86 machine code - 11 bytes**

```
     6 00000000 66C1C008                rol ax, 8
     7 00000004 C1C010                  rol eax, 16
     8 00000007 66C1C008                rol ax, 8

```

Debug it to see value of `0x00C0FFEE` has been swapped to `0xeeffc000` in register `eax`.

```
% gdb -q swap
Reading symbols from swap...(no debugging symbols found)...done.
(gdb) disassemble _start
Dump of assembler code for function _start:
   0x08048060 <+0>:     mov    eax,0xc0ffee
   0x08048065 <+5>:     rol    ax,0x8
   0x08048069 <+9>:     rol    eax,0x10
   0x0804806c <+12>:    rol    ax,0x8
End of assembler dump.
(gdb) r
Starting program: /home/user/swap

Program received signal SIGSEGV, Segmentation fault.
0x08048070 in ?? ()
(gdb) i r $eax
eax            0xeeffc000   -285229056
(gdb)

```
> 0 votes

# Answer
# Desmos, ~~51~~ 48 bytes

*-3 bytes thanks to @Aiden Chow!*

```
f(n)=∑_{i=0}^3mod(floor(n/256^i),256)256^{3-i}

```

Try it on Desmos!

Extracts each byte and adds them back in reverse order.
> 0 votes

---
Tags: code-golf, number, integer, hexadecimal
---