# Question
Title: The shortest code to invert bit-wise a binary string
Me thinks there aren't enough easy questions on here that beginners can attempt!

The challenge: Given a random input string of 1's and 0's such as:

```
10101110101010010100010001010110101001010

```

Write the shortest code that outputs the bit-wise inverse like so:

```
01010001010101101011101110101001010110101

```

# Answer
# 05AB1E, 1 byte

```
_

```

Try it online! Beats all other answers. Takes I/O as a list of bits.

```
_  # full program
_  # logically negate...
   # (implicit) each element of...
   # implicit input
   # implicit output

```
> 0 votes

# Answer
# J, 5 bytes

Assumes the input string is in variable `b`.

```
b='0'

```

This does not do what it would do in most languages...

> The J comparison operator is just `=` (`=:` and `=.` are global and local assignment, respectively). However, `=` doesn't work like the normal `==` operator: it compares item-by-item. Keep in mind that an array is formed like this: `0 2 3 2 3 1 2 3 4`. `2 = 0 2 3 2 3 1 2 3 4` gives `0 1 0 1 0 0 1 0 0` for example. This is similar for a string: `'a'='abcadcadda'` doesn't just return `0`, it returns `1 0 0 1 0 0 1 0 0 1` (This can be extrapolated to mean `0` with `*/`, which basically means `all`.) In this case however, this behavior is excelent, since we want a string of ones and zeros, or true's and false's. Since J's bools *are* `1` and `0`, this results in an array of `1`'s and `0`'s (They aren't strings, and every other character other than `1` would also result in `0` in this array.) This doesn't need printing: J automatically prints the result of an expression. I hope this was adequate explanation, if not, please ask for something that isn't yet clear in the comments. This answer also could've been `'0'&=` (or `=&'0'`), but I felt that `b='0'` was clearer.
> 92 votes

# Answer
# GolfScript, 5 bytes

```
{1^}%

```

Try it online.

### How it works

* GolfScript reads the entire input from STDIN and places it on the stack as a string.
* `{}%` goes through all characters in the string and executes the code block for all of them.
* `1^` computes the exclusive OR of the characters ASCII code with 1. “0” corresponds to the ASCII code 48, “1” to ASCII code 49.

Since `48 ^ 1 = 49` and `49 ^ 1 = 48`, this turns 0's into 1's and 1's into 0's.
* Once finished, GolfScript prints the modified string.
> 46 votes

# Answer
# CJam - 4

```
q1f^

```

This xor's every character with 1.
Unlike the other CJam answer, I'm not assuming the input is already on the stack.

Try it at http://cjam.aditsu.net/
> 36 votes

# Answer
# x86 machine code on DOS - ~~14~~ ~~13~~ 11 bytes

Well, it did get shorter again! After writing a solution for an unrelated challenge, I noticed that the same trick could be applied even here. So here we go:

```
00000000  b4 08 cd 21 35 01 0a 86  c2 eb f7                 |...!5......|
0000000b

```

Commented assembly:

```
    org 100h

section .text

start:
    mov ah,8        ; start with "read character with no echo"
lop:
    ; this loop runs twice per character read; first with ah=8,
    ; so "read character with no echo", then with ah=2, so
    ; "write character"; the switch is performed by the xor below
    int 21h         ; perform syscall
    ; ah is the syscall number; xor with 0x0a changes 8 to 2 and
    ; viceversa (so, switch read <=> write)
    ; al is the read character (when we did read); xor the low
    ; bit to change 0 to 1 and reverse
    xor ax,0x0a01
    mov dl,al       ; put the read (and inverted character) in dl,
                    ; where syscall 2 looks for the character to print
    jmp lop         ; loop

```

---

### Previous solution - 13 bytes

~~I think it doesn't get much shorter than this.~~ Actually, it did! Thanks to @ninjalj for shaving off one more byte.

```
00000000  b4 08 cd 21 34 01 92 b4  02 cd 21 eb f3           |...!4.....!..|
0000000d

```

This version features *advanced interactivity™* \- after running it from the command line, it spits out the "inverted" characters as long as you write the input digits (which are not echoed); to exit, just do a Ctrl-C.

Unlike the previous solution, this has some trouble running in DosBox - since DosBox doesn't support Ctrl-C correctly, you are forced to close the DosBox window if you want to exit. In a VM with DOS 6.0, instead, it runs as intended.

NASM source:

```
org 100h

section .text

start:
    mov ah,8
    int 21h
    xor al,1
    xchg dx,ax
    mov ah,2
    int 21h
    jmp start

```

### Old solution - ~~27~~ ~~25~~ 22 bytes

This accepted its input from the command line; runs smoothly as a .COM file in DosBox.

```
00000000  bb 01 00 b4 02 8a 97 81  00 80 f2 01 cd 21 43 3a  |.............!C:|
00000010  1e 80 00 7c f0 c3                                 |...|..|

```

NASM input:

```
    org 100h

section .text

start:
    mov bx, 1
    mov ah, 2
loop:
    mov dl, byte[bx+81h]
    xor dl, 1
    int 21h
    inc bx
    cmp bl, byte[80h]
    jl loop
exit:
    ret

```
> 33 votes

# Answer
# Bash+coreutils, 8 bytes

```
tr 01 10

```

Takes input from STDIN.

---

Or

# sed, 8 bytes

```
y/01/10/

```
> 26 votes

# Answer
# CJam, 4 bytes

```
:~:!

```

Assumes the original string is already on the stack. Prints the modified string.

Try it online by pasting the following **Code**:

```
"10101110101010010100010001010110101001010":~:!

```

### How it works

* `:~` evaluates each character of the string, i.e., it replaces the *character* 0 with the *integer* 0.
* `:!` computes the logical NOT of each integer. This turns 0's into 1's and 1's into 0's.
> 21 votes

# Answer
# Brainfuck (70 71)

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

```

**Explanation:**

```
>,[>,]                       Read characters until there are none left.
<[<]                         Return to start
>[<                          Loop as long as there are characters to invert
  +++++++[>-------<-]        Subtract 49 (ASCII value of 1)
  >[++<]                     If not 0, add 2
  +++[<++++>-]<[>>++++<<-]>> Add 48
  .                          Print
  [-]                        Set current cell to 0
>]                           Loop

```
> 21 votes

# Answer
## PHP - 19 bytes

```
<?=strtr($s,[1,0]);

```

Yea, not really original, I guess!
> 17 votes

# Answer
# Pancake Stack, 532 bytes

```
Put this tasty pancake on top!
[]
Put this delicious pancake on top!
[#]
Put this  pancake on top!
How about a hotcake?
If the pancake is tasty, go over to "#".
Eat all of the pancakes!
Put this supercalifragilisticexpialidociouseventhoughtheso pancake on top!
Flip the pancakes on top!
Take from the top pancakes!
Flip the pancakes on top!
Take from the top pancakes!
Put this supercalifragilisticexpialidociouseventhoughthes pancake on top!
Put the top pancakes together!
Show me a pancake!
If the pancake is tasty, go over to "".

```

It assumes the input is terminated by a null character. The strategy is as follows:

* Take a character of input
* Subtract the ascii value of `1` from it.
* Subtract that from `0` (yielding a `1` if we had `0`, or a `0` if we had `1`)
* Add the ascii value of `0` to it
* Print the char.
* Repeat
> 12 votes

# Answer
# C: 29

```
i(char*s){*s^=*s?i(s+1),1:0;}

```

Try it online here.

Thanks for pointing out the XOR trick, Dennis.
> 10 votes

# Answer
## Python 2.7 – 34\*

Oh how much this first one sucks. Pretty ugly, this one is. 63 chars.

```
print''.join([bin(~0)[3:] if x == '0' else bin(~1)[4:] for x in ''])

```

This one is a bit better but still not that fancy. 44 chars.

```
print''.join([str(int(not(int(x)))) for x in ''])

```

Since `int(x) and 1` returns `int(x)` if it's not 0 and otherwise False. The solution can be further reduced to 36 chars.

```
print''.join([str(1-int(x)) for x in ''])

```

Since `join()` takes a generator the brackets can be removed. 32 chars.

```
print''.join(str(1-int(x))for x in'')

```

And backticks can be used instead of `str()`

```
print''.join(`1-int(x)`for x in'')

```

*Reduced to 44 from 34 thanks to pointers from @TheRare*

Finding one's complement is difficult in python since `bin(-int)` returns -0bxxx hence the above.
> 9 votes

# Answer
# Perl, 9 characters

```
'y/10/01/'

```

The 9th character is the 'p' flag

Usage:

```
$ echo '10101001' | perl -pe 'y/10/01/'

```
> 8 votes

# Answer
# Javascript (*ES6*) 36

```
alert(prompt().replace(/./g,x=>x^1))

```
> 7 votes

# Answer
# Labyrinth, 6 bytes

(Labyrinth is newer than this challenge, so this answer doesn't compete - not that it's winning anyway...)

```
1,
.$@

```

This code assumes that STDIN contains *only* the digits (in particular, no trailing newline).

The instruction pointer (IP) starts in the top left corner going right. While there are digits to read it will cycle in a tight loop through the left-hand 2x2 block: `1` push a 1, `,` read a digit, `$` XOR it with 1 to toggle the last bit, `.` print the result. The IP takes this loop because the top of the stack is positive after the XOR, such that it will take a right-turn. When we hit EOF, `,` returns `-1` instead. Then the XOR will yield `-2` and with this negative value the IP takes a left-turn onto the `@` and the program ends.

This solution should be optimal for Labyrinth: you need `,` and `.` for an I/O loop and `@` to terminate the program. You need at least two characters (here `1` and `$`) to toggle the last bit. And you need at least one newline for a loop which can be terminated.

Unless... if we ignore STDERR, i.e. allow terminating with an error we can save the `@` and we also don't need any way to switch between two paths. We just keep reading and printing until we accidentally try to print a negative value (the `-2`). This allows for at least two 5-byte solutions:

```
1,
.$

```

```
,_1$.

```
> 6 votes

# Answer
# Ruby: 23

```
p $<.read.tr("01","10")

```
> 5 votes

# Answer
# Turing Machine Code, 32 bytes (1 state - 3 colors)

Using the rule table syntax required by this online TM simulator. Borrowed from a post I made to my Googology Wiki user blog a few months back.

```
0 0 1 r *
0 1 0 r *
0 _ _ * halt

```

You may also test this using this java implementation.
> 5 votes

# Answer
## R, 27 characters

```
chartr("01","10",scan(,""))

```

Usage:

```
> chartr("01","10",scan(,""))
1: 10101110101010010100010001010110101001010
2:
Read 1 item
[1] "01010001010101101011101110101001010110101"

```
> 4 votes

# Answer
# APL (Dyalog Unicode), 7 bytesSBCS

Full program. Prompts stdin.

```
∊⍕¨~⍎¨⍞

```

Try it online!

prompt stdin

`⍎¨` execute each character

`~` logical NOT

`⍕¨` format each character as text

**ϵ**nlist (flatten)
> 4 votes

# Answer
# PHP \> 5.4 -- 37 characters

```
foreach(str_split($s) as $v)echo 1^$v

```

`$s` is the input

`**Try it online**`
> 3 votes

# Answer
# Python 2.x - 44 bytes

```
print''.join(`1-int(x)`for x in raw_input())

```

Why make it complex, or use some cheaty variables?
> 3 votes

# Answer
# TI-BASIC, 7 bytes

This is a function that takes a binary string (through `Ans`) as input and returns the output as an inverted (not reversed) string, as specified. For more help, you can read through list application by `not(` on the TI-BASIC wiki. I'm using the compiled version because it is smaller:

```
»*r>Õ¸r

```

In hex:

```
BB 2A 72 3E D5 B8 72

```

**Explanation**

`»*r` \- Take function input as string and convert to list

`>` \- Pipe given list to the next operators

`Õ¸r` \- Return the inverse of the list
> 3 votes

# Answer
# Haskell, 22 bytes

```
map(\c->"10"!!read[c])

```

I was surprised by the lack of Haskell solutions to this challenge, so here's one. It evaluates to a function that takes a string and returns its inverse.

### Explanation

Nothing fancy here.

```
map(\c->             )  -- For each character c in the input string:
                  [c]   -- wrap c into a string,
              read      -- convert to integer,
        "10"!!          -- and index the string "10" with it.

```
> 3 votes

# Answer
## Befunge 93, 25 bytes

```
0>~1+:#v_$>:#,_@
 ^   -1<

```

Assuming empty stack and EOF both read -1.

`0` pushes a \0 as a null terminator

`>~1+:#v_` is an input loop, it reads ascii, adds 1, checks for EOF+1=0,

`^ -1<` else subtracts 1 and leaves the pushed ascii value on the stack.

`$>:#,_@` drops the extra copy of zero on top of the stack, then prints the binary string top to bottom

If empty stack reads 0, save 2 bytes with

```
>~:1+#v_$>:#,_@
^   -1<

```

A version around 15 bytes is possible using this same algorithm if EOF = 0, but I don't have such an implementation handy to test with.
> 3 votes

# Answer
# Javascript ES6, 26 chars

```
s=>s.replace(/\d/g,x=>x^1)

```
> 3 votes

# Answer
# brainfuck, 24 bytes or 19 bytes

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

```

Try it online!

or

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

```

(this one requires an interpreter which will noop on `<` if the data-index is 0)

Both programs use 8-bit wrapping cells. The main part of the programs are the `>++[->++[<]>-]>-` and `+[<[-->>]<--]<` which do some rather convoluted things to flip the last bit of the number.

I'm happy I managed to beat some more 'real' languages like C and Python, not something that happens every day with bf ;)
> 3 votes

# Answer
# Befunge-98 (PyFunge), 7 bytes

```
'a#@~-,

```

For every character, `c`, in the input, it prints the character with an ascii value of `94 - c`, where 94 is the value of ‘0’ +’1’, or ‘a’

Try it online!
> 3 votes

# Answer
# brainfuck, 26 bytes

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

```

This flips the last bit of each byte of input. (Assumes EOF -\> 0, assumes nothing about cell size, doesn't go out of bounds to the left.)
> 3 votes

# Answer
## Python3, 39

Methinks Python is not the best language for this. :)

```
for i in input():print(1-int(i),end='')

```

If you care about having a newline after the output, here's a 43-character alternative:

```
print(''.join("01"[i<"1"]for i in input()))

```
> 2 votes

# Answer
## J - 11 chars

Boolean values in J are represented as the integers `0` and `1`, which of course are also valid indices into arrays (in this case, the 2-character array `'01'`)

```
'01'{~'0'&=

```
> 2 votes

# Answer
# C#, 131 bytes

A little late to the party, but here's mine. :)

```
using System;class R{static void Main(string[]a){foreach(var v in a[0].ToCharArray()){Console.Write(int.Parse(v.ToString())^1);}}}

```
> 2 votes

# Answer
# MATLAB, 13 bytes

```
@(x)[97-x '']

```

After running the above, simply call the function with your input string to get the inverted string. For example running:

```
ans('10101110101010010100010001010110101001010')

```

prints:

```
01010001010101101011101110101001010110101

```
> 2 votes

# Answer
# BotEngine, 4x8=32

Noncompeting as the language postdates the question.

```
Iv2 0 12
 >e>S SS
    e1e0
   ^< <P

```

With highlighting:
> 2 votes

# Answer
# Jelly, 4 bytes

```
^1Ṿ€

```

Try it online!

Explanation:

First of all, if you're familiar with Jelly, you might've noticed that I'm trying to **bitwise-xor with a string**. That sounds all sorts of ridiculous at first, but Jelly actually supports vectorized bitwise-xor'ing with strings, where each char, if it's a digit from 1 to 9, it's treated as such, otherwise it's treated as 0. The only chars in the string will in this case be `'0'` and `'1'`, being treated as themselves, as previously specified. So, bitwise-xor'ing then with `1` will return `0 ^ 1 = 1` for every `'0'` and `1 ^ 1 = 0` for every `'1'` in the string. Right now, our output is a list of `0`s and `1`s, so it's not yet in the correct format. We right now have to find a way to concatenate the integers into a single string, and we don't have a builtin for that. Fortunately, strings in Jelly are lists of 1-char Python strings, so we can simply take the string representation of each of the integers in the list. But wait! That builtin costs us 2 bytes, so let's see if there's a shorter builtin...and there is! Behold the uneval builtin! Unevaling an integer just takes its Jelly string representation, which, for integers, is equivalent to Python's string representation. So why not use it? That's what we'll do, to actually finish our program.

```
^1Ṿ€ Main link, monadic
^1   XOR each char with 1, as specified above
  Ṿ€ Uneval each resulting integer

```
> 2 votes

# Answer
# Japt `-m`, 2 bytes

```
^1

```

Try it here
> 2 votes

# Answer
# Vim, 19 keystrokes

```
:s/./-&/g␤qq␁l@qq@q

```

is `Return` and  is `Ctrl``A`

# Explanation

```
:s/./-&/g␤   Negate every digit (01100 -> -0-1-1-0-0)
qq␁l@qq@q   Increment every number (-0-1-1-0-0 -> 10011)

```
> 2 votes

# Answer
# Forth (gforth), 38 36 bytes

```
: f 0 do dup c@ 1 xor emit 1+ loop ;

```

Try it online!

-2 bytes thanks to @bubbler

### Explanation

Gets the string character by character. For each character:

1. checks if it's equal to 49 and then adds -1 to the result (forth uses -1 as true).
2. Prints the space right-aligned in a space of size 1 (removes space after number that `.` normally outputs)

### Code Explanation

```
: f                \ start a new word definition
  0 do             \ start counted loop from 1 to string-length
    dup c@         \ duplicate the string address and get the ascii value of the char at the beginning
    49 = 1+        \ check if equal to 49 and add 1 to the result (forth uses -1 as true)
    1 .r           \ output right-aligned in a space of size (removes trailing space)
    1+             \ increment the string address
  loop             \ end the loop
;                  \ end the word definition

```
> 2 votes

# Answer
# tinylisp, 34 bytes

```
(load library
(d F(q((A)(map not A

```

Try it online!

# tinylisp, 37 bytes

```
(d F(q((A)(i A(c(i(h A)0 1)(F(t A)))(

```

Try it online!

surprisingly close to the library version.
> 2 votes

# Answer
# Cobra - 89

```
class P
    def main
        r=''
        for i in Console.readLine,r+=if(i==c'1','0','1')
        print r

```
> 1 votes

# Answer
# C# in LINQPad, 64 63

```
foreach(var c in Console.ReadLine())Console.Write((char)(c^1));

```

**EDIT**: removed one character by using XOR 1
> 1 votes

# Answer
## Tcl - 23 bytes

```
string map {0 1 1 0} $s

```

Not quite the shortest but highly readable.
> 1 votes

# Answer
# ECMAScript (28 bytes)

```
for(i of prompt(r=''))r+=1-i

```

Just subtraction.

## Alternative 1 (28 bytes)

```
for(i of prompt(r=''))r+=i^1

```

A simple bitwise not.

## Alternative 2 (29 bytes)

```
for(i of prompt(r=''))r+=2+~i

```

`~'1'` is `-2` and `~'0'` is `-1`, so `2+~i` gives `0` for `1` and `1` for `0`.

## Alternative 3 (29 bytes)

```
for(i of prompt(r=''))r+=+!+i

```

The last `+` changes `i` to a number, `!` converts it to a boolean (`0` is `false` and anything else is `true`) and inverts it, and the first `+` converts it to a number (`false` becomes `0` and `true` becomes `1`).
> 1 votes

# Answer
Linux amd64 assembly version, 370 bytes, generates small ELF executable (392 bytes after strip --strip-all).

```
global _start

_start:
        mov rsi, [rsp+16] ; argv[1]
        xor rdx, rdx
loop:
        mov bl, [rsi+rdx]
        test bl, bl
        jz print
        xor bl, 1
        mov [rsi+rdx], bl
        inc rdx
        jmp loop
print:
        mov rdi, 1 ; stdout
        mov rax, 1 ; write
        syscall
        mov rax, 60 ; exit
        xor rdi, rdi
        syscall

```
> 1 votes

# Answer
# Java - ~~120~~ ~~103~~ 94

This is for hdante :)

```
class I{public static void main(String[]a){for(int
x:a[0].getBytes())System.out.print(49-x);}}

```

It takes the string as a command-line argument.
> 1 votes

# Answer
## \>\<\> (6 bytes)

Assuming you don't mind the code exiting with an error, the following works:

```
{2%0=n

```

Example run:

```
$ python3 fish.py binary.fish -s "100010101101111001"
011101010010000110
something smells fishy...

```

This errors when it runs out of values left on the stack. If it has to actually end correctly, 11 bytes works;

```
{2%0=nl0=?;

```

Example:

```
$ python3 fish.py binary.fish -s "10111111101101001"
01000000010010110

```

Essentially, each piece of code is doing the same thing: `{` shifts the entire stack to the left, moving the first value entered in the command call to the top of the stack; `2%` takes the modulus of the top value with 2 (so `"1" -> 49 (ASCII code) -> 1` and `"0" -> 48 -> 0`); `0=` pushes 0 to the stack and pops the top two values off, pushing 1 to the stack if they are equal and 0 otherwise; and `n` prints the numerical value of the value on top of the stack.
The additional bit in the second piece just checks if there are any values left on the stack and ends if there aren't.
> 1 votes

# Answer
# PowerShell, ~~33~~ 29 Bytes

```
$args-split0-replace1,0-join1

```

Similar, but distinct, from DarkAjax's answer.

Uses inline operators to split on `0`'s (which results in a collection of strings of `1`'s), replace those `1`'s with `0`'s, and then join the collection back together with `1`'s (i.e., replacing the `0`'s that were removed when we split with `1`'s).
> 1 votes

# Answer
## Python 3, 60 bytes

Not the shortest solution but i wanted to see if it could be achieved without a loop.

Exclusive or on a binary of ones same length as the input string (equivalent of 2\**n - 1 where n is length of input). Padding with zfill was not ideal...

```
a=input()
print(bin(int(a,2)^2**len(a)-1)[2:].zfill(len(a)))

```
> 1 votes

# Answer
# Chicken Scheme - 85

Me thinks this problem needs *more parenthesis*!

`(display(list->string(map(lambda(s)(if(eqv? s#\0)#\1 \0))(string->list(read-line)))))`

Switching `display` for `write` saves 2 more characters, at the cost of quotes around the answer.

> Fun fact:
>
> A little over 20% of those 85 characters above are parentheses. Achievement unlocked.
> 1 votes

# Answer
## \>\<\>, ~~13~~ 10 bytes

```
i1+:?!;2%n

```

Explanation:

```
i1+:?!;2%n

i          Input as code point
 1+        Add one
   :       Duplicate the top item
    ?!;    Terminate if EOF
       2%  Modulo the top item of the stack by two.
           Because we added one earlier, this is effectively flipping the output.
         n Output as integer

```

Try it here
> 1 votes

# Answer
# Simplex v.0.7, ~~3~~ 4 bytes

Noncompeting; languages postdates question.

```
bTng
b    ~~ take string input
 Tn  ~~ applies negation function on each character
   g ~~ clear strip and output it

```
> 1 votes

# Answer
# Python 2, ~~57~~ ~~53~~ ~~52~~ ~~46~~ 41 bytes

```
lambda s:''.join(['10'[c>'0']for c in s])

```

Here's another one, with a different approach:

```
def b(s):return''.join([str(int(not(int(c))))for c in s])

```

Shortened with lambda anonymity per the advice of Mego. Shortened with '10' instead of tuple of characters per advice of DLosc

(Thanks!)
> 1 votes

# Answer
# Lua, 66 bytes

```
function a(b)return b:gsub("1","2"):gsub("0","1"):gsub("2","0")end

```
> 1 votes

# Answer
## Burlesque, 9 bytes

```
)-.'/'1r~

```

Try online here.

Explanation:

```
)-. -- decrement every character (1 -> 0, 0 -> /)
'/'1r~ -- replace / with 1

```
> 1 votes

# Answer
# Prolog, ~~73~~, ~~71~~, 67 bytes

```
q(X):-X='0',write(1);write(0).
p(X):-atom_chars(X,L),maplist(q,L).

```

Not an optimal language for this challenge.
Having input in string-form makes for an expensive conversion to list.
Could probably be improved on though.
**Testing:**
Try it out here
> 1 votes

# Answer
# Java 8, 85 bytes

`void i(String s) {s.chars().mapToObj(c->(char)49-(int)c).forEach(System.out::print);}`

I like Java. I like streams. Gotta do both.
> 1 votes

# Answer
# PHP, ~~48~~ 41 bytes

```
foreach(str_split($argv[1])as$c)echo+!$c;

```

Saved 7 bytes thanks to Jörg Hülsermann!

Test online
> 1 votes

# Answer
## Racket 71 bytes

```
(λ(s)(list->string(map(λ(x)(if(eq? x #\0)#\1 #\0))(string->list s))))

```

Detailed version:

```
(define f
  (λ(s)
    (list->string
     (map
      (λ(x)
        (if(eq? x #\0)
           #\1
           #\0))
      (string->list s)))))

(f "1010111")

```

Output:

```
"0101000"

```
> 1 votes

# Answer
# Clora, 6 bytes (Noncompeting)

```
<0I?01

```

Explanation:

`<0I` Means, `if 0 < I` (Current input character), set flag as true

`?01` If the flag is true (I is 1), output 0, else output 1
> 1 votes

# Answer
# VBA, ~~74~~ 44 Bytes

VBE immediate window function that takes input from cell `[A1]` and inverts the binary sting by replacement

```
?Replace(Replace(Replace([A1],1,2),0,1),2,0)

```
> 1 votes

# Answer
# SmileBASIC 3, 40 bytes

**Down 10 bytes thanks to suggestions from 12Me21.**

While I like 12Me21's answer, it doesn't actually answer the question.

```
INPUT S$WHILE""<S$?!VAL(SHIFT(S$));
WEND

```

This doesn't print a linebreak afterwards though, so if you did this on the console you might get something like `001010101OK`. Oh well, nothing about it in the question.

```
INPUT S$             'get string
WHILE ""<S$          'while input string isn't empty:
  ? !VAL(SHIFT(S$)); '-SHIFT a character off our string
                     '-find the opposite value with VAL and !
                     '-print that value, omitting newline
WEND                 'while end

```
> 1 votes

# Answer
# Noether, 18 bytes

***100th Answer! :D***

```
I~sL(1si/W-Pi1+~i)

```

**Try it here!**

Loops through each character in the string, inverting each character.

**Explanation:**

```
I  - Push input to stack
~s - Store the top of the stack in the variable s
L  - Pop string off the top and push its length
(  - Pop off the stack and repeat code between brackets until stack equals popped value
1  - Push the number 1
s  - Push the value of variable s
i  - Push the value of variable i (all variables are initialised to zero)
/  - Pop a string and number, n, off stack and push the character at index n
W  - Convert string to number
-  - Pop two numbers off stack and push the numbers subtracted
P  - Print top of stack
i  - Push value of variable i
1  - Push number 1
+  - Pop top two numbers and push the addition
~i - Pop top off stack and store in variable i
)  - End loop

```
> 1 votes

# Answer
# Pyth, 6 bytes

`jkms!s`

Try it!

Takes input as a string. New at this so it probably isn't optimal but the shortest pyth one here so far!
> 1 votes

# Answer
# Cubix, 12 bytes

```
i?./^\'1c$@O

```

Try it online!

cube form:

```
    i ?
    . /
^ \ ' 1 c $ @ O
. . . . . . . .
    . .
    . .

```
> 1 votes

# Answer
# Sinclair ZX81, Timex TS1000/1500, ~60 tokenized BASIC bytes

```
 1 INPUT A$
 2 PRINT A$
 3 FOR I=1 TO LEN A$
 4 PRINT NOT VAL A$(I);
 5 NEXT I

```

This technique iterates over each byte of the string, taking it's numeric value and printing the `NOT` equivalent. In ZX81 terms, `NOT 1` is `0` and `NOT 0` is `1`. `RUN` the program and enter your binary string, followed by `NEW LINE` (or the Enter key).

Simple test case shown below.
> 1 votes

# Answer
# Excel, 51 bytes

Performs 3 substitutions: 0 -\> 5, 1 -\> 0, 5 -\> 1

```
=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,0,5),1,0),5,1)

```

For fun, replacing the third substitution (5 -\> 1) eith a `/5` works for input where first character is `0`. But for others, need to pad with for length. Resulting in 59 bytes:

```
=TEXT(SUBSTITUTE(SUBSTITUTE(A1,0,5),1,0)/5,REPT(0,LEN(A1)))

```
> 1 votes

# Answer
## **Pure Bash shell solution. 87 bytes.**

```
while((n<=${#1}));do
case "${1:$n:1}" in
0)printf 1;;1)printf 0;;
esac;n=$((n+1));done

```
> 1 votes

# Answer
# Perl 6, 11 bytes

```
{TR/10/01/}

```

Try it online!

Simple transliterate that turns all `1`s to `0`s and vice-versa.
> 1 votes

# Answer
# 05AB1E, 3 bytes

```
€_J

```

Try it online.

**Explanation:**

```
€      # Map over the digits of the (implicit) input
 _     #  Negative boolean: 0 becomes 1, everything else (so the 1s) becomes 0
  J    # After the map, join everything together (and output implicitly)

```
> 1 votes

# Answer
# Whitespace, 79 bytes

```
[N
S S N
_Create_Label_LOOP][S S S T T   S S S T N
_Push_49][S N
S _Duplicate_49][S N
S _Duplicate_49][T  N
T   S _Read_STDIN_as_character][T   T   T   _Retrieve][T    S S T   _Subtract][S N
S _Duplicate][N
T   S S N
_If_0_Jump_to_Label_1][S S S T  N
_Push_1][T  S S T   _Subtract][N
T   S T N
_If_0_Jump_to_Label_0][N
N
N
_Exit][N
S S T   N
_Create_Label_0][S S S T    N
_Push_1][N
S S S N
_Create_Label_1][T  N
S T _Print_integer_to_STDOUT][N
S N
N
_Jump_to_Label_LOOP]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Since Whitespace can only take input as integer or character, we must add a trailing character (other than `0` or `1`; like a newline, space, a letter, etc.) to indicate we're done with the input-string after reading it character by character.

**Try it online** (with raw spaces, tabs and new-lines only).

**Example run: `input = 100`**

```
Command       Explanation                     Stack        Heap      STDIN   STDOUT

NSSN          Create Label_LOOP               []
 SSSTTSSSTN   Push 49                         [49]
 SNS          Duplicate 49                    [49,49]
 SNS          Duplicate 49                    [49,49,49]
 TNTS         Read STDIN as character         [49,49]      {49:49}   1
 TTT          Retrieve                        [49,49]      {49:49}
 TSST         Subtract (49-49)                [0]          {49:49}
 SNS          Duplicate 0                     [0,0]        {49:49}
 NTSSN        If 0: Jump to Label_1           [0]          {49:49}
 NSSSN        Create Label_1                  [0]          {49:49}
  TNST        Print to STDOUT as integer      []           {49:49}           0
  NSNN        Jump to Label_LOOP              []           {49:49}

 SSSTTSSSTN   Push 49                         [49]
 SNS          Duplicate 49                    [49,49]
 SNS          Duplicate 49                    [49,49,49]
 TNTS         Read STDIN as character         [49,49]      {49:48}   0
 TTT          Retrieve                        [49,48]      {49:48}
 TSST         Subtract (49-49)                [1]          {49:48}
 SNS          Duplicate 0                     [1,1]        {49:48}
 NTSSN        If 0: Jump to Label_1           [1]          {49:48}
 SSSTN        Push 1                          [1,1]        {49:48}
 TSST         Subtract (1-1)                  [0]          {49:48}
 NTSTN        If 0: Jump to Label_0           []           {49:48}

 NSSTN        Create Label_0                  []           {49:48}
  SSSTN       Push 1                          [1]          {49:48}
  NSSSN       Create Label_1                  [1]          {49:48}
  TNST        Print to STDOUT as integer      []           {49:48}           1
  NSNN        Jump to Label_LOOP              []           {49:48}

 SSSTTSSSTN   Push 49                         [49]
 SNS          Duplicate 49                    [49,49]
 SNS          Duplicate 49                    [49,49,49]
 TNTS         Read STDIN as character         [49,49]      {49:48}   0
 TTT          Retrieve                        [49,48]      {49:48}
 TSST         Subtract (49-49)                [1]          {49:48}
 SNS          Duplicate 0                     [1,1]        {49:48}
 NTSSN        If 0: Jump to Label_1           [1]          {49:48}
 SSSTN        Push 1                          [1,1]        {49:48}
 TSST         Subtract (1-1)                  [0]          {49:48}
 NTSTN        If 0: Jump to Label_0           []           {49:48}

 NSSTN        Create Label_0                  []           {49:48}
  SSSTN       Push 1                          [1]          {49:48}
  NSSSN       Create Label_1                  [1]          {49:48}
  TNST        Print to STDOUT as integer      []           {49:48}           1
  NSNN        Jump to Label_LOOP              []           {49:48}

 SSSTTSSSTN   Push 49                         [49]
 SNS          Duplicate 49                    [49,49]
 SNS          Duplicate 49                    [49,49,49]
 TNTS         Read STDIN as character         [49,49]      {49:10}   \n
 TTT          Retrieve                        [49,10]      {49:10}
 TSST         Subtract (49-10)                [39]         {49:10}
 SNS          Duplicate 39                    [39,39]      {49:10}
 NTSSN        If 0: Jump to Label_1           [39]         {49:10}
 SSSTN        Push 1                          [39,1]       {49:10}
 TSST         Subtract (39-1)                 [38]         {49:10}
 NTSTN        If 0: Jump to Label_0           []           {49:10}
 NNN          Exit program                    []           {49:10}

```
> 1 votes

# Answer
# C, 34 bytes

Fully portable (not just one or two character encodings).

```
f(char*s){for(;*s;)*s++^='0'^'1';}

```

Output is in-place modification of the string.

A less portable version would use a simple number in place of the expression `'0'^'1'` \- e.g. `1` for ASCII or EBCDIC - saving up to 6 bytes.

# Demo

```
#include<stdio.h>
int main(void)
{
    char s[] = "10101110101010010100010001010110101001010";
    f(s);
    printf("%s\n", s);
}

```
> 1 votes

# Answer
# Reticular, 15 bytes

```
iSBql[n1~-o]~*;

```

Try it online!

## Explanation

```
i               # Read input as string.
 S              # Push array of characters in the string.
  B             # Push every character in the array to the stack.
   q            # Reverse the stack.
    l           # Push the size of the stack.
     [     ]    # Push a function that does the following:
      n         # Convert top of stack to int.
       1~-      # Push 1, swap the top two items in the stack and subtract them.
                  This takes a character x in the input string to 1-x, resulting in the bit negation.
          o     # Output the top item of the stack
            ~   # Swap the top two items in the stack.
             *  # Call the above function the same number of times as length of the input string.
                  (That is, for each bit in the input string, negate the bit and output it.)
              ; # Exit

```
> 1 votes

# Answer
# Zsh, ~~32~~ ~~30~~ 29 bytes

Shell builtins only: specifically, the XOR operator **`^`**.

29 bytes: `<<<$[1&#1^1]${1:+`$0 ${1:1}`}` *recursion, by @GammaFunction*
~~30 bytes~~: `for X (${(s::)1})printf $[1^X]` *more efficient `for`, by @GammaFunction*
~~32 bytes~~: `for X in ${(s::)1};printf $[1^X]`

---

# Bash, 35 bytes

35 bytes: `echo $[1^${1:0:1}]${1:+`$0 ${1:1}`}` *recursion, by @GammaFunction*
~~44 bytes~~: `for((;i<${#1};i++));{ printf $[1^${1:i:1}];}`
> 1 votes

# Answer
# naz, 62 bytes

```
2a2x1v4a8m2x0v1x0f1a1o1f0x1x1f1r3x1v2e3x0v0e1s1o1f0x1x2f0a0x1f

```

Works for any input file of 1's and 0's terminated with the control character STX (U+0002).

**Explanation** (with `0x` commands removed)

```
2a2x1v                   # Set variable 1 equal to 2
4a8m2x0v                 # Set variable 0 equal to 48
1x0f1a1o1f               # Function 0
                         # Add 1 to the register, output, then jump to function 1
1x1f1r3x1v2e3x0v0e1s1o1f # Function 1
                         # Read a byte of input
                         # Jump to function 2 if it equals variable 1
                         # Jump to function 0 if it equals variable 0
                         # Otherwise, subtract 1 from the register, output,
                         # then jump back to the start of function 1
1x2f0a                   # Function 2
                         # Add 0 to the register
1f                       # Call function 1

```
> 1 votes

# Answer
# Vyxal, 1 byte

Try it Online!
> 1 votes

# Answer
# Seed, 4001 bytes

```
12 22467800860124070178830737520017462583858242261688818083563967964459492073122807697499205500520814270057390910850070898023779372337845606451434999597324513116009103282793138363889251070541548956324245082329674394635061703600124082725719347051922338244963555154324370355238030226191755446700141538448744882828401289257105544925638425778005923480537339123570198316859318125063896435356052960878798108984454300034802385262580209301524236136248719519921946031828718409466542238635588879942564163080889109125277745199171883349061520869997942949639546109688688788190940395919772174262841234098191606390237829497693620421210677789981161937899626045826080802574655497452130041254940986107805698757014260882449573944556602129769737703315763962652354056343895230431267996034382053925203053307001003333804173344801825634791820695141553355621023990400711189803634409496082889140704419749000824286397618093636247662749951187708752873519950104578968340972361618524412325645098713699731021088671725575084245344751522649567245480821120339220564646068943031946783303903697367253955714044444736783957222575572241319818457276409266126595415669073513253183989135440889608714964831521757016620819816850763183162405901035026179418588534822021105457990128662024405359920540011554379532044740831623941815066395865241509740805855343347903491296220782048364612164349265833607844707347159345067371895976293721572188715573401930387350648051542907586789168439477137453524755084958277596405623536912666957589117645881846750438246766165234099806368247856450957646185589082789378547512134409783416060602945874310445999221638049305359530033182401798760305340764937308446248612494477798147335809113299917339976366532774445821809050635734106638274070832257786599315353165493685027605339636316348551394743274112960759253605959515456316478044100123168731682979291374569338572092082869123150387567271191092971638844368321984656886356084605909222030710150000407927489274727063860328145859688080273381880596439423213732909155412724144303878876832255238035073247552082203299616735975900731438704855017567941085339636443620043767639365385673296669965015825191217275207514003602363380064736873151800792178445714348743862550536432711191527537777366511426388278812825671029910854980928682139046501881451902927544724305377340163929216935010743857978836424566071713806944632017276688837315532946743339777915616030011161708954637903288482182308670771005462983742584744344066707662057998285468364681750429465060696832417939697844369858677491150502866685111618816518160802785248209223095658989030839275159107736257541077894710268795690490482316124636074318996932638195319298458661969220607094970584356214121664089841491446209143755531268896976923041463145479413553581327439998726678121104922190297288358873060196647710463668580909699483989882954140817314685815779877890795712718361623431063616953603383264989936053474641614569529053703569694229770237259956181704387417633362063048253194547238628479951576197180647512354097114011449776247632199450163435658817379247320758050414702476804424429759571774687799269847272241040125929986561154071306898735707411802043172870573801610582124052361577796587449450980584367871604033018651000439099472710719881306790290886915898325194141014611846079395667807264562687901178526268969175193051163108905837484413417816154510711926841899863006227166207619380521870269028440296101561963248505036429083164400024679203296550171382565396820939898890114978768872643479708314697168816959694732131149657059289619022081777426733646802338248337315031956161258755974424581432365955447254124547801478393685789570178512768654602326030764253268669713151354485782078002288517388185165706102804594623909510752146365156058948091625484531645749465785838573681651816640209540090471551546428418684230905961729447735111300809970327136013512273479286642147001855525584783017763430816620169651297763121245380125111624755448069360703085235290573427681024676161302183767200167011805149778397302405685676191974385732998259279459936937214011

```

Doesn't work on TIO.
> 1 votes

# Answer
# Julia, 29 bytes

```
x->replace(x,'0'=>'1','1'=>0)

```

Attempt This Online!

Julia also has the operator `~` for bitwise not:

julia> x=0b10101110101010010100010001010110101001010
0x0000015d5288ad4a

julia> bitstring(x)
"0000000000000000000000010101110101010010100010001010110101001010"

julia> bitstring(~x)
"1111111111111111111111101010001010101101011101110101001010110101"
```
</code></pre>
> 1 votes

# Answer
# Julia, 20 bytes

```
x->join('1'.-[x...])

```

Attempt This Online!

-4 bytes thanks to Steffan
> 1 votes

# Answer
# BitBitJump `-16`, 61 bytes

```
-1 96
-1 87
22 -1
87 -1
-1 -1
-1 -1
-1 -1
-1 -1
-1 -1
-1 -1 0

```

TIO doesn't allow passing arguments to the compiler so I called the program manually.

Try it online!

16-bit mode is not very useful outside of minimizing offsets because self-modifying code is unable to encode a negative offset. This is because in all word sizes, the offsets are read stored in an int32 array and they are not properly sign extended unless the source was sign extended.

So for example, if I do

```
    .include lib.bbj

    .copy A, B
    A:0 B:-1

```

The result will be this:

```
    A:65535 B:-1

```

The code expects a string followed by a newline.

Explained:

```
    # Read bit 0 from stdin to "x"
  L:-1   i:x
    # Store bit 1 to bit 7 of the jump offset of this instruction.
    # When '\n' (00001010), bit 1 will be set and instead of jumping to the next
    # instruction (96), it will jump to e (224)
    -1     j'7     j:?
    # Bits [7:6] of i are 01. When the first bit of stdin is copied here,
    # it will either target i'6 or i'7.
    # It basically becomes {1, 0}[i], flipping the bit.
  x:i'6    -1
    # When the IP interprets e, it sees -1, 240, -1, which exits.
    #   -1 240 -1
    j'7  e:-1
    # Copy the rest of stdin to stdout
    -1     -1
    -1     -1
    -1     -1
    -1     -1
    -1     -1
    # Loop
    -1     -1    L

```

This code compiles to this.

```
-1 96 48    # 1111111111111111 0000000001100000 0000000000110000
-1 87 96    # 1111111111111111 0000000001010111 0000000001100000
22 -1 144   # 0000000000010110 1111111111111111 0000000010010000
87 -1 192   # 0000000001010111 1111111111111111 0000000011000000
-1 -1 240   # 1111111111111111 1111111111111111 0000000011110000
-1 -1 288   # 1111111111111111 1111111111111111 0000000100100000
-1 -1 336   # 1111111111111111 1111111111111111 0000000101010000
-1 -1 384   # 1111111111111111 1111111111111111 0000000110000000
-1 -1 432   # 1111111111111111 1111111111111111 0000000110110000
-1 -1 0     # 1111111111111111 1111111111111111 0000000000000000

```
> 1 votes

# Answer
# Thunno 2 `B`, 3 bytes

```
1Æ^

```

Attempt This Online!

Inspired by Dennis's GolfScript answer.

#### Explanation

The `B` flag does most of the heavy-lifting here.

```
    # Implicit input. The B flag converts the
    # input string to a list of codepoints.
1Æ^ # Compute the bitwise XOR of each codepoint
    # with 1, so 48 -> 49 and 49 -> 48
    # Implicit output. The B flag converts the
    # integer list to a string.

```
> 1 votes

# Answer
# Ruby, ~~37~~ 32

```
$*[0].each_char{|x|p x==?0?1:0}

```
> 0 votes

# Answer
## Scala, 33 bytes

```
print(readLine map(c=>"10"(c&1)))

```
> 0 votes

# Answer
# Powershell 41

```
(($args-split''-ne'')|%{1-bxor$_})-join''

```

**Explanation**:

It reads the input and splits it to turn it into an array. Then it iterates through every element of the array and uses the bitwise exclusive or to turn 1 to 0 and 0 to 1, and then joins the result and prints it to console...
> 0 votes

# Answer
# JavaScript 56

```
a=prompt()
for(b='',r=/./g;c=r.exec(a);b+=c^1);
alert(b)

```
> 0 votes

# Answer
## Batch - 167 Bytes

```
@echo off&setlocal enabledelayedexpansion&set l=-1&set s=%~1&set o=%~1
:c
if defined s set/al+=1&set s=%s:~1%&goto c
for /l %%a in (%l%,-1,0)do set/p=!o:~%%a,1!<nul

```

Could be cut down a bit by using Powershell to get the length of the input - then again, it could be cut down a lot by using a different language.
> 0 votes

# Answer
## Groovy - 31 28 chars

edit thanks to cfrick's insightful comment:

```
print args[0].tr("01","10")

```

previous:

```
args[0].each{print it=="1"?0:1}

```
> 0 votes

# Answer
## Python 3 - 50 bytes

```
r=str.replace
r(r(r(input(),'1','a'),'0','1'),'a','0')

```

It's not as short as some of the other ones, but it takes a different approach.
> 0 votes

# Answer
# php, 41 bytes

Where $s is the string:

```
str_replace(array(1,0,2),array(2,1,0),$s)

```

This works because the str\_replace() function is just a loop when given an array. This works like this:

* replace all `1` with `2`
* then all `0` with `1`
* then the `2` back to `0`
> 0 votes

# Answer
## Java, 101 bytes

```
class R{String r(String s){return s.replaceAll("0", "2").replaceAll("1", "0").replaceAll("2", "1");}}

```

**Ungolfed**

```
class R{
    String r(String s){
        return s.replaceAll("0", "2").replaceAll("1", "0").replaceAll("2", "1");
    }
}

```
> 0 votes

# Answer
# Vitsy, ~~13~~ 12 Bytes

Byte size reduced by newest version ending execution on end of file\*.

```
I\[i1+2M]l\N
I\             Repeat everything in the [] for input stack's length.
  [i1+2M]      Grab an item from the input, add 1 and modulo 2 (to invert the number).
         l\    Repeat the next character for the currently active program stack's length.
           N   Output the top item of the stack as a number.

```

\*In situations that don't involve special cases.
> 0 votes

# Answer
## Mathematica / Wolfram Language

Three solutions here, all of which assume that the argument is being passed as a string in a variable "b". If it is being passed in another format (as I think some of the other solutions here assume), shorter solutions are possible.

**Method 1, using bitwise operator for 64 char**

```
StringJoin[ToString[BitNot[#] + 2] & /@ ToExpression[Characters@b]]

```

**Method 2 using If/Then for 45 char**

```
StringJoin[If[# == "0", "1", "0"] & /@ Characters@b]

```

**Method 3, operating directly on the string, for 34 char**

```
StringReplace[b, {"0" -> "1", "1" -> "0"}]

```

I suspect some Mathematica wizard is going to breeze in here and do it in 15 bytes.
> 0 votes

# Answer
# , 13 chars / 23 bytes

```
ô⟦ï]ć⇝a^1)ø⬯)

```

`Try it here (Firefox only).`
> 0 votes

# Answer
# TeaScript, 8 bytes

```
xl(#l^1)

x       //input
 l(#    //loops through every character of the input
    l^1 //find the inverse of each character
       )

```

Try it online at its online interpreter (**DOES NOT WORK IN CHROME**).
> 0 votes

# Answer
# C, 42 bytes

```
main(c){for(;c=~getchar();putchar(~c^1));}

```
> 0 votes

# Answer
# Ruby, 48 bytes

```
$<.each_char{|i|print (i.ord-1).chr.gsub"/","1"}

```

Not the shortest, but somewhat interesting
> 0 votes

# Answer
# Python 3, 57 bytes

```
print(''.join(['0' if i=='1' else '1' for i in input()]))

```
> 0 votes

# Answer
## Pyth, 8 bytes

```
VwpCxCN1

Vw       for every char in input
     CN  compute char code of char
    x  1 xor with 1
   C     convert from int to char
  p      print

```
> 0 votes

# Answer
# pb, 46 bytes (non-competing)

```
^w[B!0]{w[B=48]{vb[1]^b[0]}>}vw[X!0]{<b[48+B]}

```

pb is newer than this challenge is, so it can't compete. Oh well.

In pb, the input lives at Y=-1. This program loops over the whole input, putting a 1 below any bytes in the input with a value of 48, or '0'. At the end of the input, it goes back to Y=0 and heads right, adding 48 to everything. Spaces that were left alone become 48=='0', spaces with a 1 value become 49=='1'.

**Explained:**

```
^w[B!0]{        # For each byte of input:
    w[B=48]{      # While byte == '0':
        vb[1]^      # Place a 1 on the canvas below it
        b[0]        # Clear input char (just to break loop)
    }
>}

vw[X!0]{<       # For each point on the canvas below the input:
    b[48+B]       # Add 48 to the existing value (convert digit to ASCII)
}

```
> 0 votes

# Answer
# Beam, 54 bytes

While I having some fun playing with beam, hears the shortest I've managed to do for this one so far. All the unused spaces are a wee bit annoying, but I might be able to compress this a wee bit more.

```
'''''''>`+++++\
v+<--n<rSP(++ /
 Hu(`<
(@   r^
>@pS r^

```

Boiled down it compares the the ascii value of STDIN to the ascii value of 1 and decrements if 1 or increments otherwise. It doesn't throw errors or anything if non zeros or ones are encountered.

Try it in the snippet

```
var ITERS_PER_SEC = 100000;
var TIMEOUT_SECS = 50;
var ERROR_INTERRUPT = "Interrupted by user";
var ERROR_TIMEOUT = "Maximum iterations exceeded";
var ERROR_LOSTINSPACE = "Beam is lost in space";

var code, store, beam, ip_x, ip_y, dir, input_ptr, mem;
var input, timeout, width, iterations, running;

function clear_output() {
document.getElementById("output").value = "";
document.getElementById("stderr").innerHTML = "";
}

function stop() {
running = false;
document.getElementById("run").disabled = false;
document.getElementById("stop").disabled = true;
document.getElementById("clear").disabled = false;
document.getElementById("timeout").disabled = false;
}

function interrupt() {
error(ERROR_INTERRUPT);
}

function error(msg) {
document.getElementById("stderr").innerHTML = msg;
stop();
}

function run() {
clear_output();
document.getElementById("run").disabled = true;
document.getElementById("stop").disabled = false;
document.getElementById("clear").disabled = true;
document.getElementById("input").disabled = false;
document.getElementById("timeout").disabled = false;

code = document.getElementById("code").value;
input = document.getElementById("input").value;
timeout = document.getElementById("timeout").checked;

code = code.split("\n");
width = 0;
for (var i = 0; i  width){
  width = code[i].length;
 }
}
console.log(code);
console.log(width);

running = true;
dir = 0;
ip_x = 0;
ip_y = 0;
input_ptr = 0;
beam = 0;
store = 0;
mem = [];

input = input.split("").map(function (s) {
  return s.charCodeAt(0);
 });

iterations = 0;

beam_iter();
}

function beam_iter() {
while (running) {
 var inst;
 try {
  inst = code[ip_y][ip_x];
 }
 catch(err) {
  inst = "";
 }
 switch (inst) {
  case ">":
   dir = 0;
   break;
  case "<":
   dir = 1;
   break;
  case "^":
   dir = 2;
   break;
  case "v":
   dir = 3;
   break;
  case "+":
   if(++beam > 255)
    beam = 0;
   break;
  case "-":
   if(--beam < 0)
    beam = 255;
   break;
  case "@":
   document.getElementById("output").value += String.fromCharCode(beam);
   break;
  case ":":
   document.getElementById("output").value += beam;
   break;
  case "/":
   dir ^= 2;
   break;
  case "\\":
   dir ^= 3;
   break;
  case "!":
   if (beam != 0) {
    dir ^= 1;
   }
   break;
  case "?":
   if (beam == 0) {
    dir ^= 1;
   }
   break;
  case "_":
   switch (dir) {
   case 2:
    dir = 3;
    break;
   case 3:
    dir = 2;
    break;
   }
   break;
  case "|":
   switch (dir) {
   case 0:
    dir = 1;
    break;
   case 1:
    dir = 0;
    break;
   }
   break;
  case "H":
   stop();
   break;
  case "S":
   store = beam;
   break;
  case "L":
   beam = store;
   break;
  case "s":
   mem[beam] = store;
   break;
  case "g":
   store = mem[beam];
   break;
  case "P":
   mem[store] = beam;
   break;
  case "p":
   beam = mem[store];
   break;
  case "u":
   if (beam != store) {
    dir = 2;
   }
   break;
  case "n":
   if (beam != store) {
    dir = 3;
   }
   break;
  case "`":
   --store;
   break;
  case "'":
   ++store;
   break;
  case ")":
   if (store != 0) {
    dir = 1;
   }
   break;
  case "(":
   if (store != 0) {
    dir = 0;
   }
   break;
  case "r":
   if (input_ptr >= input.length) {
    beam = 0;
   } else {
    beam = input[input_ptr];
    ++input_ptr;
   }
   break;
  }
 // Move instruction pointer
 switch (dir) {
  case 0:
   ip_x++;
   break;
  case 1:
   ip_x--;
   break;
  case 2:
   ip_y--;
   break;
  case 3:
   ip_y++;
   break;
 }
 if (running && (ip_x < 0 || ip_y < 0 || ip_x >= width || ip_y >= code.length)) {
  error(ERROR_LOSTINSPACE);
 }
 ++iterations;
 if (iterations > ITERS_PER_SEC * TIMEOUT_SECS) {
  error(ERROR_TIMEOUT);
 }
}
}
```

```

Code:

    <textarea id="code" rows="8" style="overflow:scroll;overflow-x:hidden;width:90%;">'''''''>`+++++\
v+<--n<rSP(++ /
 Hu(`<
(@   r^
>@pS r^</textarea>

Input:

    <textarea id="input" rows="2" style="overflow:scroll;overflow-x:hidden;width:90%;">10101110101010010100010001010110101001010</textarea>

Timeout:
        <input id="timeout" type="checkbox" checked="checked">

        <input id="run" type="button" value="Run" onclick="run()">
        <input id="stop" type="button" value="Stop" onclick="interrupt()" disabled="disabled">
        <input id="clear" type="button" value="Clear" onclick="clear_output()">

Output:

    <textarea id="output" rows="6" style="overflow:scroll;width:90%;"></textarea>

```
> 0 votes

# Answer
# Javascript, 81 Bytes:

```
function(s){return s.replace(/1/g,'a').replace(/0/g,'b').replace(/a/g,0).replace(/b/g,1)}

```

## Test

`=>`"1001101"

`<=`"0110010"
> 0 votes

# Answer
## Clojure, 41 bytes

```
(fn[b](apply str(map #(if(= %\1)\0\1)b)))

```
> 0 votes

# Answer
## Hoon, 34 bytes

```
|*(* `tape`(turn +< (cury mix 1)))

```

Stole Dennis' method for using `char xor 1` to switch between '0' and '1'.

Return a gate that maps over the tape given, and calls `(mix n 1)` (binary xor) for each element, then cast the resulting list back to a tape.

In Hoon, the entire memory model is a binary tree of bignums. All code is evaluated on this tree, called the 'subject'. `+<` is "tree navigation syntax"; instead of specifying a name for the compiler to resolve into an axis of the subject, you can provide the axis yourself with alternating characters of `+`/`-` and `<`/`>` to walk the tree. Code within a gate is evaluated on a subject that has the arguments it was called with placed at `+<`, so we can reference the arguments directly without having to assign a name to them.

`|*` creates a wet gate, essentially a generic function, that is typechecked at the callsite with a monomorphized version of the gate. This lets us use `*` as the sample for the gate instead of having to use `|=(tape code)` \- as long as the type of the arguments at the callee are a valid list, so that `++turn` typechecks.

```
> %.  "10101110101010010100010001010110101001010"
  |*(* `tape`(turn +< (cury mix 1)))
"01010001010101101011101110101001010110101"

```
> 0 votes

# Answer
# C#, ~~47~~ 44 bytes

as an anonymous function takes a string and returns a string

```
s=>s.Aggregate("",(a,b)=>a+(b>'0'?'0':'1'));

```

~~or as an anonymous function takes a string and prints the inverted, also in 47 bytes~~

~~```
s=>{foreach(var c in s)Write(c=='0'?'1':'0');};

```~~
> 0 votes

# Answer
# Swift 3 (40 bytes)

As a closure expression that takes `x` as input and returns a String:

```
{x in String(cString:x.utf8.map{$0^1})}

```

## Explanation

```
// make a function…
let invert = { (x: String) in

  // …that will xor each UInt8 character in the input string
  let y = x.utf8.map { $0 ^ 1 }

  // …and create String from the resultant [UInt8]
  String(cString: y)
}

```
> 0 votes

# Answer
# Gogh, 5 bytes

```
{n!}m

```

This takes the logical not of the integer value of each character in the string.
> 0 votes

# Answer
# Java, 55 bytes

```
a->a.replace('0','2').replace('1','0').replace('2','1')

```

This is a `java.util.function.UnaryFunction<String>`.
> 0 votes

# Answer
# Turtlèd, 24 bytes (non-competing)

```
' !-[*+.(1'0r)(0'1r)_]'

```

\[note trailing space\]

beating the non golf langs, in a task this language is not really designed for :)

## Explanation

```
'[space]                      write space over initial square
  !                           take input into string variable
   -                          decrement the string pointer (used when writing char from string)
    [*               ]        while current cell is not *
      +.                      increment string pointer, write pointed char from string
        (1'0r)                if cell is 1, write 0, move right
              (0'1r)          if cell is 0, write 1, move right
                    _         EOF checker: if end of string var, write *, else [space]
                      '[space]write space on cell (asterisk must be here)
          [implicit]     remove trailing and leading spaces and newlines, print grid.

```
> 0 votes

# Answer
## Python 3 - ~~59~~ 41 bytes

( -18 bytes thanks to @Mego)

```
lambda s:''.join(str(1-int(c))for c in s)

```
> 0 votes

# Answer
# Reticular, 13 bytes

```
iSBl[:0Eo]~*;

```

Try it online!

### Explanation

```
iSBl[:0Eo]~*;
i              take one line of input
 S             convert string to array of chars
  B            merge array with stack
   l           push the length
    [    ]~*   active the inside (length) times
     :0        push the string "0"
       E       check for equality
        o      output
            ;  terminate program

```
> 0 votes

# Answer
# Java, 97 bytes

Inspired by a comment from 2 years ago @hdante ...

*Golfed version*:

```
String d(String s){String r="";for(int i=0;i<s.length();)r(s.charAt(i++)=='0')?"1":"0";return r;}

```

*Ungolfed version*:

```
String d(String s)
{
    String r = "";
    for (int i = 0; i < s.length();)
        r += (s.charAt(i++) == '0') ? "1" : "0";
    return r;
}

```

Nothing too fancy ...
> 0 votes

# Answer
# Befunge 98, 13 bytes

```
#@~1+:'1`2*-,

```

Increments each character, and substracts 2 if the result is greater than '1' (using a multiply instead of a conditional, i.e. using *2 * \<greater than '1'\>*).

Commented version:

```
v / Skip the next byte
  |
  |/ End
  ||
  ||/ getc, reflect IP on EOF
  |||
  |||/ push 1
  ||||
  ||||/ add
  |||||
  |||||/ duplicate TOS
  ||||||
  ||||||/ character literal
  |||||||
  |||||||/ push '1'
  ||||||||
  ||||||||/ greater than
  |||||||||
  |||||||||/ push 2
  ||||||||||
  ||||||||||/ multiply
  |||||||||||
  |||||||||||/ substract
  ||||||||||||
  ||||||||||||/ putc
  |||||||||||||
> #@~1+:'1`2*-,

```
> 0 votes

# Answer
# Binary-Encoded Golfical, 31 bytes

Noncompeting, language postdates the question.

This encoding can be converted back to Golfical's standard graphical format using the encoder/decoder provided in the Golfical github repo, or run directly by using the `-x` flag.

Hex dump of binary encoding:

```
00 80 03 00 30 14 14 0C 01 14 14 1B 14 1A 16 14
14 26 14 14 25 1B 14 00 30 00 31 17 1C 1C 1D

```

Original image:

Scaled up 45x:
> 0 votes

# Answer
## Lithp, 61 bytes + 3 for `-v1` flag

```
#S::((replace S (regex "\\d" "g") (js-bridge #X::((^ X 1)))))

```

Requires the `-v1` flag to `run.js`, as `js-bridge` is not part of the standard library yet.

Exploits the JavaScript's `String.replace` function by passing a bridge function, allowing Lithp code to handle the replacement.

Usage:

```
(
    (def i #S::((replace S (regex "\\d" "g") (js-bridge #N::((^ N 1))))))
    (print (i "01010101111000"))
)

```
> 0 votes

# Answer
# Python 3, 39 bytes

Taking input from stdin and printing to stdout:

```
for c in input():print(1-int(c),end="")

```
> 0 votes

# Answer
# Logicode, 9 bytes

```
out ~ainp

```

Try it online!
> 0 votes

# Answer
# Java, 39 bytes

```
s->{for(int i=s.length;i-->0;)s[i]^=1;}

```

## Testing

```
import java.util.Arrays;
import java.util.function.Consumer;

public class Pcg30361 {
  public static void main(String[] args) {
    Consumer<char[]> f = s->{for(int i=s.length;i-->0;)s[i]^=1;};

    char[] s = "10101110101010010100010001010110101001010".toCharArray();

    char[] expected = "01010001010101101011101110101001010110101".toCharArray();

    f.accept(s);
    System.out.println(Arrays.equals(s, expected));

  }
}

```
> 0 votes

# Answer
# Python 3.5, 54 Bytes

```
print(''.join('1'if a=='0' else '0' for a in input()))

```

Much longer now ;-; (but it depends how you interpret the Q, invert can mean "reverse" as well as "opposite")
> 0 votes

# Answer
# Python 2.7, 69 bytes

Full Program:

```
b=raw_input();a=''
for i in b:
    if i=='1':a+='0'
    else:a+='1'
print a

```

Try it online!
> 0 votes

# Answer
# Braingolf, 7 bytes

```
dn&,{_}

```

Try it online!

Kinda non-competing because braingolf *cannot* accept integer input from command-line arguments, it will always implicitly convert it to an integer if the input is only digits.

## Explanation

```
dn&,{_}  Implicit input from command-line args
d        Split number into digits
 n       Negate, all truthy values become 0, all falsey values become 1
  &,     Flip entire stack
    {_}  Print each item

```

# Old Braingolf, 12 bytes

```
i{#0-}n&,{_}

```

Try it online!

## Explanation

```
i{#0-}n&,{_}
i             Read line from STDIN, convert each char to ordinal and push to stack
 {...}        Foreach, runs on each item in stack
  #0-         Subtract 48 from each ordinal
      n       Negate, all truthy values become 0, all falsey values become 1
       &,     Flip entire stack
         {_}  Print each item

```
> 0 votes

# Answer
# q/kdb+, 8 bytes

**Solution:**

```
"01""0"=

```

**Example:**

```
q)"01""0"="1010101100010011"
"0101010011101100"

```

**Explanation:**

Same vein as the J answers, use a boolean list to index into an array of `"01"`

```
/ return list of bools where list = "0" (thus inverted)
q)"0"="1010101100010011"
0101010011101100b
/ index into array of "01" at indexes 0 or 1
q)"01" 0101010011101100b
"0101010011101100"

```
> 0 votes

# Answer
# C++, 39 bytes

```
void f(string s){for(v:s)cout<<(v<49);}

```
> 0 votes

# Answer
# Befunge-98, 12 bytes

```
'0:~\-!+:,j@

```

Try it online!
> 0 votes

# Answer
## Check, 27 bytes

Non-competing as language postdates the question.

```
   :,r>#v
#d=!pd)##.:+&:R-?

```

Check is my new esolang. It uses a combination of 2D and 1D semantics. Stack manipulation is done in 1D, while control flow is done in 2D.

This program assumes that the input bits were passed as a command-line argument.
> 0 votes

# Answer
# Aceto, 6 bytes

```
,i!ipO

```

Read a character, cast it to an int, negate it, cast it to an int again, print it, and go back to the start.
> 0 votes

# Answer
# Chip, 6 bytes

```
A~ae*f

```

Try it online!

```
A       Take bit 0x01 of input
 ~      Invert it
  a     Set bit 0x01 of output to that value
    *   Provide a constant 1 value to neighbors
   e f  Set bits 0x10 and 0x20 to 1

```

So, in English, this prints '0' if the low bit of input is on, and '1' if the low bit is off.

(Chip is a 2D language, which is why the `*` sends a signal both left and right. It sends the same up and down too. `a` and `e` don't interact, so no whitespace is needed there.)

We can handle raw binary data too, in 31 bytes:

```
A~a B~b C~c D~d E~e F~f G~g H~h

```

This simply inverts all bits.
> 0 votes

# Answer
# SmileBASIC, 38 bytes

```
INPUT S$WHILE""<S$?SHIFT(S$)<"1";
WEND

```
> 0 votes

# Answer
# Jq 1.5, 29 bytes

```
./""|map("\(1-tonumber)")|add

```

Expanded

```
  ./""                   # split into array of one character strings
| map("\(1-tonumber)")   # invert each element
| add                    # join array back into a single string

```

Try it online!
> 0 votes

# Answer
# J-uby, 14 bytes

```
~:tr&'01'&'10'

```

equivalent to `lambda { |x| x.tr("01","10")}`; literally replaces `1` with `0` and `0` with `1`.
> 0 votes

# Answer
# SQL 2017, 35 bytes

The `TRANSLATE` keyword is only available starting in SQL 2017 (is the "non-competing" rule still a thing?), and replaces all instances of characters from the second string with the corresponding character in the third.

```
SELECT TRANSLATE(a,'01','10')FROM t

```

Input is via pre-existing table `t`, per our input standards.

The triple replace for older SQL versions is nearly twice as long (**65 bytes**):

```
SELECT REPLACE(REPLACE(REPLACE(a,'0','2'),'1','0'),'2','1')FROM t

```
> 0 votes

# Answer
# RProgN 2, 5 bytes

```
³n¬w;

```

Try it online!
> 0 votes

# Answer
# ARBLE, 23 bytes

```
join(a|"."|#floor(1-a))

```

Try it online!
> 0 votes

# Answer
# OML, 10 bytes

```
1(j1^oee)L

```

Try it online!

## Explanation

```
1(j1^oee)L
1(    ee)    while stdin is not empty
  j          take a character of input
   1^        xor it with 1
     o       and output it
        L    clear the stack (stack is displayed implicitly otherwise)

```
> 0 votes

# Answer
# R, 49 bytes,

```
bitwXor(strtoi(unlist(strsplit(scan(,""),""))),1)

```

Not the shortest answer, but eh !

Here, we :

* take as input the sequence as a character string `scan(,"")`,
* split it into its digits `strsplit(x, "")`, creating a list (an **R** object),
* flatten the list `unlist(x)`, creating a vector (another **R** object).

The items in the vector are converted to integers `strtoi`, on which the **XOR** logical operation is applied `bitwXor`, with respect to `1`.

Here we're taking advantage of **R**'s recycling. Both elements of the fonction `bitwXor` are vectors, but have different length. The function reuse the shortest vector to apply the operation to each element of the longest vector.

---

Briefly, **XOR** (⊕) table of truth is :

1 ⊕ 1 = 0
1 ⊕ 0 = 1
0 ⊕ 1 = 1
0 ⊕ 0 = 0
> 0 votes

# Answer
# Excel VBA, 15 Bytes

```
y=StrReverse(x)

```

Assuming that x is a String Input, StrReverse Function can be used and the output is y As String. (Credit: Grant Peters)

A code to test the result:

```
Sub test()
    Dim x As String, y As String
    x = "10101110101010010100010001010110101001010"
    y = StrReverse(x)
    Debug.Print y
    'Output: 01010010101101010001000101001010101110101
End Sub

```
> 0 votes

# Answer
# J, 5 Bytes

That is, if array input is allowed:

```
i=:-.

```

Defines the verb i to be the 'not' function.

If string input is mandatory, there's this 10 byte solution:

```
i=:-.@"."0

```

If string *output* is also mandatory, there's this 18 byte solution:

```
i=:,@:(":@-.@"."0)

```
> 0 votes

# Answer
# Charcoal, 6 bytes

```
ＦθＩ¬Ｉι

```

Try it online!

Link is to the verbose version of the code. Explanation:

```
Ｆθ             for each character in the input as string
                implicitly print
      Ｉι       the character as a number,
     ¬          inverted
   Ｉ           and casted again as string

```
> 0 votes

# Answer
# Ahead, 10 bytes

Or is it 01 bytes?

```
~O!-84i@j~

```

Try it online!
> 0 votes

# Answer
# C# (Visual C# Interactive Compiler), 39 bytes

```
b=>b.Aggregate("",(c,d)=>c+(char)(d^1))

```

Try it online!

Shortest of all the C# solutions! You can make it even shorter with Select instead of Aggregate if the rules allow you to return a sequence of chars instead of a string.
> 0 votes

# Answer
# Keg, 4 bytes

```
÷(¬"

```

Try it online!

* `÷` splits the number into individual bits
* `(` does the following `length of stack` times
* .... `¬` logically not the top
* .... `"` right shifts to the next item

Uses latest github interpreter.
> 0 votes

# Answer
# Ly, 9 bytes

```
ir['0=up]

```

Try it online!

Pretty straightforward this time...

```
i         - read in the input a codepoints
 r        - reverse the stack
  [     ] - loop until the stack is empty
   '0=    - compare to "0"
      u   - write the test results out 0=1, 1=0
       p  - pop the

```
> 0 votes

# Answer
# TI-BASIC, 3 bytes

```
B=0

```

Same "feature" as J; assuming the binary is stored in `B`, it will display the output. Here is an explanation:

> The TI-BASIC comparison operator is =. However, = doesn't work like the normal == operator: it compares item-by-item. Keep in mind that an array is formed like this: {0,2,3}. `2={0,2,3}` returns `{0,1,0}` for example. Since TI-BASIC's bools are 1 and 0, this results in a list of 1's and 0's (They aren't strings, and every other character other than 1 would also result in 0.)
> -1 votes

# Answer
# , 3 bytes

Given the input as a boolean list:

```
not

```

# k, 1 byte

```
~

```

Logical not operator
> -1 votes

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


title: Output endless powers of 2

text:
# Question
Title: Output endless powers of 2
In any programming language, make a program that outputs infinite subsequent powers of two, starting at any power of two with finite integer exponent. There does not need to be a seperator between outputs.
Note: it only has to *theoretically* output infinite subequent powers of two given infinite integer size (so you can ignore any potential issues with floating-point).
Each power of two sufficently sized (greater than some value) must be theoretically be able to be outputted within a finite amount of time.
An example in js might look like this:

```
var num = 1;
while (true){
  console.log(num);
  num *= 2;
}
```

Remember, shortest wins

Standard Loopholes apply.

# Answer
# Vyxal, 2 bytes

```
¨²

```

Try it Online!

Builtin for infinite powers of 2.

## Vyxal, 3 bytes

```
Þ∞E

```

Try it Online!

`Þ∞` Infinite list of positive integers

`E` \\$2^x\\$
> 6 votes

# Answer
# Haskell, 12 bytes

```
p=1:map(*2)p

```

Try it online!
> 6 votes

# Answer
# Rust, 34 bytes

```
||for i in 0..{print!("{} ",1<<i)}

```

Attempt This Online!
> 4 votes

# Answer
# Husk, 2 bytes

```
İ2

```

Try it online!

Built-in solution: `İ2` = (infinite) sequence of: Powers of 2.

---

# Husk, 3 bytes

```
¡D1

```

Try it online!

Non-built-in solution: Repeatedly (`¡`) double (`D`), starting with `1`.
> 4 votes

# Answer
# Bash, ~~25~~ 22 bytes

```
f()(
echo $[1<<a++];f)

```

Try it online!

*Saved 3 bytes thanks to Digital Trauma*

Solution of Digital Trauma's:

# Bash, 18 bytes

```
echo $1
$0 $[$1*2]

```

Try it online!
> 4 votes

# Answer
# C (gcc), 31 bytes

```
n=1;f(){f(printf("%d ",n*=2));}

```

Try it online!

If passing a specific argument (with value 1) to the function was allowed (29 bytes):

```
f(n){printf("%d ",n);f(n*2);}

```

Try it online!
> 3 votes

# Answer
# Dyalog APL, ~~12~~ 10 bytes

-2 thanks to Adám

```
{⎕←2×⍵}⍣=1

```

Explanation:

* `1` starting from one,
* `⍣=` until the last result and the current one are equal (never, so infinite loop)
* `{⎕←2×⍵}` double it at each iteration, printing it
> 3 votes

# Answer
# Rust, 37 bytes

```
let mut i=1;loop{print!("{i} ");i*=2}

```

This is the same solution as in Peter's C answer.

Attempt This Online!

# 34 bytes

This is the previous invalid solution

```
fn f(n:i32){print!("{n} ");f(2*n)}

```

A neat thing is that Rust notices that this is an infinite recursion and issues a compiler warning.

Attempt This Online!
> 3 votes

# Answer
# Lua, 27 bytes

```
n=1::p::print(n)n=n*2goto p

```

Try it online!
> 3 votes

# Answer
# dc, 11 bytes

* 1 byte saved thanks to @Dadsdy

```
[r2*prdx]dx

```

Try it online!

### Explanation

```
 [r2*prdx]    # push a macro to the stack
  r           #   reverse the top two stack elements
   2*         #   multiply the top of stack by 2
     p        #   print the top of stack (the number)
      r       #   reverse the top two stack elements (macro on top again)
       dx     #   duplicate the macro and execute it recursively
          dx  # duplicate the macro and execute it for the first time

```

Note that the first multiplication fails with a warning `dc: stack empty` as multiply requires at least 2 numbers on the stack. However in GNU dc, this is just a warning, and the 2 is left on the stack and can be used correctly in the next iteration.
> 3 votes

# Answer
# ATOM, 8 characters, 12 bytes

```
1{**2}

```

Explanation:

```
{**2}

```

is a controller (function) that takes a number as input, multiplies it by 2, prints the result, and returns the new number as well. The first star is parsed as the input to the controller, and the second star is parsed as the multiplication operation.

A while loop, it submits the result of the controller back into itself until it gets a 0.

Note:

ATOM is a living language with updates happening time to time, but this program works on the version of the language before this question was posted.
> 3 votes

# Answer
# PHP, ~~21~~ 20 bytes

```
for(;;)echo 2**++$i;

```

Try it online!

There is no separator for the output, but the question didn't ask for one ;)

**EDIT**: 1 byte saved by pre-incrementing the exponent, had to add a space for the echo though
> 3 votes

# Answer
# Brain-Flak, 16 bytes

```
(()){[(({}){})]}

```

Try it online!

```
# Push a 1
(())

# While True...
{
    # Print...
    [
        # Double the value on top of stack
        (({}){})
    ]
}

```
> 3 votes

# Answer
# GFA-Basic 3.51 (Atari ST),  ~~20~~  17 bytes

A manually edited listing in .LST format. All lines end with `CR`, including the last one.

```
W 1
?2^i
IN i
WE

```

which expands to:

```
WHILE 1
  PRINT 2^i
  INC i
WEND

```

### Output

This is the output before the screen starts scrolling up.
> 2 votes

# Answer
# Charcoal, 13 bytes

```
≔¹θＷ¹«ＩθＤ⎚≦⊗θ

```

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

```
≔¹θ

```

Start with `1`.

```
Ｗ¹«

```

Repeat forever.

```
ＩθＤ

```

Output the current value.

Clear the canvas for the next pass.

```
≦⊗θ

```

Double the value.

Note that the version of Charcoal on TIO throttles the dump, which is why the code appears to take 10 seconds to overflow the output pipe; with the version of Charcoal on ATO this can be disabled using the `--nt` option.
> 2 votes

# Answer
# Rockstar, 30 bytes

```
X's 1
while X
say X
let X be*2

```

Try it (Code will need to be pasted in)
> 2 votes

# Answer
# , 19 bytes

```
repeat show(T<-T*2)

```

Try it online!
> 2 votes

# Answer
# Ruby, 19 15 bytes

*-4 thanks AZTECCO*

```
0.step{p 2**_1}

```

This loops yields subsequent numbers starting from 0 and calculates `2 ** i` for each yielded argument. `_1` refers to the first block argument since Ruby 2.7. `p` prints the calculated value to STDOUT.
> 2 votes

# Answer
# \>\<\> (Fish), does not ignore numerical limits, 49 bytes

Generally you can ignore numerical limits on this site. Just for fun this program does not and properly checks for overflows and will keep running till memory runs out.

Output in reversed decimal

```
8l0&>:?v~r&:?!~rao00.
nr1-^  \$}r:2*&+:a,:1%-&a%$

```

Try it
> 2 votes

# Answer
# Desmos, 9 bytes

```
o->2o
o=1

```

`o->2o` goes into a ticker while `o=1` is in an expression box. Start the ticker to run the code. Note that this does output all positive powers of two, even if they only show for a brief moment of time.

Try It On Desmos!
> 2 votes

# Answer
# Thunno 2, 4 bytes

```
1ƘO£

```

Attempt This Online!

There aren't any infinite lists in Thunno 2 :(

#### Explanation

```
1Ƙ    # Apply this code to each positive integer, n:
  O   #  Push 2 ** n
   £  #  And print the result

```
> 2 votes

# Answer
# \>\<\> (Fish), ~~8~~ 6 bytes

-2 thanks to @mousetail

```
1:n:+!

```

Try it
> 2 votes

# Answer
# Commodore C64 BASIC, 27 Tokenised BASIC Bytes, 20 characters with BASIC keyword abbreviations

```
0X=1
1?X:X=X*2:GOTO1

```

As this is 8-BIT BASIC, this will start to use exponent notation after 2^29, and likely run into rounding and other issues soon after.

Note that it's more performant in Commodore BASIC (and likely other 8-bit BASIC variants) to add X to itself, rather than multiplying by 2, but for this purpose it is not necessary.
> 2 votes

# Answer
# Pyth, 5 bytes

```
f!
^2

```

Try it online!

### Explanation

```
f!\n^2T    # implicitly add T
f          # find the first integer which makes lambda T truthy starting at 1
 !         #   not (makes false, thus looping forever)
  \n       #   print
    ^2T    #   2 to the power of T

```
> 2 votes

# Answer
# Desmoslang Assembly, 3 Bytes

```
2O*

```
> 1 votes

# Answer
# Python, 24 bytes

*-1 byte from @Sisyphus*

```
a=1
while[print(a)]:a*=2

```

Attempt This Online!

# Python 2, 24 bytes

```
a=1
while 1:print a;a*=2

```

Attempt This Online!
> 1 votes

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

```
for(n=1;;)console.log(n*=2)

```

Attempt This Online!

## JavaScript (Node.js), 33 bytes

```
function*(){for(n=1;;)yield n*=2}

```

Attempt This Online!
> 1 votes

# Answer
# Haskell, 14 bytes

```
p=iterate(2*)1

```

Try it online!
> 1 votes

# Answer
# Retina, 16 bytes

```
K`1
+\`.+
$.(*2*

```

Try it online! Starts with `2`. Explanation:

```
K`1

```

Set the input to `1`.

```
+`

```

Repeat.

```
\`

```

Output the result of the replacement on each pass through the loop with a trailing newline.

```
.+
$.(*2*

```

Double the (implicit) character `_`, then repeat that by the decimal (implicit) input, then take the length in decimal, i.e. double the input in decimal.
> 1 votes

# Answer
# Nekomata, 3 bytes

```
Ň2E

```

Attempt This Online!

```
Ň       Natural numbers
 2E     Power of 2

```
> 1 votes

# Answer
# Befunge-98 (PyFunge), 5 bytes

```
2<.:*

```

Try it online!

Starts from 4.
> 1 votes

# Answer
# Fortran (GFortran), 51 bytes

```
integer(kind=16)i;i=1
1 print*,2**i;i=i+1;goto1;end

```

Try it online!

Fortran's default integer max is `2147483647 (=2^31-1)` but setting `kind=16` extends the range up to `170141183460469231731687303715884105727 (=2^127-1)`
> 1 votes

# Answer
# bc, 14 bytes

```
while(1)2^x++

```

Try it online!
> 1 votes

# Answer
# Arturo, 19 bytes

```
1whileø[*2print<=]

```

```
1         ; push 1 to the stack
whileø[   ; start infinite loop
    <=    ; duplicate
    print ; print
    *2    ; double
]         ; end infinite loop(?)

```
> 1 votes

# Answer
# Nibbles, 3 bytes (6 nibbles)

```
`.;2*

```

```
`.;2*       # full program
`.;2*@$     # with implicit args added
`.          # repeatedly apply (while results are unique)
   2        # starting with 2
  ;         # (and save the 2 for later)
    *       #   multiply
     @      #   saved value of 2
      $     #   by result-so-far

```

---

Alternative approach, also 3 bytes (6 nibbles):

```
.,~^2

```

```
.,~^2       # full program
.,~^2$      # with implicit arg added
.           # map over
 ,          # list from 1..
  ~         # infinity:
   ^2       #   2 to the power of
     $      #   each element in the list

```
> 1 votes

# Answer
# 05AB1E, 2 bytes

```
∞o

```

Try it online.

**Explanation:**

```
∞   # Infinite list of positive integers: [1,2,3,...]
 o  # Take 2 to the power each value in the list
    # (after which the infinite list is output implicitly as result)

```
> 1 votes

# Answer
# MathGolf, 4 bytes

```
îóo∟

```

Try it online.

**Explanation:**

```
   ∟  # Do-while true without popping:
 ó    #  Take 2 to the power
î     #  the 1-based loop index
  o   #  Print with trailing newline without popping

```
> 1 votes

# Answer
# Go, 32 bytes, to STDERR

```
func f(n int){println(n);f(n*2)}

```

Attempt This Online!

# Go, 45 bytes, to STDOUT

```
import."fmt"
func f(n int){Println(n);f(n*2)}

```

Attempt This Online!
> 1 votes

# Answer
# Knight, 13 bytes

```
;=a 1W=a*2aOa

```

Try it online!
> 1 votes

# Answer
# Alice, 11 bytes

```
.2~E/ O \h

```

Try it online!

The trailing newline is required

```
.             Duplicates the top of the stack, or two `0` if the stack is empty
 2~           Pushes two on the stack, swap the top two items
   E          Calculates `2^n`, where `n` is the current iteration minus 1
    / O \     Prints the number
         h    Increments the exponent

```
> 0 votes

---
Tags: code-golf, math
---


title: Calculate Euclidean distance on a torus

text:
# Question
Title: Calculate Euclidean distance on a torus
Euclidean distance between two lattice points \\$(x\_1, y\_1)\\$ and \\$(x\_2, y\_2)\\$ on a plane is: \\$\sqrt{(x\_1 - x\_2)^2 + (y\_1 - y\_2)^2}\\$.

Imagine now a lattice `N x N` replicated infinitely many times next to itself. The two points \\$(x\_1, y\_1)\\$ and \\$(x\_2, y\_2)\\$ also get replicated. Euclidean distance on a torus is then the minimal distance between all these points.

Input: `x1, y1, x2, y2` and `N`. Arrange these in any convenient order or way (e.g. represent \\$(3,4)\\$, \\$(5,6)\\$ as 4 arguments `3, 4, 5, 6`, two complex numbers \\$3+4j\\$, \\$5+6j\\$, a list `[[3,4],[5,6]]`, a list `[3,4,5,6]` or anything that's not too bizarre). Coordinates must be integers in the range `0..N-1` or `1..N`. The size of the torus (`N`) must be an integer (you can assume `1 < N < 100`).

Output: a real number, with precision better than \\$1\\%\\$.

Test cases:

| x1 | y1 | x2 | y2 | N | Result |
| --- | --- | --- | --- | --- | --- |
| 1 | 0 | 1 | 1 | 2 | 1.00 |
| 2 | 3 | 2 | 3 | 4 | 0.00 |
| 0 | 0 | 2 | 2 | 4 | 2.83 |
| 0 | 9 | 1 | 1 | 10 | 2.24 |
| 9 | 0 | 9 | 8 | 10 | 2.00 |
| 12 | 34 | 56 | 78 | 99 | 62.23 |
| 0 | 0 | 98 | 98 | 99 | 1.41 |

# Answer
# , 40 bytes

```
\(a,b,N)sum(pmin((d=a-b)%%N,-d%%N)^2)^.5

```

Attempt This Online!

Input the two points as vectors `a` and `b`.
> 10 votes

# Answer
# K (ngn/k), ~~18~~ 16 bytes

-2 bytes thanks to @ngn.

Function taking input as `f[N;(x1,y1;x2,y2)]`.

```
{%+/&/x*x!:y-|y}

```

Try it online!

`y-|y` Subtract the reversed list of points from the list of points. This results in component-wise distances in both directions.
`x!:` Take all values mod *N*. Updates x.
`x*` Square each value.
`&/` take the element-wise minimum between positive and negative difference.
`%+/` Sum, then take the square root.
> 7 votes

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

```
ạ/«ạ¥ÆḊ

```

A dyadic Link that accepts the coordinates as a pair of pairs\* of integers\** on the left and the size as an integer\** on the right and yields the Euclidean toroidal distance.

* I guess this will work in any integer number of dimensions too.

\** Will work with floats too (up to floating point inaccuracies, of course).

**Try it online!** Or see the test-suite.

### How?

\\$\text{Distance} = \sqrt{\left (|x\_1-x\_2| \land ||x\_1-x\_2|-N| \right )^2 + \left (|y\_1-y\_2| \land ||y\_1-y\_2|-N| \right )^2}\\$

```
ạ/«ạ¥ÆḊ - Link: Coordinates=[[x1, y1], [x2, y2]]; Size=N
 /      - reduce (Coordinates) by:
ạ       -   ([x1, y1]) absolute difference ([x2, y2])
              -> D = [|x1-x2|, |y1-y2|]
    ¥   - last two links as a dyad - f(D, N):
   ạ    -   (D) absolute difference (N) (vectorises)
              -> D2 = [||x1-x2|-N|, ||y1-y2|-N|]
  «     -   (D) minimum (D2) (vectorises)
              -> M = [min(|x1-x2|, ||x1-x2|-N|), min(|y1-y2|, ||y1-y2|-N|)]
     ÆḊ - norm = vector_length = square_root(sum(squared_values)))
            -> (min(|x1-x2|, ||x1-x2|-N|)^2 + min(|y1-y2|, ||y1-y2|-N|)^2)^(1/2)

```
> 6 votes

# Answer
# julia, 43 bytes

Notice that for any point \\$x\\$, the \\$N\\$-toroidal distance from \\$x\\$ to \\$(N/2, N/2)\\$ is the Euclidean distance from \\$\mathrm{mod}(x, N)\\$ to \\$(N/2, N/2)\\$.

Hence, we can find the \\$N\\$-toroidal distance between \\$a\\$ and \\$b\\$ by computing the Euclidean distance from \\$\mathrm{mod}(a-b+(N/2, N/2), N)\\$ to \\$(N/2, N/2)\\$.

```
d(a,b,N)=sum(@. (mod1(a-b+N/2,N)-N/2)^2)^.5

```

Attempt This Online!
> 6 votes

# Answer
# Wolfram Language (Mathematica), ~~38~~ 33 bytes

```
nNorm[Min[#,n-#]&/@Abs[#-#2]]&

```

Thanks to @att!
Where  stands for `\[Function]`

Try it online!

Input: `[N][{x1,y1}, {x2,y2}]`
> 5 votes

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

```
αDŠ-ø€ßnOt

```

Try it online!

-1 thanks to *@KevinCruijssen*

#### Explanation

```
αDŠ-ø€ßnOt  # Implicit input
α           # Absolute difference between the first two inputs
 D          # Duplicate this pair
  Š         # Triple swap so the input is second
   -        # Subtract the absolute difference between the
            # first two inputs from the third input
    ø       # Zip this with the absolute difference
     €ß     # Minimum of each inner pair
       n    # Square each
        O   # Sum the list
         t  # Square root the sum
            # Implicit output

```
> 5 votes

# Answer
# JavaScript (ES7), 64 bytes

Expects `(x1,y1,x2,y2,N)`.

```
(x,y,X,Y,n)=>((g=d=>(d*=d)<(q=n-d**.5)*q?d:q*q)(X-x)+g(Y-y))**.5

```

Try it online!

### Commented

```
( x, y,       // (x, y) = coordinates of the 1st point
  X, Y,       // (X, Y) = coordinates of the 2nd point
  n           // n = size of the torus
) => (        //
  ( g = d =>  // g is a helper function taking d
    (d *= d)  // square d
    <         // and compare it with
    ( q =     // q defined as:
      n -     //   the difference between n and
      d ** .5 //   the square root of d (which is the
              //   absolute value of the original d)
    ) * q     // multiplied by itself
    ?         // if d is less than q²:
      d       //   return d
    :         // else:
      q * q   //   return q²
  )(X - x) +  // 1st call to g with d = X - x
  g(Y - y)    // 2nd call to g with d = Y - y
) ** .5       // square root of the sum

```
> 4 votes

# Answer
# Factor, 52 bytes

```
[ v- 2dup n-v rot '[ [ _ rem ] map ] bi@ vmin norm ]

```

Try it online!

Takes input as `N { x1 y1 } { x2 y2 }`.

```
                   ! 10 { 9 0 } { 9 8 }
v-                 ! 10 { 0 -8 }
2dup               ! 10 { 0 -8 } 10 { 0 -8 }
n-v                ! 10 { 0 -8 } { 10 18 }
rot                ! { 0 -8 } { 10 18 } 10
'[ [ _ rem ] map ] ! { 0 -8 } { 10 18 } [ [ 10 rem ] map ]
bi@                ! { 0 2 } { 0 8 }   (apply quot to both points)
vmin               ! { 0 2 }
norm               ! 2.0

```
> 4 votes

# Answer
# Python, ~~63~~ ~~59~~ 57 bytes

*Edit: -4 bytes thanks to @Neil and -2 thanks to @xnor.*

```
lambda x,y,X,Y,N:abs((x-X+(k:=N/2))%N-k+((y-Y+k)%N-k)*1j)

```

Attempt This Online!

Port of Damian Pavlyshyn's comment.
> 4 votes

# Answer
# Ruby, ~~60~~ 56 bytes

```
->a,b,n{(-4..4).map{|c|(a-b-n*(c%3-1+1i*c/=3)).abs}.min}

```

Try it online!

## How?

Input as complex numbers.

`(a-b).abs` is the distance between a and b on the complex plane. We have to move b into the 8 adjacent spaces, and calculate distance between the original a and the new b, then take the minimum.

Iterating from -4 to +4 we get the offset table using `c%3-1` for the real part, and `c/3` for the imaginary part:

```
+-----+-----+-----+
| -4  | -3  | -2  |
|-1-i | -i  | 1-i |
+-----+-----+-----+
| -1  |  0  |  1  |
| -1  |  0  |  1  |
+-----+-----+-----+
|  2  |  3  |  4  |
|-1+i |  i  | 1+i |
+-----+-----+-----+

```
> 3 votes

# Answer
# Python3, 79 bytes:

```
lambda x,y,X,Y,n:(min(abs(x-X),n-abs(x-X))**2+min(abs(y-Y),n-abs(y-Y))**2)**0.5

```

Try it online!
> 2 votes

# Answer
# Vyxal , ~~10~~ 9 bytes

```
ε:?$-Þ∵∆/

```

Thanks @TheThonnu!

Try it Online!

Input: `[x1, y1] \n [x2, y2] \n N`
> 2 votes

# Answer
# Thunno 2, 9 bytes

```
-AD⁶_Ọ²Sƭ

```

#### Explanation

```
-AD⁶_Ọ²Sƭ  # Implicit input
-A         # Absolute difference between first two inputs
  D        # Duplicate the pair
   ⁶_      # Subtract from the third input
     Ọ     # Elementwise dyadic minimum
      ²    # Square each
       S   # Sum the list
        ƭ  # Square root the sum
           # Implicit output

```

#### Screenshot
> 2 votes

# Answer
# Charcoal, 19 bytes

```
Ｉ₂ΣＥθ⌊Ｘ⁻↔⁻ι§ηκ⟦⁰ζ⟧²

```

Try it online! Link is to verbose version of code. Takes input as two pairs of coordinates and a number. Explanation:

```
    θ               First input
   Ｅ                Map over coordinates
          ι         Corrent coordinate
         ⁻          Subtract
            η       Second input
           §        Indexed by
             κ      Current index
        ↔           Absolute value
       ⁻            Vectorised subtract
              ⟦  ⟧  List of
               ⁰    Literal integer `0` and
                ζ   Third input
      Ｘ             Vectorised raise to power
                  ² Literal integer `2`
     ⌊              Take the minimum
  Σ                 Take the sum
 ₂                  Take the square root
Ｉ                   Cast to string
                    Implicitly print

```
> 2 votes

# Answer
# Scala, ~~137~~ 96 bytes

Saved 41 bytes thanks to the comment of @corvus\_192

---

Try it online!

```
import math._
(x,y,X,Y,n)=>sqrt(pow(min(abs(x-X),n-abs(x-X)),2)+pow(min(abs(y-Y),n-abs(y-Y)),2))

```
> 2 votes

# Answer
# SAS 4GL, 71 bytes (or 57)

1. *The answer (in short, just "the point"):*

```
data;set;a=abs(x-p);b=abs(y-q);d=sqrt((a><(N-a))**2+(b><(N-b))**2);run;

```

---

2. *The answer and all details \[with details ;-)\]:*

Input:

```
data input;
/* x1 y1 x2 y2 N Result */
input x y p q n r;
cards;
1   0   1   1   2   1.00
2   3   2   3   4   0.00
0   0   2   2   4   2.83
0   9   1   1   10  2.24
9   0   9   8   10  2.00
12  34  56  78  99  62.23
0   0   98  98  99  1.41
;
run;
/* to print input data */
proc print data=input;
run;

```

Immediately after "input code" run: Code:

```
data;set;a=abs(x-p);b=abs(y-q);d=sqrt((a><(N-a))**2+(b><(N-b))**2);run;

```

The:

```
data;set;...run;

```

part is mandatory for every SAS 4GL code so if we select only the "calculation" part:

```
a=abs(x-p);b=abs(y-q);d=sqrt((a><(N-a))**2+(b><(N-b))**2);

```

it is 57 bytes ;-)

Code formatted:

```
data;
  set;
  a = abs(x - p);
  b = abs(y - q);

  d = sqrt(
            (a >< (N - a))**2
          + (b >< (N - b))**2
          );
run;

```

Comments:

* `i><j` is minimum of i and j, `i**j` is i to power j
* `sqrt(expression)` is the same number of bytes as `(expression)**.5`,
* brackets arounf `N-b` are necessary because `><` takes precedence over substraction,
* result dataset is named `DataX` where X is the first integer not yet used for naming default dataset.

Log:

```
1    data;set;a=abs(x-p);b=abs(y-q);d=sqrt((a><(N-a))**2+(b><(N-b))**2);run;

NOTE: There were 7 observations read from the data set WORK.INPUT.
NOTE: The data set WORK.DATA4 has 7 observations and 9 variables.
NOTE: DATA statement used (Total process time):
      real time           0.00 seconds
      cpu time            0.00 seconds

```

---
> 2 votes

# Answer
# Japt, 13 bytes

```
íaV ËmDaWÃx²¬

```

Try it

```
íaV ËmDaWÃx²¬     :Implicit input of arrays U=[x1,y1] & V=[x2,y2] and integer W=N
í V               :Interleave U & V
 a                :  Reducing each pair by absolute difference
    Ë             :Map each D
     m            :  Minimum with
      DaW         :    Absolute difference of D & W
         Ã        :End map
          x       :Reduce by addition after
           ²      :  Squaring each
            ¬     :Square root

```
> 2 votes

# Answer
# Arturo, 57 bytes

```
$=>[x:abs&-&y:abs&-&n:&sqrt+^min@[x,n-x]2(min@[y,n-y])^2]

```

Try it

Takes input as `x1 x2 y1 y2 N`.

```
$=>[                 ; a function
    x:abs&-&         ; assign absolute value of first arg minus second arg to x
    y:abs&-&         ; assign absolute value of third arg minus fourth arg to y
    n:&              ; assign fifth arg to n
    (min@[y,n-y])^2  ; minimum of y and n-y squared
    ^min@[x,n-x]2    ; minimum of x and n-x squared
    +                ; add
    sqrt             ; square root
]                    ; end function

```
> 1 votes

# Answer
# BQN, 17 bytes

```
{√+´×˜⌊´|-⊸⋈-´}

```

Try it at BQN REPL

```
{√+´×˜⌊´|-⊸⋈-´}  # function taking N as left arg ()
                    # and [[x1,y1],[x2,y2]] as right arg ():
              -´   # vectorized fold-subtract: [x1-x2,y1-y2]
          -⊸⋈      # joined to negative of itself: [[x1-x2,y1-y2],[x2-x1],[y2-y1]]
        |          # all modulo N
      ⌊´            # vectorized fold-minimum
    ×˜              # vectorized multiply each element by itself
  +´                # sum (fold-addition)
 √                  # square-root

```
> 1 votes

# Answer
# Scala, 104 bytes

Golfed version. Try it online!

```
(a,b,N)=>{val d=a.zip(b).map{case(p,q)=>(p-q+N)%N};math.sqrt(d.map(r=>math.pow(math.min(r,N-r),2)).sum)}

```

Ungolfed version. Try it online!

```
object Main {

  def main(args: Array[String]): Unit = {
    println(toroidal_dist(Array(1, 0), Array(1, 1), 2))    // 1
    println(toroidal_dist(Array(2, 3), Array(2, 3), 4))    // 0
    println(toroidal_dist(Array(0, 0), Array(2, 2), 4))    // 2.83
    println(toroidal_dist(Array(0, 9), Array(1, 1), 10))   // 2.24
    println(toroidal_dist(Array(9, 0), Array(9, 8), 10))   // 2
    println(toroidal_dist(Array(12, 34), Array(56, 78), 99)) // 62.23
    println(toroidal_dist(Array(0, 0), Array(98, 98), 99)) // 1.41
  }

  def toroidal_dist(a: Array[Int], b: Array[Int], N: Int): Double = {
    val d = a.zip(b).map { case (ai, bi) => (ai - bi + N) % N }
    math.sqrt(d.map(di => math.pow(math.min(di, N - di), 2)).sum)
  }
}

```
> 0 votes

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