title: Convert binary to unary

text:
# Question
Title: Convert binary to unary
The title says it all; Given a number in the binary (base-2) number system, output the same number expressed in unary (base-1).

You should take the binary number as a string (optionally with a separator), list, or equivalent structure of digits, using any number or digit you like for the digits. The unary output can use any aforementioned format, and it should use a single-digit throughout the number but does not have to be consistent for different input values. You may choose to assume that the binary number will have no more than 8 bits, and/or that it will always be left-padded with zero bits to a certain length.

One method you may use to achieve this task is documented at this esolangs.org article:

1. Replace all `1`s with `0*` (Using `*` as the unary digit; you may use any character.)
2. Replace all `*0`s with `0**`.
3. Remove all `0`s.

Here are some examples, using `0` and `1` for the binary digits and `*` for the unary digit:

* `1001``*********`
* `1010``**********`
* `00111111``***************************************************************`
* `00000` → (empty output)

This is , so the shortest answer in each language wins.

# Answer
# TypeScript's Type System, ~~130~~ 128 bytes

```
//@ts-ignore
type R<S,F,X>=S extends`${infer A}${F}${infer B}`?R<`${A}${X}${B}`,F,X>:S;type B<S>=R<R<R<S,1,"02">,20,"022">,0,"">

```

Try it at the TypeScript Playground!

Uses 2 as the unary digit. Defines a utility type to recursively remove all occurrences of a given string with a different string, and then defines the main type which is a series of nested calls to the utility type.
> 11 votes

# Answer
# Vyxal, 2 bytes

```
BI

```

Try it Online! or see it with asterisks instead

Same as my Thunno 2 answer.

#### Explanation

```
BI  # Implicit input
B   # From binary
 I  # That many spaces
    # Implicit output

```
> 10 votes

# Answer
# Excel, 20 bytes

```
=REPT(9,BIN2DEC(A1))

```

Input in cell `A1`.
> 9 votes

# Answer
# Haskell, 26 bytes

```
f l=10^foldl((+).(2*))0l-1

```

Try it online!

Input is a list of `0/1`, output is a number like `9999999999` made of the digit `9`.

Haskell is interesting for this challenge because it lacks base-conversion built-ins without imports, so we have to do it ourselves. This answer folds the operation `\n b->n*2+b` over the list of bits to get a number `k`, then computes `10^k-1` to get a number made of `k` 9-digits. The 9's trick is shorter than more natural methods like `replicate k 1` or `1<$[1..k]` or `take k[0,0..]`.

It's slightly longer to do the power-of-10 within the fold and decrement after:

**27 bytes**

```
pred.foldl(\n b->n^2*10^b)1

```

Try it online!

though if we bend the rules and represent bits as `1` or decimal `10`, we can do

**21 bytes**

```
pred.foldl((*).(^2))1

```

Try it online!

# Haskell, 26 bytes

```
foldl(\s b->s++s++[1|b])[]

```

Try it online!

Input is list of Booleans, output is a list of 1's. This iterates over the list of Booleans, each time doubling the current string then appending an additional `1` if the bit is `True`.
> 8 votes

# Answer
# Python 3, 21 bytes

```
lambda s:"*"*int(s,2)

```

Try it online!
> 6 votes

# Answer
# APL (Dyalog Extended), 3 bytes

Anonymous tacit prefix function. Takes list of binary digits and returns list of `1`s

```
⊥⍴≡

```

Try it online!

the base-2 evaluation

**r**eshapes

the depth (nesting level, which is always 1 for a list)
> 5 votes

# Answer
# TypeScript Type System, 79 bytes

```
type B<S>=S extends`${infer Q}${infer V}`?`${B<V>}${B<V>}${Q extends"1"?Q:""}`:S

```

Try it on the Typescript Playground!

Note: This works with little-endian binary, not big-endian.

While the algorithm in the post allows simply performing replacements, we can take advantage of Typescript's ability to anchor string matches for a much simpler algorithm.

Essentially, `S extends`${infer Q}${infer V}`` matches the first character `Q` and the rest of the string `V`. We recurse on `V` twice, and append a 1 if `Q` is a 1.
> 5 votes

# Answer
# x86+MMX machine code, 10 bytes

Despite the question only saying the input has to be "binary", comments seem to imply they're thinking of a text string of base-2 digits, not 1-bit digits packed into an integer which a computer can already use directly as an unsigned integer. If that's allowed, see my 7-byte answer on Output / Convert to unary number.

This is that answer plus conversion from 8 bytes to an 8-bit integer, by extracting the high bit of each input. Input is in `mm0`, an MMX vector register, with the lowest element being the *least* significant. (If stored to memory, this would be opposite of standard printing order where the most significant goes first, at the lowest address of a string.)

```
   ; machine code    |   NASM source
                       ; RDI or ES:EDI = output buffer of size n+1
                       binary_to_unary:
                       ;  pslld    mm0, 7     ; 4 bytes. For input digits '0' / '1', shift the low bit to high
  0FD7C8                pmovmskb ecx, mm0    ; pack the binary digits into an integer in ECX
                                             ; memset(dst, '1', n)
  B031                  mov      al, '1'
  F3AA                  rep stosb
  880F                  mov byte [rdi], cl   ; terminate the C-style string
  C3                    ret

```

For ASCII `'0'` / `'1'` input, we'd start with `pslld mm0, 7` to shift the low bit to the high position of each byte. Also, if the digit-string was loaded from a string in memory in printing order (most significant at lowest address), we'd need to byte-reverse. In that case scalar code to read input would be smaller than `movbe` or load+`bswap` in an integer register + `movq mm0, rax`, or `psufb` with an 8-byte vector constant.

In this current version, our input string in an MMX register is effectively big-endian, most significant digit in the highest element number (on the left when writing it in the notation Intel manuals use to document vector instructions).

# x86 scalar machine code, 14 bytes, input from a C string in printing order

* RDI or ES:EDI points to an input buffer of base-2 ASCII digits, terminated by a `0` byte (or any byte below ASCII `'0'`), padded to at least 32 digits.
* RSI or ES:ESI points to an output buffer of size n+1, will be filled with `'0'` digits and terminated with a `0`.

Callable from C with the x86-64 System V calling convention as `void binary_string_to_unary(const char *binary_src, char *unary_dst);`. Use the x32 ABI for 32-bit pointers, or change the `mov edi, esi` to `push rsi`/`pop rdi` to copy a 64-bit register with the same code size. (Or use the same binary machine code in 32-bit mode.)

```
               binary_string_to_unary:
  B030           mov      al, '0'    ; input digit to compare against, also the output digit
               .loop:
  11C9           adc    ecx, ecx     ; ECX = 2*ECX + CF
  AE             scasb               ; set FLAGS like cmp al, [rdi] then increment RDI.   CF=1 for digit='1', CF=0 for digit='0'.
  76FB           jbe   .loop         ; while('0' <= digit);   i.e. while digit >= '0', false for digit = 0 terminator

  89F7           mov   edi, esi      ; x32 ABI, or for 32-bit mode.  For full 64-bit pointers, push rsi / pop rdi
  F3AA           rep stosb           ; memset(rdi, al='0', rcx)
  880F           mov   [rdi], cl     ; terminate the C-style string
  C3             ret

```

Note that we don't `xor ecx,ecx` before the loop. Instead we rely on the input string being '0'-padded to at least 32 digits, so the previous contents get shifted out.

There might be a way (with same code size) to take the input pointer in RSI like you'd expect from the traditional meanings of those registers, perhaps with `lodsb` / `cmp al, '0'` (3 bytes instead of 1 for scasb, but avoiding the 2-byte `mov edi, esi` after the loop). Change the branch conditions accordingly for comparing in the other direction. Except that would get CF=0 for digit='1'. So maybe `add al, 255-'0'` so '1' produces a carry-out but '0' doesn't? And the terminator is a value that results in some FLAGS condition that the other two don't, perhaps a signed overflow and/or the sign flag.
> 5 votes

# Answer
# brainfuck, 53 bytes

Takes a string of `0` and `1` characters, outputs a string of `1`s.

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

```

**Explaination**

```
>,[                 read a character
>-[<->-----]<+++    subtract 48 to turn it into 0/1
<[->++<]            double the existing sum and add it to the new digit
>>,]                read another character and repeat if not EOF
>-[<+>-----]<--     make 49
<[->.<]             print 49 the necessary number of times

```

Try it online!
> 5 votes

# Answer
# Husk, 3 bytes

```
B1ḋ

```

Try it online!

```
  ḋ  # interpret input as binary digits
B    # and convert this to base
 1   # 1

```
> 4 votes

# Answer
# Mathematica, 14 bytes

As a list of '1's:

```
Table[1,2^^#] &

```

Anonymous function. Would probably be 10 bytes in the hypothetical mthmca golfing language.
> 3 votes

# Answer
# C (clang), ~~60~~ 58 bytes

```
i;f(char*s){for(i=0;*++s;i+=i+*s-48);i&&printf("%0*d",i);}

```

Attempt This Online!
> 3 votes

# Answer
# , 22 bytes

```
\(x)rep(1,strtoi(x,2))

```

Attempt This Online!

Convert from binary and repeat `1` that many times.

Unfortunately shorter than the more-interesting (I think):

# , ~~36~~ 34 bytes

*Edit: -2 bytes thanks to pajonk*

```
\(x)Reduce(\(a,b)c(a,a,b[b]),x,{})

```

Attempt This Online!

Input is a vector of binary digits; fold over (`Reduce`) this from the left, starting with an empty vector (`NULL`), at each step duplicating whatever we've got so far, and appending the new digit if it's a `1`.
> 3 votes

# Answer
# TI-Basic, 15 bytes

```
1 or rand(.5sum(Ans2^cumSum(1 or Ans

```

Input is taken as a list of `0`s and `1`s in little-endian binary in `Ans`. Output is a list of `1`s.
> 3 votes

# Answer
# Ruby, 20 bytes

```
->(b){?**b.to_i(2)}

```

Try it online!

It goes from binary to a decimal integer, and becomes a factor by which an asterisk char is multiplied.

(Idea to switch to char from string was suggested by Travis. Thanks!)

---

# Ruby, 21 bytes | (old)

```
->(b){"*"*b.to_i(2)}

```

Try it online!

Same as the upper one, but the upper one has been improved.
> 3 votes

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

```
x=>'x'.repeat('0b'+x)

```

Try it online!
> 2 votes

# Answer
# , 4 or 5 bytes

```
#.##

```

Uses the length of the input digit list for the unary digit.

Attempt This Online!

Like 05AB1E, uniformity is one extra byte, with alternatives.
> 2 votes

# Answer
# Perl 5, 15 bytes

```
$_=9x oct"0b$_"

```

Try it online!

Outputs 9 (my chosen char) the number of times given in the input binary number.
> 2 votes

# Answer
# PowerShell, 28 bytes

```
"*"*[Convert]::ToInt32($_,2)

```

Try it online!
> 2 votes

# Answer
# Kotlin, 22 bytes

```
{"*".repeat(toInt(2))}

```

Try it online!
> 2 votes

# Answer
# Thunno 2, 2 bytes

```
Ḃṣ

```

Try it online! or see it with asterisks instead

Uses spaces.

#### Explanation

```
Ḃṣ  # Implicit input
Ḃ   # From binary
 ṣ  # That many spaces
    # Implicit output

```
> 1 votes

# Answer
# Charcoal, 3 bytes

```
⍘Ｓ²

```

Try it online! Link is to verbose version of code. Outputs a string of `-`s. Explanation:

```
 Ｓ  Input string
⍘   Convert from base
  ² Literal integer `2`
    Print as row of `-`s

```

Unfortunately `BaseString(2, InputString())` performs a different operation, which means I can't use implicit input to save a byte.
> 1 votes

# Answer
# Arturo, 23 bytes

```
$=>[@.of:from.binary&1]

```

Try it!

Returns a list of digits.

```
$=>[             ; a function where input is assigned to &
    from.binary& ; convert input from binary string to decimal integer
    @.of: _ 1    ; create list of that many 1s
]                ; end function

```
> 1 votes

# Answer
# Retina 0.8.2, 16 bytes

```
1
01
+`10
011
0

```

Try it online! Link includes test cases. Explanation: A direct interpretation of the method given in the question, except using `1` instead of `*` for obvious reasons. Note that the method in Retina's own tutorial is slightly different preferring to use `^0+` presumably for a slight performance improvement.
> 1 votes

# Answer
# 05AB1E, 3 bytes

Since outputting the unary as a single character is required, there are a couple of 3 bytes alternatives:

If a mixture of multiple characters for the unary output would have been allowed, since only the length matters in unary, it could have been 2 bytes with:

```
C∍

```

Outputs a mixture of `1`s and `0`s (depending on the input) for its unary output.

Try it online or verify all test cases.

**Explanation:**

```
C   # Convert the (implicit) input binary-string to a base-10 integer
 ð× # Pop and push a string with that many spaces
    # (after which the result is output implicitly)

$   # Push 1 and the input binary-stringC×
Î   # Or alternatively, push 0 and the input binary-string
 C  # Convert the binary-string to a base-10 integer
  × # Repeat the 1 or 0 that many times as string
    # (after which the result is output implicitly)

C   # Convert the (implicit) input binary-string to a base-10 integer
 Å9 # Pop and push a list with that many 9s (or any other digit)
    # (after which the result is output implicitly)

```

```
C   # Convert the (implicit) input binary-string to a base-10 integer
 ∍  # Extend/shorten the (implicit) input binary-string to that length
    # (after which the result is output implicitly)

```
> 1 votes

# Answer
# MathGolf, 3 bytes

Some different alternatives are available:

* Output as `*`s: `å⌂*`; `åÄ⌂`; `å{⌂`.
* Output as spaces: `å *`; `åÄ`; `å{`.
* All six above should have been also possible with a binary-list instead of binary-string as input, replacing the `å` with `ä`, but unfortunately there seems to be a bug with leading `0`s apparently.. - Try `ä⌂*` online.

**Explanation:**

```
å    # Convert the (implicit) input binary-string to a base-10 integer
 ⌂*  # Repeat that many "*" as string
  *  # Or alternatively, repeat that many spaces as string
     # (after which the entire stack is output implicitly as result)

å    # Convert the (implicit) input binary-string to a base-10 integer
 Ä   # Pop and loop that many times, using the following character as inner code-block:
 {   # Or alternatively, use everything after it as code-block:
  ⌂  #  Push an "*" to the stack every iteration
     #  Or alternatively, push a space character to the stack every iteration
     # (after which the entire stack is joined together and output implicitly as result)

```
> 1 votes

# Answer
# PHP, 32 bytes

```
echo str_repeat('*',bindec($i));

```

Where `$i` is the input string.
> 1 votes

# Answer
# ///, 18 bytes

```
/1/0*//*0/0**//0//

```

Try it online!

I didn't write this, I borrowed it from the esolangs wiki. Here's how it works:

Let's start with the string `10101`, which represents 21.

`/1/0*/` replaces `1`s with `0*`. The string becomes `0*00*00*`. In this, each `*` represents a sort of place value - for example, the first `*` has 4 `0`s after it, so it represents 24 = 16.

`/*0/0**/` replaces each `*` before a zero with two copies of it after the zero, each with half the place value. The first replacement this would do would be replacing `0***0**0*00*` with `0**0****0*00*`, replacing a `*` representing 16 with 2 `*`s each representing 8.

In `///`, replacements are repeated until nothing is left to replace, so this will eventually result in a string with some amount of 0s at the start, followed by 21 `*`s each representing 1.

Finally, `/0//` removes the leading zeros, leaving just 21 `*`s, which is the output in unary.
> 1 votes

# Answer
# sed 4.2.2, 28

```
:
s/1/0u/
s/u0/0uu/
t
s/0//g

```

Implementation algorithm as per the question.

Try it online!
> 1 votes

# Answer
# dc, 17

```
[q]sz2iA?^9/d0=zn

```

Try it online!

### Explanation

```
[ ]                # define a macro to...
 q                 #   quit (i.e. print the empty string)
   sz              # save the macro to register z
     2i            # set input radix to 2 (binary)
       A           # pop 10
        ?          # read input
         ^         # exponentiate 10 to the power of the input
          9/       # divide by 9.  This gives a number consisting of n 1s, or 0
            d      # duplicate top of stack
             0=z   # if equal to 0, call macro stored in z register to print the empty string
                n  # otherwise print the unary number

```
> 1 votes

# Answer
# Julia 1.0, 24 bytes

```
~x="*"^parse(Int,"0b"*x)

```

Try it online!

Generally, any base other than 10 needs to be specified: `parse(Int,x,base=2)`. Two bytes are saved by appending a `0b` integer prefix instead.
> 1 votes

# Answer
# Brain-Flak, 42 bytes

```
([]){{}({}<>({}){})<>([])}<>{({}[(())])}{}

```

Try it online!

The code works by accumulating the values of partial sums on the second stack, then it expands the second stack from the single value n, to n copies of 1.

```
([]) Push the stack height
{ While the stack is not empty
  {} pop the stack height
  (
    {} pop the top of the stack
    <> Jump to the second stack
    ({}){} Add the top element of the second stack twice, popping it
  ) Push the sum
  <>
  ([]) Push new height
}
<> On the second stack:
{ While n>0
  ({} Pop n
    [(()) Push 1
    ] add -1
  ) Push n-1
}{} Pop the zero

```
> 1 votes

# Answer
# Thue, 46 bytes

```
a::=:::
1::=0*
*0::=0**
*>::=!>
!::=~*
::=
a>

```

Try it online!
> 1 votes

# Answer
# Uiua, ~~6~~ 4 bytes

```
⊚°⋯⇌

```

Try it

Convert from binary, use  where to change this to an array of N 0s.

Before I knew about `°⋯`:

## Uiua, 13 bytes

```
×0⇡/+×ⁿ:2⇌⇡⧻.

```

Try it

Multiply by powers of 2, sum, range, multiply each by 0.
> 1 votes

# Answer
# Swift 5.9, 48 bytes

```
let f={{String.init}()("*",Int($0+"",radix:2)!)}

```
> 1 votes

# Answer
# Lua, 33 bytes

```
print(('*'):rep(tonumber(...,2)))

```

Try it online!
> 0 votes

# Answer
# Japt, 2 bytes

Takes input as a binary string, outputs a string of spaces.

```
Íç

```

Try it (Footer replaces spaces with `1`s)
> 0 votes

# Answer
# YASEPL, 65 bytes

```
=d'=m=h$=o=u®"d"=k$u+`1!t$u-m!x¥t,"d"[2!o+h`2!h$2^m!m+}2,k;"1",o<

```

1 is the unary digit, prompts you for input

## explanation

```
=d'=m=h$=o=u®"d"=k$u+`1!t$u-m!x¥t,"d"[2!o+h`2!h$2^m!m+}2,k;"1",o<    packed
=d'                                                                  get user input and set it to variable "d"
   =m   =o                                                           set variable "m" and o to 0
     =h$                                                             set variable "h" to 1
          =u®"d"                                                     set variable "u" to length of user input
                =k$u+                                                set variable "k" to u + 1
                     `1                               }2,k           while m < k...
                       !t$u-m                                        set variable "t" to u - m
                             !x¥t,"d"                                get item from user input index t
                                     [2!o+h`2                        add h to variable "o" if x == 1
                                             !h$2^m                  set variable "h" to the power of m
                                                   !m+               add 1 to m
                                                          ;"1",o<    repeat number 1 o times and print it once finished

```
> 0 votes

# Answer
# Scala 3, 25 bytes

```
"*"*Integer.parseInt(_,2)

```

Attempt This Online!
> 0 votes

---
Tags: code-golf, binary, base-conversion
---


# Question
Title: Convert a string of digits from words to an integer
Convert a string containing digits as words into an integer, ignoring leading zeros.

# Examples

* `"four two"` -\> `42`.
* `"zero zero zero one"` -\> `1`.

# Assumptions

Submissions can assume that:

1. The input string is comprised of space-separated digit words.
2. All words are valid (in the range "zero".."nine") and lowercase. Behaviour for empty input is undefined.
3. The input string always represents an unsigned number within the range of `int` and is never an empty string.

# Scoring

Answers will be scored in bytes with fewer bytes being better.

# Answer
> 24 votes
# PHP, 74 bytes

```
foreach(explode(' ',$argn)as$w)$n.='793251_8640'[crc32($w)%20%11];echo+$n;

```

Try it online!

Tried to get a solution which doesn't copy existing answers. I get cyclic redundancy checksum polynomial of 32-bit lengths (crc32) for each word and then do a mod 20 and mod 11 on it to get mixed up unique values from 0 to 10 (missing 6) for each digit. Then using that unique value I find the actual digit.

```
| Word  | CRC32      | %20 | %11 | Equivalent digit |
|-------|------------|-----|-----|------------------|
| zero  | 2883514770 | 10  | 10  | 0                |
| one   | 2053932785 | 5   | 5   | 1                |
| two   | 298486374  | 14  | 3   | 2                |
| three | 1187371253 | 13  | 2   | 3                |
| four  | 2428593789 | 9   | 9   | 4                |
| five  | 1018350795 | 15  | 4   | 5                |
| six   | 1125590779 | 19  | 8   | 6                |
| seven | 2522131820 | 0   | 0   | 7                |
| eight | 1711947398 | 18  | 7   | 8                |
| nine  | 2065529981 | 1   | 1   | 9                |

```

Another 74 bytes CRC32 alternative using `%493%10`: Try it online!

Another 74 bytes CRC32 alternative using `%2326%11`: Try it online!

---

# PHP, 74 bytes

```
foreach(explode(' ',$argn)as$w)$n.=strpos(d07bfe386c,md5($w)[21]);echo+$n;

```

Try it online!

Another alternative with same length, takes 22nd character in the `md5` of the word (only character which gives a unique value for each word) and then uses that character to map to a digit.

# Answer
> 10 votes
# Python 2,  ~~71~~  70 bytes

-1 thanks to ovs (use `find` in place of `index`)

```
lambda s:int(''.join(`'rothuvsein'.find((w*3)[6])`for w in s.split()))

```

**Try it online!**

# Answer
> 7 votes
# JavaScript (ES6),  ~~70 67 66~~  62 bytes

*Saved 3 bytes thanks to @ovs*

```
s=>+s.replace(/\w+ ?/g,s=>'2839016547'[parseInt(s,36)%204%13])

```

Try it online!

# Answer
> 6 votes
# Python 3, ~~107~~, ~~91~~, ~~77~~, ~~90~~, 73 bytes

-16 bytes by Sriotchilism O'Zaic

+13 bytes to remove leading zeroes

-16 bytes using `find` and a more clever indexing, but now it's basically a rip-off of the Python 2 version...

```
lambda s:int(''.join(str('rothuvsein'.find((w*3)[6]))for w in s.split()))
```

Try it online!

# Answer
> 6 votes
# Jelly,  ~~19~~  17 bytes

```
Ḳµ7ị“*;nÄƲ]³Ṙ»i)Ḍ

```

A monadic Link accepting a list of characters which yields an integer.

**Try it online!**

Pretty much a port of my Python 2 answer.

---

Previous

```
ḲŒ¿€i@€“©¥q£½¤MÆÑ‘Ḍ

```

Try it online!

There is ~~quite possibly~~ a shorter way, but this is a way that first came to mind.

# Answer
> 5 votes
# Perl 6, ~~35~~ 32 bytes

```
{+uniparse 'SP'~S:g/<</,DIGIT /}

```

Try it online!

### Explanation

```
{                              }  # Anonymous block
                S:g/<</,DIGIT /   # Insert ",DIGIT " at
                                  # left word boundaries
           'SP'~  # Prepend 'SP' for space
  uniparse  # Parse list of Unicode names into string
 +  # Convert to integer

```

# Answer
> 5 votes
# 05AB1E, ~~18~~ 16 bytes

```
#ε6è}.•ƒ/ÿßÇf•Åβ

```

Try it online.

**Explanation:**

```
#                 # Split the (implicit) input-string on spaces
 ε  }             # Map each string to:
  6è              #  Get the character at 0-based index 6 (with automatic wraparound)
     .•ƒ/ÿßÇf•    # Push compressed string "rothuvsein"
              Åβ  # Convert the characters from custom base-"rothuvsein" to an integer
                  # (after which the top of the stack is output implicitly as result)

```

See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*) to understand why `.•ƒ/ÿßÇf•` is `"rothuvsein"`.

# Answer
> 5 votes
# C (gcc), 89 bytes

```
i,n;f(char*w){for(i=n=0;n=*w%32?n^*w:(i+=n-2)&&!printf(L"8 0  72 3  59641"+n%17),*w++;);}

```

Try it online!

Thanks to @Ceilingcat smartest tricks :

```
- printf instead of putchar.
- !printf instead of printf()&0.
- And wide char !

```

# Answer
> 4 votes
# 05AB1E, ~~17~~ 16 bytes

```
•D±¾©xWÄ0•I#HèTβ

```

Try it online!

Perfect tie with the other 05AB1E answer, but using a completely different approach.

```
•D±¾©xWÄ0•               # compressed integer 960027003010580400
          I#             # split the input on spaces
            H            # convert each word from hex (eg "one" => 6526)
             è           # index (with wrap-around) into the digits of the large integer
              Tβ         # convert from base 10 to integer

```

# Answer
> 3 votes
# Retina 0.8.2, ~~46~~ 45 bytes

```
\w+
¶$&$&$&
%7=T`r\ot\huvs\ein`d`.
\D

^0+\B

```

Try it online! Link includes test cases. Explanation:

```
\w+
¶$&$&$&

```

Put each word on its own line and triplicate it.

```
%7=T`r\ot\huvs\ein`d`.

```

Transliterate the 7th character of each line using @UnrelatedString's string.

```
\D

```

Delete all remaining non-digit characters.

```
^0+\B

```

Delete leading zeros (but leave at least one digit).

Previous 46-byte more traditional solution:

```
T`z\wuxg`E
on
1
th
3
fi
5
se
7
ni
9
\D

^0+\B

```

Try it online! Link includes test cases. Explanation:

```
T`z\wuxg`E

```

The words `zero`, `two`, `four`, `six` and `eight` uniquely contain the letters `zwuxg`. Transliterate those to the even digits.

```
on
1
th
3
fi
5
se
7
ni
9

```

For the odd digits, just match the first two letters of each word individually.

```
\D

```

Delete all remaining non-digit characters.

```
^0+\B

```

Delete leading zeros (but leave at least one digit).

# Answer
> 3 votes
# Ruby, ~~63 bytes~~, ~~52 bytes~~, 50 bytes

```
p $*.map{|d|'rothuvsein'.index (d*3)[6]}.join.to_i

```

-2 thanks to value ink's tip

# Answer
> 3 votes
# x86 machine code, 46 bytes

Hexdump:

```
57 53 33 c0 33 ff f6 01 0f 75 15 6a 0a 5b 99 f7
f3 6b ff 0a 03 fa 33 c0 38 01 75 0f 97 5b 5f c3
69 c0 26 2b aa 6e 32 01 c1 e8 02 41 eb d8

```

It's a `fastcall` function - receives a pointer to the string in `ecx`, and returns the result in `eax`.

The hashing function multiplies by a magic number `1856645926`, does a `XOR` with input byte, and shifts right by 2 bits.

Saving and restoring noclobber registers (`edi` and `ebx`) took 4 bytes, but I didn't find a more efficient way to implement this. Storing the constant 10 in `ebx` was particularly annoying!

Disassembly with corresponding code bytes:

```
57                   push        edi  ; edi = result
53                   push        ebx  ; we use ebx to store the constant 10
33 C0                xor         eax,eax
33 FF                xor         edi,edi
    myloop:
F6 01 0F             test        byte ptr [ecx],0Fh  ; check for end of word
75 15                jne         myhash
6A 0A                push        0Ah
5B                   pop         ebx
99                   cdq              ; prepare 64-bit dividend in edx:eax
F7 F3                div         eax,ebx  ; find the remainder of division by 10
6B FF 0A             imul        edi,edi,0Ah
03 FA                add         edi,edx  ; update the result
33 C0                xor         eax,eax  ; reset the hash temporary variable
38 01                cmp         byte ptr [ecx],al  ; check for end of input (here al=0)
75 0F                jne         mycontinue
97                   xchg        eax,edi  ; set the return register
5B                   pop         ebx  ; restore registers
5F                   pop         edi  ; restore registers
C3                   ret
    myhash:
69 C0 26 2B AA 6E    imul        eax,eax,6EAA2B26h  ; hashing...
32 01                xor         al,byte ptr [ecx]  ; hashing...
C1 E8 02             shr         eax,2  ; hashing...
    mycontinue:
41                   inc         ecx  ; next input byte
EB D8                jmp         myloop

```

Equivalent C code:

```
int doit(const char* s)
{
    int result = 0;
    unsigned temp = 0;
    while (true)
    {
        int c = *s++;
        if ((c & 15) == 0)
        {
            temp %= 10;
            result = result * 10 + temp;
            temp = 0;
            if (c == 0)
                break;
            else
                continue;
        }
        temp *= 1856645926;
        temp ^= c;
        temp >>= 2;
    }
    return result;
}

```

# Answer
> 3 votes
# ARM Thumb-2 (manual `rothuvsein`, no div, no libc) 70 bytes

Machine code:

```
b5f0 2100 2420 f000 f816 0032 18c5 3b03
bf18 f1c3 0303 5cc4 a004 f000 f80c 240a
fb01 3104 1c68 2a00 d1ec bdf0 6f72 6874
7675 6573 6e69 f07f 0300 1c5b 5cc6 b10e
42a6 d1fa 4770

```

Assembly:

```
        .syntax unified
        .arch armv6t2
        .thumb
        .globl _strtoint
        .thumb_func
_strtoint:
        push    {r4-r7, lr}
        movs    r1, #0
.Lstrtoint_loop:
        movs    r4, #' '
        bl      _strfind
        movs    r2, r6
        adds    r5, r0, r3
        subs    r3, #3
        it      ne
        rsbne   r3, #3
        ldrb    r4, [r0, r3]
        adr     r0, .Lrothuvsein
        bl      _strfind
        movs    r4, #10
        mla     r1, r1, r4, r3
        adds    r0, r5, #1
        cmp     r2, #0
        bne     .Lstrtoint_loop
.Lstrtoint_loop_end:
        pop     {r4-r7, pc}

        @ naturally 4-byte aligned
        @ note: this is not null terminated - we blindly assume a match
.Lrothuvsein:
        .ascii "rothuvsein"
        @ naturally 2-byte aligned
        .thumb_func
_strfind:
        movs    r3, #-1
.Lstrfind_loop:
        adds    r3, r3, #1
        ldrb    r6, [r0, r3]
        cbz     r6, .Lstrfind_loop_end
        cmp     r6, r4
        bne     .Lstrfind_loop
.Lstrfind_loop_end:
        bx      lr

```

### Explanation

Yet another port of the `rothuvsein` method, but this seems to be the first one in assembly. It is also done manually without the support of libc or fancy useless CISC instructions like `repne scasb`. Just plain, barebones RISC. That means that it is longer than other assembly languages.

Unlike my previous entries, I am a little more flexible with the calling convention.

While the input string (null terminated) is in `r0` just like it would be in C, the output is a 32-bit integer in `r1` instead of the traditional `r0`.

It can still be wrapped in C like so, since `r1` is still used for 64-bit integers:

```
extern uint64_t _strtoint(const char *str);
uint32_t strtoint(const char *str)
{
    return (uint32_t)(_strtoint(str) >> 32);
}

```

Regardless of whether I care about the calling convention, I am going to have to do something with the link register so I can call my subroutine, so might as well `push` the callee-saved registers and remain mostly in line with the calling convention.

```
        .globl _strtoint
        .thumb_func
_strtoint:
        push    {r4-r7, lr}

```

Initialize our accumulator/output variable to 0.

```
        movs    r1, #0

```

Call our internal subroutine to find the end of the word.

`r3` will have the length of the word, and `r6` will have the last byte read. I will explain `_strfind` later.

```
.Lstrtoint_loop:
        movs    r4, #' '
        bl      _strfind

```

We save a copy of the last byte read for later to tell if we reached the null terminator.

```
        movs    r2, r6

```

Put the pointer to the string (advanced to the space) in `r5`.

```
        adds    r5, r0, r3

```

Here is the trickiest part: **One does not simply `str+str+str` in assembly.** We need to find the index.

Specifically, if we plot it out:

```
oneoneone
      ^
fourfourfour
      ^
sevensevenseven
      ^

```

We can turn it into this:

```
switch (strlen(str)) {
case 3: return str[0];
case 4: return str[2];
case 5: return str[1];
}

```

It can be done as `6 % strlen(str)`, but that is division. I can do better.

I could do a lookup table, but there is a better solution than that:

Remember that `r3` is essentially `strlen(str)`.

We can do this:

```
        subs    r3, #3
        it      ne
        rsbne   r3, #3 @ note: rsb = Reverse SuBtract

```

The equivalent C:

```
if ((len -= 3) != 0)
{
    len = 3 - len;
}

```

This works perfectly:

```
3 - 3       = 0
3 - (4 - 3) = 2
3 - (5 - 3) = 1

```

Now, we load the byte from the string at our offset...

```
        ldrb    r4, [r0, r3]

```

...then call `_strfind` with the `rothuvsein` lookup table to find it.

```
        adr     r0, .Lrothuvsein
        bl      _strfind

```

Now, we add the length to our accumulator times 10;

```
        movs    r4, #10
        mla     r1, r1, r4, r3 @ r1 = r1 * 10 + len

```

Take the copy of the string we made in `r5`, advance it past the space, and put it in `r0` for the next iteration.

```
        adds    r0, r5, #1

```

Then, loop if we are not at a null terminator:

```
        cmp     r2, #0
        bne     .Lstrtoint_loop

```

Finally, return in `r1` by popping the link register holding the return address into the program counter (along with restoring the other registers I saved).

```
.Lstrtoint_loop_end:
        pop     {r4-r7, pc}

```
\_strfind subroutine

`_strfind` is the real workhorse here.

C users will find it similar to `strcspn` or `strchr`.

It is called with the null terminated string to search in `r0` and the byte to find in `r4`.

It will return the index of the match (or null terminator) in `r3` and the last byte read in `r6`.

First, initialize our counter at -1.

```
_strfind:
        movs    r3, #-1

```

On each iteration, increment the counter..

```
.Lstrfind_loop:
        adds    r3, r3, #1

```

Then, load `str[counter]` into `r6`

```
        ldrb    r6, [r0, r3]

```

Then loop unless `r6` is `\0` or if it matches `r4`.

```
        cbz     r6, .Lstrfind_loop_end
        cmp     r6, r4
        bne     .Lstrfind_loop

```

When we find it, return back to `_strtoint`.

```
.Lstrfind_loop_end:
        bx      lr

```

# Answer
> 2 votes
# C++ (gcc), ~~478~~ ~~218~~ 142 bytes

-(a lot) thanks to Jo King

```
int f(string s){char c[]="N02K8>IE;6";int i=0,n=0;while(s[i]){n=n*10-1;while((s[i]^s[i+1])+47!=c[++n%10]);while(s[i++]!=' '&&s[i]);}return n;}

```

Try it online!

# Answer
> 2 votes
# Jelly, ~~20~~ ~~18~~ ~~17~~ 16 bytes

```
Ḳ7ị“"c tẠ;Ḅ»iƲ€Ḍ

```

Try it online!

-2 bytes from running "rothuvsein" through user202729's string compressor.

-1 byte from stealing Jonathan Allan's zero-free enklact string, and putting it in a marginally differently structured program.

-1 byte because I actually kind of understand Jelly's dictionary-based string compression now

```
Ḳ                   Split the input on spaces,
             Ʋ€     for each word
            i       find the first 1-based index (defaulting to 0)
   “"c tẠ;Ḅ»        in "othuvseine"
 7ị                 of the element at modular index 7,
               Ḍ    and convert from decimal digits to integer.

```

I must admit, I'm disappointed I couldn't get a length reduction from `othuvseinfeld`.

# Answer
> 2 votes
# Japt, 13 bytes

```
¸mg6 ì`Î¨uv

```

Try it

Looks like everyone else beat me to the same idea - could've saved myself the hassle of writing a script to brute force the optimal string for compression, only to find that, up to index `1,000,000` (it was early, I hadn't had my caffeine yet!), "rothuvsein" is the *only* possible string!

```
¸mg6 ì`...     :Implicit input of string
¸              :Split on spaces
 m             :Map
  g6           :  Character at index 6 (0-based, with wrapping)
     ì         :Convert from digit array in base
      `...     :  Compressed string "rothuvsein"

```

The compressed string contains the characters at codepoints `206`, `168`, `117`, `118`, `160` & `136`.

# Answer
> 2 votes
# sed -re, 78 bytes

```
s/three/3/g;s/five/5/g;s/\w\w(\w)\w*/\1/g;s/ //g;y/eouxvgnr/12467890/;s/^0*//

```

# Answer
> 2 votes
# T-SQL, 110 bytes

```
SELECT 0+STRING_AGG(CHARINDEX(LEFT(value,2),'_ontwthfofisiseeini')/2,'')
FROM STRING_SPLIT((SELECT*FROM i),' ')

```

Line break is for readability only.

Input is taken via table \\$i\\$, per our IO rules. I could have saved 14 bytes by pre-populating a string variable, but that's only allowed if the language has no other input methods.

Explanation:

1. `STRING_SPLIT` takes the input string and separates it at the spaces
2. `CHARINDEX` takes the first 2 characters and returns the (1-based) position in the string `'_ontwthfofisiseeini'`. `'ze'` for zero is not in the string and returns 0 for "not found". The underscore ensures we only get multiples of two.
3. Divide by 2 to get the final numeral
4. `STRING_AGG` smashes the digits back together with no separator
5. `0+` forces an implicit conversion to INT and drops any leading zeros. `1*` would also work.

# Answer
> 2 votes
# Kotlin, 83 bytes

```
fun String.d()=split(' ').fold(""){a,b->a+"rothuvsein".indexOf((b+b+b)[6])}.toInt()

```

+1 byte if you wanna support longs with `toLong()`

Same rothuvsein trick as the others, saving some precious bytes thanks to kotlin's nice `toInt()` and `fold()`. I just can't shake the feeling that some more bytes can be shaved off though...

# Answer
> 2 votes
# Scala, ~~66~~ ~~64~~ 62 bytes

```
_.split(" ").map("rothuvsein"indexOf _.*(3)(6)).mkString.toInt

```

Try it online! This is the "rothuvsein" approach in Scala. The 7th character of each (repeated) number string is extracted via `(numberString*3)(6)`. The position of this character in "rothuvsein" is then used as the correct numerical digit. The `toInt` conversion does the rest (e.g., dealing with leading zeros).

2 times 2 bytes saved thanks to @user by

1. an even more abused use of syntactic sugar :)
2. simply using `toInt` conversion rather than `BigInt` constructor

# Answer
> 1 votes
# Perl 6, 45 bytes

```
+*.words>>.&{+(1...*.uniname.comb(.uc))}.chrs

```

Try it online!

# Answer
> 1 votes
# Clean, 88 bytes

```
import StdEnv,Text
$s=toInt{#i\\n<-split" "s,c<-:"rothuvsein"&i<-['0'..]|c==(n+n+n).[6]}

```

Try it online!

Heavily based on Jonathan Allan's answer.
Uses a comprehension for indexing instead of `indexOf` / `elemIndex`.

# Answer
> 1 votes
# , 38 bytes

```
('b\e~mjPxw['i.[:u:70+1#.15|3&u:)&>@;:

```

Try it online!

# Answer
> 1 votes
# VBA, 160 bytes

```
Function e(s)
s = Split(s, " ")
For i = LBound(s) To UBound(s)
s(i) = Int((InStr("ontwthfofisiseeini", Left(s(i), 2)) + 1) / 2)
Next
e = Val(Join(s, ""))
End Function

```

Matches the first two characters in a string, zero excluded.

# Answer
> 1 votes
# Charcoal, 19 bytes

```
Ｉ⍘⭆⪪Ｓ §ι⁶rothuvsein

```

Try it online! Link is to verbose version of code. Port of @KevinCruijssen's 05AB1E answer. Explanation:

```
    Ｓ               Input string
   ⪪                Split on spaces
  ⭆                 Map over words and join
       ι            Current word
      §             Cyclically indexed
        ⁶           Literal `6`
 ⍘       rothuvsein Custom base conversion
Ｉ                   Cast to string for implicit print

```

# Answer
> 1 votes
# PowerShell, 48 bytes

```
+-join($args|%{'rothuvsein'.indexof(($_*3)[6])})

```

Try it online!

Uses the same `rothuvsein` trick as others, thanks to Jonathan Allan. Expects input arguments via splatting, which on TIO manifests as separate command-line arguments.

# Answer
> 1 votes
## Windows Batch, 169 bytes

```
@setlocal enabledelayedexpansion
@set z=zeontwthfofisiseeini
:a
@set b=%1
@for /l %%c in (0,2,18)do @if "!b:~0,2!"=="!z:~%%c,2!" set/aa=a*10+%%c/2&shift&goto a
@echo %a%
```

# Answer
> 1 votes
# APL (Dyalog Extended), 26 bytes

```
10⊥'rothuvsein'⍳7⊢/⍤⍴¨≠⍛⊆⍨

```

Try it online!

A simple function which checks the first two letters of each word.

-30 bytes from Adám using Kevin Cruijssen's idea.

## Explanation(old)

```
     {⍕2÷⍨1-⍨(2↑⍵)(⍸⍷)'zeontwthfofisiseeinite'} inner fn:
             (2↑⍵)                              take first two letters
                  (⍸⍷)'zeontwthfofisiseeinite'} find index of the letters in hardcoded string
       2÷⍨1-⍨                                   subtract 1, divide by 2
      ⍕                                         stringify
{⍎⊃,/{⍕2÷⍨1-⍨(2↑⍵)(⍸⍷)'zeontwthfofisiseeinite'}¨' '(≠⊆⊢)⍵} ⍵ → input
                                                ' '(≠⊆⊢)⍵  split input on spaces
   ,/                                                      join output of inner fn
 ⍎⊃                                                        execute it

```

# Answer
> 1 votes
# K (ngn/k), 27 bytes

```
10/"rothuvsein"?(*|7#)'" "\

```

Try it online!

Another port of Kevin Cruijssen's 05AB1E answer.

* `" "\` split input on spaces
* `(*|7#)'` take the last character of each word (repeated to be of length seven)
* `"rothuvsein"?` find index of character in "rothuvsein" (i.e. the seventh character of "zero" repeated is "r", which is at index 0)
* `10/` convert from a list of digits to a decimal number

# Answer
> 1 votes
# Python 3, 85 bytes

I put two versions of my explanation just for fun :)

Split the input **`i`** into words and loop over it using list comprehension. For all the words find the location of the first 2 letters in a lookup table (*"zeontwthfofisiseeini"*), making sure to divide by two - with **`//`** for floor division, finally use **`"".join(`** to combine into a string and **`int(`** to convert to integer and remove leading zero(s).

```
lambda i:int("".join([str("zeontwthfofisiseeini".find(x[:2])//2)for x in i.split()]))

```

Try it online!

* `lambda i:` lambda function instead of using a `def` function
* `[for x in]` use list comprehension to check through the input
* `i.split` split the input at spaces (default delimiter)
* `"zeontwthfofisiseeini".find(x[:2])` find the location of the first two characters of **x** in a lookup list
* `//2` floor divide output of `.find` because it's checking the first 2 chars
* `str()` convert position to string
* `"".join()` combine output of list comprehension to a string
* `int()` convert string to int and remove leading zero(s)

Also, this is accidentally similar to this answer but I made mine before looking at the other answers.

# Answer
> 1 votes
# Vyxal, 63 bits<sup>v2</sup>, 7.875 bytes

```
⌈ƛ₀ʁ∆ċḟ;ṅ⌊

```

Try it Online!

Bitstring:

```
110010010001010010110111001001001001010010011010110111110111010

```

```
⌈ƛ₀ʁ∆ċḟ;ṅ⌊
⌈           # split on spaces
 ƛ     ;    # map over each
      ḟ     # their index in the list
  ₀ʁ∆ċ      # 0-9 as words
        ṅ⌊  # convert back to number

```

Created with the help of Luminespire.

# Answer
> 0 votes
# **BaCon, ~~83~~ 72 bytes**

Assuming the string is provided in w$, this code looks up the index in "zeontwthfofisiseeini" using a regular expression based on the unique first 2 characters of each word. The index is then divided by 2 providing the correct result.

```
FOR x$ IN w$:r=r*10+REGEX("zeontwthfofisiseeini",LEFT$(x$,2))/2:NEXT:?r

```

# Answer
> 0 votes
# AWK, ~~76~~ 64 bytes

More of the same, but with a pinch of AWK sparkling magic.

Edit: at first, I didn't looked for the answers, and my result was actually similar to some of them. I'm mesmerized by all these ingenious solutions.

```
{i=OFS=e;for(;NF>i++;)$i=index("othuvsein",substr($i$i$i,7,1))}1

```

Try it online!

<pre><code>{
i=OFS=e;     # We start setting the _i_ variable and the
             # Output Field Separator as the _e_ variable, which is
             # just empty, for never being assigned anything,
             # so _e_ is both evaluated as zero for _i_ and null for _OFS_
             # (thanks Brian Kernighan for that!)
for(;
    NF>i++;  # the looping goes on until _i_ reaches the Number of Fields (NF).
   )         # also, _i_ is incremented by 1 each turn.

     $i=                          # $i is each field text
        index("othuvsein",        # we get this magic Klingon and locate the
              substr($i$i$i,7,1)  # 7th letter of the input concatenated 3 times
             )                    # this has the same effect as looking
                                  # for the second to last letter on the word.

}
1            # finally, we print all the $i together
```
</code></pre>

# Answer
> 0 votes
# Perl 5 `-p`, 55 bytes

```
for$b(z,on,w,th,u,iv,x,v,g,ni){s/$b/@a/eg;$#a++}s/\D//g

```

Try it online!

# Answer
> 0 votes
# Bash (pure), ~~85~~ 83 bytes

```
r=rothuvsein
for j in $@
do
s=$j$j$j
t=${r%${s:6:1}*}
((i=i*10+${#t}))
done
echo $i

```

Try it online!

Literally just the same as every other `rothuvsein` entry. Concatenates three times and gets it at index 6.

First version which uses no string concatenation: (85 bytes)

```
r=rothuvsein
for j in $@
do
t=${r%${j:$((6%${#j})):1}*}
((i=i*10+${#t}))
done
echo $i

```

Try it online!

Pass the string as command line arguments. Expects `$i` to be unset.

Ungolfed version:

```
# Default value is zero
val=0
# declare our lookup table
lut=rothuvsein
# loop through command line arguments
for word in $@
do
    # The index is at 6 % len(word) (see my Thumb submission)
    idx=$(( 6 % ${#word} ))
    # chr = word[6 % len(word)]
    chr=${word:$idx:1}
    # Find a substring using a modified technique from the linked SO post
    substr=${lut%$chr*}
    # Add the length to val * 10
    (( val = val * 10 + ${#substr} ))
done
# Echo the result
echo $val

```

How to check if a string contains a substring in Bash - Stack Overflow

# Answer
> 0 votes
# Pyth, ~~21~~ 20 bytes

```
ssm`x."evt8†À‘"@d6c
```

Try it online!

Translates literally to `print(int("".join(map(lambda d: str("rothuvsein".index(d[6%len(d)])), eval(input()).split()))))` in Python 3.

# Answer
> 0 votes
## Lua (110 bytes)

---

A translation to Lua of the `rothuvsein` trick, sorry. Note that we use 7 instead of 6 because Lua counts from 1, as sane humans do.

```
function x(s)z=""for w in s:gmatch("%a+")do z=z..(("rothuvsein"):find(w:rep(3):sub(7,7))-1) end return z+0 end

```

# Answer
> 0 votes
# Swift, ~~135~~ ~~128~~ 91 bytes

```
let f={Int(.init(($0+"").split{$0<"0"}.map{[_]("2839016547")[Int($0,radix:36)!%204%13]}))!}

```

This is pretty much a port of @Arnauld's JavaScript answer.

# Answer
> 0 votes
# Kotlin, 64 bytes

```
{split(" ").fold(0){a,b->10*a+"rothuvsein".indexOf((b+b+b)[6])}}

```

Improving upon this answer.

Try it online!

---
Tags: code-golf, string, number, conversion
---


title: Find the angle between two points

text:
# Question
Title: Find the angle between two points
Given two points `A` and `B`, find the angle from line `AO` to line `BO` about point `O` where `O` is the origin (`(0,0)`). Additionally, the angle may be positive or negative depending on the positions of the points (see examples). Input will be points `A` and `B`, and may be given in any convenient form. Output will be the angle in degrees (but it is positive if `AO` is rotated counter-clockwise about the origin to get `BO` and negative if it is rotated clockwise). If the angle is 180 degrees you may return a negative or positive output. Similarly, the angle can be the positive or negative version of the same angle (`90 deg` is equal to `-270 deg`). Examples:

* Input: `A(5,5) B(5,-5)` Output: `-90` (`AO` is rotated `-90` degrees to get `BO`).
* Input: `A(5,-5) B(5,5)` Output: `90` (`AO` is rotated `90` degrees to get `BO`).

This is , so shortest code in bytes wins!

# Answer
> 12 votes
# Pyth, 11 bytes

```
.t-FPM.jMQ6

```

Demonstration

Input is given in the format:

```
[[Bx, By], [Ax, Ay]]

```

If it is desired that A comes first, this can be changed for 1 byte.

Explanation:

```
.t-FPM.jMQ6
               Implicit: Q = eval(input())
      .jMQ     Convert input pairs to complex numbers.
    PM         Take their phases (angles in the complex plane).
  -F           Take the difference.
.t        6    Convert to degrees

```

# Answer
> 21 votes
# TI-BASIC, 13 bytes

For TI-83+/84+ series calculators.

```
Degree
Input Y
min(ΔList(R►Pθ(Ans,∟Y

```

To use this program, enter the list `{x1,x2}` through the Ans variable, and `{y1,y2}` at the prompt.

# Answer
> 10 votes
# CJam, 14 bytes

```
q~::ma:-P/180*

```

This is a full program that reads the input as `[[Ax Ay] [Bx By]]` from STDIN.

Try it online in the CJam interpreter.

### How it works

```
q~             e# Read and evaluate all input.
  ::ma         e# Replace each point (x, y) with atan2(x, y).
               e# This returns its angle with the positive y axis, measured clockwise.
      :-       e# Compute the difference of the two resulting angles.
               e# This returns the angle between the points, measured counter-clockwise.
        P/180* e# Divide by Pi and multiply by 180 to convert to degrees.

```

# Answer
> 4 votes
## Minkolang 0.9, 112 bytes

I *really* want to implement trig functions as built-ins now...but this was fun! (Caveat: this outputs the positive angle difference, not the signed angle difference. Given my limitations, I think that's justified.)

```
4[n]0c2c*1c3c*+r4[2;1R]r+1R+0g*12$:;$:8[0ci2*3+d1R;0g$:1i1+[i2*1+d1+$:*]*]$+'3.141592654'25*9;$:$:12$:r-66*5**N.

```

Try it here.

### Explanation

I'll post a fuller explanation if anyone wants it, but the gist of it is:

```
4[n]                                    Take in 4 integers from input
0c2c*1c3c*+                             dot product
r4[2;1R]r+1R+0g*12$:;                   magnitudes of vectors
$:                                      dot product divided by magnitudes (z)
8[0ci2*3+d1R;0g$:1i1+             *]    Taylor series for arccos
                     [i2*1+d1+$:*]      In particular, the coefficient (1/2 * 3/4 * ...)
$+                                      Add them all up!
'3.141592654'25*9;$:$:                  Divide by pi for converting to degrees
12$:r-                                  Subtract from 1/2 - I now have arccos(z)
66*5**                                  Convert to degrees
N.                                      Output as number and stop.

```

# Answer
> 4 votes
# Mathematica, 22 bytes

```
{-1,1.}.ArcTan@@@#/°&

```

**Example:**

```
In[1]:= {-1,1.}.ArcTan@@@#/°&[{{5,5},{5,-5}}]

Out[1]= -90.

In[2]:= {-1,1.}.ArcTan@@@#/°&[{{5,-5},{5,5}}]

Out[2]= 90.

```

# Answer
> 3 votes
# Julia, ~~18~~ 25 bytes

```
f(A,B)=angle(B/A)/pi*180

```

This assumes that "any convenient form" already allows for `A` and `B` to be given as complex numbers. Then, the complex number arithmetic does all the heavy lifting.

*Edit: converted snippet to function. 18 byte version only works in the Julia REPL.*

# Answer
> 3 votes
# Python 2.7, 73 Bytes

```
from math import*
f=lambda A,B:degrees(atan2(B[1],B[0])-atan2(A[1],A[0]))

```

**Test:**

```
f((5,5),(5,-5)) #-90.0
f((5,-5),(5,5)) #90.0

```

# Answer
> 3 votes
# Octave, 43 bytes

```
f=@(a,b)(cart2pol(b)-cart2pol(a))(1)*180/pi

```

Input/Output:

```
octave:40> f([5,5],[5,-5])
ans = -90

octave:41> f([1,0],[0,1])
ans = 90

```

# Answer
> 3 votes
# Javascript, 66 bytes

```
let f=(a,b)=>(Math.atan2(b.y,b.x)-Math.atan2(a.y,a.x))*180/Math.PI;

```

demo

# Answer
> 2 votes
# CJam, 15 bytes

```
l~ma@@ma-P/180*

```

Thought I'll get in the CJam game as well. Try it online. Input is in form of `bx by ax ay`. Unfortunately, this is the shortest method of doing this challenge without copying Dennis' answer.

# Answer
> 2 votes
# TeaScript, 28 bytes

I really should of implemented trig functions...

```
$.atan2(_[3]-y,z-x)*180/$.PI

```

Try it online input is `a.x a.y b.x b.y`

### Explanation

```
$.atan2(       // Arc Tangent of...
    _[3] - y,  // 4th input - 2nd input
       z - x,  // 3rd input - 1st input
) * 180 / $.PI // Converts rad -> deg

```

# Answer
> 2 votes
# Ruby, 64, 58 bytes

```
a=->(b){b.map{|c|Math.atan2(*c)}.reduce(:-)*180/Math::PI}

```

Usage

```
a.call [[5, 5], [5, -5]] # => -90.0
a.call [[5, -5], [5, 5]] # => 90.0

```

# Answer
> 2 votes
# JavaScript, 49 bytes

```
(a,b)=>((c=Math.atan2)(...b)-c(...a))/Math.PI*180

```

Input is taken in form: `[aY, aX], [bY, bX]` (notice the reversed x/y)

# Answer
> 1 votes
# Simplex v.0.7, 13 bytes

I'm glad I added `mathrelations` :D Unfortunately, I cannot take pointwise input. So, I input each point as a separate number (Ax, Ay, Bx, By). (I used this as a resource.)

```
(iRi~^fR)2LSo
(       )2    ~~ repeat inner twice
 iRi          ~~ take two chars of input (x,y)
    ~         ~~ switch top 2 on stack
     ^f       ~~ apply atan2 on (y,x)
       R      ~~ go right
          L   ~~ go left
           S  ~~ subtract result
            o ~~ output as number

```

I can save a char if I can take input as (Ay, Ax, By, Bx):

```
(iRi^fR)2LSo

```

# Answer
> 1 votes
# C, 88 bytes

```
#include<math.h>
typedef double d;d g(d x,d y,d a,d b){return atan2(b-y,a-x)*180/M_PI;}

```

Requires compiling with GCC to take advantage of `M_PI` being defined in `math.h` as a part of GCC's built-in math constants. Try it online \- since ideone doesn't use GCC (apparently), an additional few bytes are needed for enough digits of π to be accurate.

# Answer
> 1 votes
# , 33 bytes

```
f=\(a,b,c,d)atan2(d-b,c-a)/pi*180

```

result:

```
> f(5,5,5,-5)
[1] -90
> f(5,-5,5,5)
[1] 90

```

# Answer
> 1 votes
## Pascal, 68 Bytes

Pascal according to ISO standard 10206 “Extended Pascal” includes complex numbers as a built‑in data type.

```
function f(A,B:complex):real;begin f:=arg(B/A)*90/arg(cmplx(0,1))end

```

## FreePascal, 71 Bytes

As of version 3.2.0 the FreePascal Compiler (FPC) does not (yet) support (all) Extended Pascal features, but the standard RTL (run‑time library) includes a custom `ucomplex` UCSD Pascal `unit` providing a `record`‑based complex number implementation.

```
uses uComplex;function f(A,B:complex):real;begin f:=180/pi*carg(B/A)end

```

# Answer
> 0 votes
# Swift, 62 bytes

```
import Foundation
let f={(atan2($3,$2)-atan2($1,$0))*180/M_PI}

```

If you're on a Mac, you should be able to replace `import Foundation` with `import Darwin` to save 4 bytes.

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


title: Sleep for 1000 years

text:
# Question
Title: Sleep for 1000 years
Some `sleep` commands implement a delay of an integer number of seconds. However, 2³² seconds is only about 100 years. Bug! What if you need a larger delay?

Make a program or a function which waits for 1000 years, with an error of less than ±10%. Because it's too time-consuming to test, please explain how/why your solution works! (unless it's somehow obvious)

You don't need to worry about wasting CPU power - it can be a busy-loop. Assume that nothing special happens while your program waits - no hardware errors or power failures, and the computer's clock magically continues running (even when it's on battery power).

What the solution should do after the sleep is finished:

* If it's a function: return to caller
* If it's a program: terminate (with or without error) or do something observable by user (e.g. display a message or play a sound)

# Answer
> 26 votes
# MATL, ~~6~~ 5 bytes

```
35WY.

```

This waits for 34359738368 seconds, which is a little more than 1089 years and a half.

Don't try it online!

### Explanation

```
35     % Push 35
W      % 2 raised to that. Gives 34359738368
Y.     % Pause for that many seconds

```

# Answer
> 83 votes
# C (gcc), ~~40 36 32 29 26~~ 24 bytes

```
i;f(){--i&&f(sleep(7));}

```

Try it online!

-3 thanks to @gastropner.

-1 recursive approach thanks to @AZTECCO.

4294967295\*7/86400/365.25 ~ 952.69

# Answer
> 41 votes
# Python 3 (Excluding CPython on Windows), 28 bytes

```
import time
time.sleep(3e10)

```

Try it online! (Remember to put something in your will so future generations can check that it ended on time.)

`time.sleep(seconds)` takes either an int or a float.

`1000*365.2422*24*60*60/3e10 == 1.051897536` which is an error of less than 10%.

# Answer
> 30 votes
# bash, 26 24 bytes

I think part of the challenge here is to not have a signed 32 bit overflow, so:

```
ping -i86400 -c365243 t.co

```

The idea here is to make 1000 years of pings (365243), once per day (86400).

"t.co" is simply a four character internet hostname (in this case, a link shortener). If your local host table has a one character hostname, you can subtract 3 bytes.

Edit: corvus-192 points out that country code ai resolves as a host, so you can write:

```
ping -i86400 -c365243 ai

```

As this will should work for anyone, I will accept this. Saved 2 bytes.

# Answer
> 23 votes
# Ruby, 10 bytes

```
sleep 3e10

```

Try it online!

There are approximately \\$3\*10^{10}\\$ seconds in a thousand years.

# Answer
> 21 votes
## 6502 Machine Code on an Apple II, 10 9 bytes

Code is actually platform-independent, other than it relies on the Apple's clock speed of 1.023 MHz for timing.

Code starts at address 0x0000:

`0000: A2 CA F6 44 F0 FB D0 F8 F7`

Saved an additional byte. Details are below original answer.

### Original answer:

Code starts at address 0x0059:

`0059: A2 08 F6 60 D0 FA CA D0 F9 F5`

Disassembly:

```
loop1: 0059- A2 nn     LDX #$nn   ; 2 cyc
loop2: 005B- F6 60     INC $60,X  ; 6 cyc
       005D- D0 FA     BNE loop1  ; 2-3 cyc
       005F- CA        DEX        ; 2 cyc
       0060- D0 F9     BNE loop2  ; 2-3 cyc
       0062- pp        DB  $pp    ; data byte

```

This is a fairly simple routine that increments a multi-byte counter. When the counter rolls over, the last branch instruction gets modified so that it points to an RTS instruction, which provides the exit for the routine.

loop1 is taken for each increment of the counter and takes 11 cycles per iteration. loop2 is taken for each byte carried over and takes 13 cycles per iteration. So if we increment the counter N times, we spend approximately:

11\*N + 13\*(1/256 + 1/(256^2) + 1/(256^3) + ...)\*N = 11.05\*N cycles

1000 years is 365242\*86400\*1023000 = 32282717702400000 cycles

So we need N = 2921512914244345 +/- 10%

Or a range of 2629361622819911 - 3213664205668779
= 0x095763F583A447 - 0x0B6ACF816801AB

In the code above, set pp = 0xF5 and nn = 0x08.

This gives us a 7-byte counter in memory locations 0x62-0x68 (with MSB at lowest address, i.e. big endian). Only location 0x62 is initialized, so our starting counter value could be anywhere from 0xF5000000000000 to 0xF5FFFFFFFFFFFF.

We'll increment the counter until it rolls over to 0, which will cause the byte at 0x61 to increment by 1, which happens to be the branch target for loop2. On the first byte carry after rollover-- when the counter hits 0x100-- we'll hit the modified branch instruction for the first time. This will take us to address 0x5C (loop2+1). The 0x60 byte there is the opcode for "Return from Subroutine" (RTS) which provides our exit.

So our total loop count is between, 0x0A000000000101 and 0x0B000000000100, which is a subset of the range we calculated which gives us the necessary number of cycles +/- 10%.

Now that we have the exact starting and ending counter values, we could go back and calculate the exact cycle counts, but given how much margin there is, I'm willing to hand-wave that part.

You can actually test it out with smaller values of nn. For example nn of 4 will pause for several seconds.

### 9-byte answer:

```
0000- A2 CA     LDX #$CA   ; 2 cyc
0002- F6 44     INC $44,X  ; 6 cyc
0004- F0 FB     BEQ $0001  ; 2-3 cyc (rollover)
0006- D0 F8     BNE $0000  ; 2-3 cyc (non-rollover)
0008- F7        DB  $F7    ; data byte

```

Saved one byte by folding the DEX opcode into the argument for LDX.

Instead of 11.05 cycles, each counter increment is now 13 + 11\*(1/256 + 1/(256^2) + ...) = 13.043 cycles.

Now we need 2475073064976549 +/- 10% iterations, or a range of 0x7E9F591BF7A2E - 0x9AC2C23EA071C.

So now we initialize the 7-byte counter to something between 0xF7000000000000 and 0xF7FFFFFFFFFFFF. This ends up giving between 0x08000000000001 and 0x09000000000000 loop iterations, which is within the +/-10% needed.

When the counter rolls over to 0, the last branch gets modified to jump to $0001, which leads to an increment of the BNE opcode itself (to a CMP instruction, which for our purpose is effectively a no-op). Code then falls through to $0008, which now contains a 0 (because of counter rollover). A 0 byte is a BRK instruction, which drops you back to the system monitor, ending the routine.

# Answer
> 20 votes
# PowerShell, ~~35~~ ~~32~~ ~~24~~ ~~21~~ 19 bytes

```
1..3e4|%{sleep 1mb}

```

Try it online!

Strangely, the maximum seconds value for `Start-Sleep` is `2147483`. No, I don't know why it's such an odd value. That works out to a little over `2` megabytes (`2097152`). `1mb * 30000 / 86400 / 365.25` is `996.821051030497`, so a little under 1000 years. I could get more exact using a different value than `3e4`, but this is within the allowed margin and I'm lazy.

*Saved 3 bytes thanks to ceilingcat.*
*Saved 8 bytes thanks to Jeff Zeitlin.*
*Saved 3 bytes thanks to Neil.*
*Saved 2 bytes thanks to Mark Henderson and Nahuel Fouilleul.*

# Answer
> 15 votes
# 05AB1E, 6 bytes

```
27;°.W

```

Inspired by the other answer in 05AB1E.

Waits for 1027/2 milliseconds, or about 1002 years.

Explanation:

```
27            push the number 27
  ;           divide by 2
   °          replace X by 10 to the power of X
    .W        wait that number of milliseconds

```

Try it online!

# Answer
> 11 votes
# Jelly, 8 bytes

```
32œS$ȷ9¡

```

Try it online!

A niladic link which waits for 32 seconds 1 billion times. 32,000,000,000 is within 10% of 31,557,600,000 seconds which is 1,000 years (ignoring leap seconds and ignoring the fact that centuries indivisible by 400 are not leap years).

# Answer
> 11 votes
# Charcoal, 7 bytes

```
Ｆ³³ＲＸφ⁴

```

Try it online! Link is to verbose version of code with a speed up factor of 1e9 (obtained by changing the ⁴ into a a ¹) so that it doesn't time on TIO. Explanation:

```
Ｆ³³

```

Repeat 33 times.

```
ＲＸφ⁴

```

Refresh the screen, but delay 1000⁴ milliseconds between refreshes.

Although there are 33 refreshes, there are only 32 intervals, so the total delay is 32000000000000 milliseconds or approximately 1015 years.

# Answer
> 10 votes
# Java (JDK), 23 bytes

```
v->Thread.sleep(7L<<42)

```

Try it online!

It's hard to find a short way to write a number in Java. `Thread.sleep` only accepts a `long` number of milliseconds. So the standard answer `3e10` doesn't work because it's a double. Casting it to a long would be the appropriate action. But it would still be 1000 too small. So enter `3e13` which is closer. But fortunately, `7L<<42` is `30,786,325,577,728`, which is close to the actual count of 1000 years, and is a `long` without cast, so 4 bytes shorter than `(long)3e13`.

## Credits

* -4 bytes thanks to Neil by replacing `(long)3e13` with `7L<<42`.

# Answer
> 8 votes
# Batch, ~~41~~ 25 bytes

 -8 bytes thanks to AdmBorkBork
-6 bytes thanks to ceilingcat
-2 bytes thanks to inspiration from Neil

```
ping 1 -n 31556952000>nul

```

Using 31,556,952 seconds / year and a (default) 1 second delay between each ping, this will wait 1000 years before returning nothing.

Note that `ping 1` results in failure but it'll fail 31 billion times so that still works.

# Answer
> 8 votes
# APL (Dyalog Unicode), ~~9~~ 8 bytesSBCS

-1 thanks to Eric Towers.

Full program. This works by observing that $$\sum\_{n=1}^{8^6}n=3.44×10^{10}\approx3.16×10^{10}$$which is the number of seconds in a thousand years.

```
⎕dl¨⍳8*6

```

Don't try it online!

`8*6`\\$8^6=262144\\$

**ɩ**ntegers until that

`⎕dl¨`**d**e**l**ay each of those many seconds

# Answer
> 7 votes
# Wolfram Language (Mathematica), 11 bytes

```
Pause[2^35]

```

2 to the 35th power is about 8.9% greater than 31,556,926,000.

# Answer
> 7 votes
# T-SQL, 56 bytes

```
DECLARE @ INT=0a:WAITFOR TIME'9:0'SET @+=1IF @<4E5GOTO a

```
* The SQL `WAITFOR` command is limited to 24 hours, so it has to go in a loop.
* `WAITFOR` has two options: `DELAY` that waits a certain length of time, or `TIME` which waits until a certain time of day. Turns out `WAITFOR TIME'9:0'` (which will pause until 9am the following day) is a couple of bytes shorter than `WAITFOR DELAY'24:0'`.
* Using a `GOTO` loop is shorter than a `WHILE` loop.
* I'm looping `4E5` times (400,000), which is within 10% of the 10-year (365,242 day) goal.
* If I start it today, this would complete in February, 3115

# Answer
> 6 votes
# , 24 bytes

```
sapply(1:25e4,Sys.sleep)

```

Try it online!

A solid starter, feels like there's optimisation to be had with a different function & number combo. This sleeps for 1s, then 2s, then 3s, then 4s... up to 250000s, at which point it's been running for about 990 years and outputs a list of 250k empty elements.

# Answer
> 6 votes
# Lua, 38 bytes

```
t=os.time;o=t()+2^35while t()<o do end

```

Try it online!

Being ANSI C compliant, Lua does not implement any sleep functions, so we have to make one ourselves. Oh, and make sure to keep the dust off that One Thousand Year Computer, we're busy waiting.

# Lua, 38 bytes

```
t=os.time;o=t()+2^35repeat until o<t()

```

Try it online!

Same thing, different loop. Tried to see if I can save some bytes, but nope.

# Answer
> 6 votes
# gbz80 machine code program, 40 (6 + 34) bytes

VBlank handler (put at 0x40)

```
CD 5A 01 F1 FB 76

```

Program after entrypoint (put at 0x150)

```
01 B7 02 21 FF FF 36 01 FB 76 2D 20 14 25 20 11
1D 20 0E 15 20 0B 0D 20 08 05 20 05 2F E0 21 E0
23 C9

```

Runs a timer that decrements every frame. At the Game Boy's frame rate, one thousand years is ~1,884,804,967,414 (0x1B6D7216BF6) frames (with a frame rate of 59.727500569606 fps and the assumption of 24 hours per day and 365.24 days per year). This program's timer runs for 0x1B6\****FEFE frames. The stars are that the middle registers aren't initialized, and the bottom registers are used for an optimization, but the three most significant hex figures are correct and therefore the timer will be well within tolerance.

After the thousand years, the noise channel plays for a short while, and there will be a looping timer that will play the sound every ~149,339 years. Those are some good AAs.

Maybe it could be shorter if you want to cycle count instead of VBlank count.

Source:

```
section "VBlankInterrupt", ROM0[$40]
    call VBlankHandled
    pop af                  ; get rid of pushed return address
    ei                      ; enable interrupts
    db $76                  ; directly encoded halt, one byte saved over "halt"
                            ; ei and halt interact buggily, but it doesn't matter here because we discard the return address.

section "Header", ROM0[$100]
    jr AfterEntryPoint      ; thing for every Game Boy program, shouldn't count

    ds $150 - @, 0          ; Make room for the header

AfterEntryPoint:
    ld bc, $02B7            ; we have to set b one higher, because we decrement then check for zero. also did c because no reason not to and more accuracy
                            ; d and e will be set to their startup values.
    ld hl, $FFFF            ; double-use: part of timer and as a pointer
    ld [hl], $01            ; enable v-blank interrupt only
    ei
    db $76                  ; necessary halt to prevent stack underflow from return, again the return address is discarded so ei halt bug isn't a worry
VBlankHandled:
    dec l
    jr nz, .backToSleep
    dec h
    jr nz, .backToSleep
    dec e
    jr nz, .backToSleep
    dec d
    jr nz, .backToSleep
    dec c
    jr nz, .backToSleep
    dec b
    jr nz, .backToSleep
.madeItOut:
    cpl                     ; invert a, which is 01 from the pop
    ldh [$21], a
    ldh [$23], a            ; this and previous turn on and up the noise channel, which briefly plays because of time limit not being turned off
.backToSleep:
    ret

```

# Answer
> 5 votes
# C# (Visual C# Interactive Compiler), 59 bytes

```
b=>{for(var d=DateTime.Now.AddYears(999);d>DateTime.Now;);}

```

Can be tested by replacing `AddYears()` with `AddSeconds()`

Try it online!

# Answer
> 5 votes
## Mumps (M): 7 Bytes

```
H 9**11

```

Mumps likes single-letter commands & big numbers... H(ang) sleeps for ## of seconds; 9 to the 11th power gives 31381059609 seconds, which is almost 0.6% low for 1000 years; well within the margin of error.

Keeping with the 7 byte code length, I tested "power of 9" sleep times on 2 different Mumps implementations; the largest power of 9 on YottaDB/GT.M I can find without numeric overflow would be:

```
H 9**49

```

which gives a sleep time of just over 1,814 *decillion* millennia. InterSystems' Cache doesn't overflow and can go to:

```
H 9**99

```

which gives 9.352x1083 millennia. That's quite a nap in 7 bytes!

# Answer
> 4 votes
# Pyth, 10 bytes

```
VT.dC"¼€

```

Try it online!

There are exactly 31,557,600 seconds in the Julian astronomical year., totalling 31,557,600,000 seconds in 1000 years. 2^32 is about a tenth of this, so we just wait for 3,155,760,000 seconds ten times. Note that  is a blank codepoint in the TIO, not sure why it translates to this on SE

Here you can see that `C"¼€` is equal to 3,155,760,000

And here is an example that waits for only 22 seconds using a similar method

# Pyth, 8 bytes

```
.dC"XúÃ

```

Try it online!

Alternatively, this one just uses `C"XúÃ` for 31,557,600,000. I thought it was more in line with the spirit of the challenge to have a 2^32 limit, though

---

The average length of a sidereal year, however, is 365.256363004 days or around 31,558,149.763 seconds, giving us a total of ~31,558,149,764 seconds in 1000 years. In this case, the more accurate solution would be

This: `VT.dC"¼ê@`

This:`.dC"Y&ƒ`(1 byte longer than Julian solution)

# Answer
> 4 votes
# Perl 5, 18 bytes

```
sleep 1e9for 1..30

```

Try it online!

10 bytes (doesn't work)

```
sleep 3e10

```

Try it online!

# Answer
> 4 votes
# PHP, 30 bytes

The time() function can be used instead of microtime(1), as when plused with 3e10, PHP converts the value into a float, even when the original value is an int and thereby save some more bytes.

```
time_sleep_until(time()+3e10);

```

See how php converts values
As stated by "manassehkatz-Reinstate Monica" a flag can be set to make it run without the tags in PHP, so a more clean version is here made. (36 bytes)

```
time_sleep_until(microtime(1)+3e10);

```

Google tells me that 1000 years = 3.1556926 × 1010 seconds (31,556,926,000)
The method cloud even be made recoverable in the event of power failures. (not done in this example)

```
<?php time_sleep_until(microtime(true)+31556926000)); ?>

```

The shorter but more imprecise version (45 bytes with the php tags)

```
<?php time_sleep_until(microtime(1)+3e10); ?>

```

With a correction from "Kaddath" this option below is dropped as the documentation state that it is a int not a float used in sleep()
It can be done like so:

```
<?php sleep(31556926000); ?>

```

Try it online!

# Answer
> 4 votes
# JavaScript (Node.js), ~~70~~, ~~67~~, 34 bytes

-3 thanks to Joost K, see their answer for why I used `8e6`
-33 thanks to Benjamin Gruenbaum for pointing out callbacks are better, using the concept of his answer

I've found 2 ways of solving this problem. The first defines `a` globally:

```
(f=_=>a&&setTimeout(f,--a))(a=8e6)

```

the other method passes `a` through each time, using `setTimeout`'s further args:

```
(f=a=>a&&setTimeout(f,--a,a))(8e6)

```

These solutions remain the same length when using IIFEs or just calling the function manually.

# Answer
> 4 votes
# C# (Visual C# Interactive Compiler), 38 37 bytes

this waits 1 + 2 + 3.. +77e5-1 + 77e5ms.

I got this 77e5 magic number using the formula `(x+1)/2*x=3e13` where x results in approximately `7.745.967` which I shortened to 77e5.

To check if it still falls in the allowed range I did `1000*365.25*24*3600*1000/((77e5+1)/2*77e5)` which is `1.064` aka 6.45% of target

update : 8e6 results in `0.98` more precise and less bytes.

```
for(var i=0;i++<8e6;)Thread.Sleep(i);

```

Try it online!

# Answer
> 4 votes
# 05AB1E, 5 bytes

```
₆9e.W

```

Sleeps for about 1082 years.

Try it online!

```
₆         # push 36
 9        # push 9
  e       # nPr (number of 9-element permutations of a 36-element list)
   .W     # wait that many milliseconds

```

# Answer
> 4 votes
# TI-BASIC, 17 bytes

```
For(I,0,2^32:rand(564:End

```

TI-BASIC doesn't have any wait commands/functions, so I just used one of the slowest functions available: generating random lists!

Generating a random list of 564 elements takes \\$\approx7.95\\$ seconds to make and the loop goes through \\$2^{32}\\$ iterations, so that results in \\$7.95\*2^{32}=34144990003.2\\$ seconds or \\$1082.01255\\$ years.

# Answer
> 4 votes
# Matlab, 12 bytes

```
pause(3e+10)

```

This will sleep for 951 years which is within 10% of 1000 years. Note that Matlab can sleep for a floating number of seconds.

This is my first ever answer on CodeGolf :)

# Answer
> 4 votes
# x86-64 function, 10 bytes

```
6A 16 59 48 C1 E1 1F E0 FE C3

```

In assembly:

```
sleep_for_a_thousand_years:
    push 0x17
    pop rcx
    shl rcx,52
    loopnz $
    ret

```

This is a function

The `loopnz` opcode decrements the `rcx` register and jumps if the zero flag is not set and `rcx!=0` after it is decremented. `$` denotes the address of the `loopnz` address itself, so this just loops back to the same instruction over and over until `rcx` is zero.

`loopnz` is infamously slow, and the code before sets `rcx` to 103,582,791,429,521,408. So this will loop 103,582,791,429,521,408 times, which should take 1012 years, based on some benchmarks I did on TIO. (The number may need to be tweaked a bit if you have some overclocked monstrosity though.)

Try it online! ... Actually, maybe skip that just this once.

# Answer
> 3 votes
# Applescript, 10

```
delay 3e10

```

Sleeps for 3 * 1010 seconds.

# Answer
> 3 votes
# 05AB1E, ~~7~~ 6 bytes

```
35oF.Z

```

~8.879% too large

Also take a look at this excellent alternative 6-byter by *@anatolyg*.

**Previous 7-byters:**

```
žqþ¨¨.W     # ~0.449% too small
žG14∍.W     # ~3.837% too large
13°3*.W     # ~4.936% too small

```

For 100% precision (: assuming a year is 365.25 days), use `•Tε‚šä¦•.W` (**10 bytes**) instead.

**Explanations:**

```
35          # Push 35
  o         # Pop and push 2 to the power 35: 34359738368
   F        # Loop that many times:
    .Z      #  And sleep for 1 second every iteration

žq          # Push PI with 15 decimal digits by default: 3.141592653589793
  þ         # Remove the dot by only leaving the digits: 3141592653589793
   ¨¨       # Remove the last two digits: 31415926535897
     .W     # Sleep that many ms

žG          # Push builtin integer 32768
  14∍       # Extend it to size 14: 32768327683276
     .W     # Sleep that many ms

13°         # Push 10 to the power 13: 10000000000000
   3*       # Multiply it by 3: 30000000000000
     .W     # Sleep that many ms

•Tε‚šä¦•    # Push compressed integer 31557600000000
        .W  # Sleep that many ms

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `•Tε‚šä¦•` is `31557600000000`.

05AB1E is built in Elixir, and its sleep builtin can even hold `:infinity` apparently, so I can assume the `.W` has no maximum.

# Answer
> 3 votes
# SmileBASIC, 19 bytes

```
@L
WAIT 12e7GOSUB@L

```

Waits 120 000 000 frames (around 21.2 days), and loops until the GOSUB stack overflows (after 16383 iterations)
This lasts 1038.32 years

# Answer
> 3 votes
# JavaScript (browser), 19 bytes

```
setTimeout("a",3e13)

```

This will throw and error in about a 1000 years.

# Answer
> 2 votes
# SAS, 38 bytes

```
data;do i=1to 3e10;a=sleep(1);end;run;

```

This loop seems to be the shortest option as both `sleep` and `wakeup` are capped at 46 days - slightly less than 222 seconds. I wonder what the rationale for that was?

# Answer
> 2 votes
# JavaScript (Node.js), 34 bytes

uses the 3e13 like most answers but in a for loop. The `1` at the end is to make it a valid for loop.

```
d=Date.now;for(i=d();i>d()-3e13;)1

```

Try it online!

Don't actually try it...

# Answer
> 2 votes
# Roblox, 11 bytes

```
wait(3e+10)

```

Waits 30,000,000,000 seconds, which is roughly equal to 950 years.

# Answer
> 2 votes
# MSX-BASIC, 47 characters

```
1FORK=1TO31557600000:TIME=0
2IFTIME<50GOTO2
3NEXT

```

`TIME` is a MSX-BASIC system variable holding a 50Hz counter that can be initialized to any value at will. There are 31557600000 seconds in 1000 years (assuming one leap year every 4 years) so there you go.

# Answer
> 2 votes
## Zsh/Bash/Sh, 23,19,14,10 bytes

```
sleep 8e6h

```

*-4 bytes thanks to @Grimmy*

## Explanation

GNU coreutils sleep command can take a suffix of either `s` (*seconds*), `m` (*minutes*), `h` (*hours*), or `d` (*days*). It also accepts IEEE-754 numbers, which allows us to use the shorter form of `8e6` to specify 8M hours.

8 million hours is equivalent to roughly 912½ years.

# Answer
> 2 votes
# RPL, 8 bytes

```
3E10WAIT

```

shall wait 3e10 seconds on, say, your hp48sx. Good the OP excluded hardware issues, so we can ignore the reboot at the end of Dec. 31st, 2088 (the date is reinitialized to Jan. 1st, 1989.)

For RPL/2, add one byte as a space is needed before `WAIT`.

I am surprised such commands are accepted anyhow…

Btw a challenge about 2763 years would allow us to use the factorial as in `14!WAIT`.

# Answer
> 2 votes
# MathGolf, 15 bytes

```
{tï╜Ä_⌐_¬Wó+<}▲

```

Just like my top 05AB1E answer, it's ~8.879% too large.

Try it online with debugging argument `-d` to see what's going on.

**Explanation:**

There were a few difficulties to tackle here:

1. Apparently there is no way in MathGolf to access a value outside of the scope of a while-loop. I therefore had to push the initial timestamp inside the loop, and by using some duplicates and stack-rotates access it to check against the current timestamp.
2. After that I initially had `{t_⌐_¬Wó+<}▲` (12 bytes) to overcome the issue mentioned at point 1. Unfortunately there are some bugs in MathGolf, so this required a leading `1`, otherwise the do-while didn't work: `1{t_⌐_¬Wó+<}▲`.
3. MathGold is built in Python, and since Python's List size is limited to 536,870,912 items, I therefore had to remove unused garbage from the stack instead of letting it grow by one additional item every iteration. (Since it executes roughly 5-10 iterations per ms on TIO, the stack size grows way too fast to last even close to 1000 years.) I did this by adding an if-statement in front of that initial duplicate, so I only duplicate it in the very first iteration. For some reason I could now also remove that `1` which was used as a bug-workaround..

Putting it all together gave me the 15-byter you see here, with the following code explanation:

```
{            }▲  # Do-while true with pop:
 t               #  Push the current timestamp
  ï              #  Push the current 0-based loop-index
   ╜             #  If it's falsey (so it's the first iteration):
    Ä            #   Execute the following single command:
     _           #    Duplicate this initial timestamp
      ⌐          #  Rotate the stack, so the bottom item is at the top
       _         #  Duplicate it
        ¬        #  And rotate the stack back, so its both at the top and bottom now
         Wó      #  Push 35, and then pop and push 2**35: 34359738368
           +     #  Add it to the timestamp of the first iteration
            <    #  And check whether it's still lower than the current timestamp

```

# Answer
> 2 votes
# CJam, ~~15~~ 14 bytes

*-1 byte because I forgot that e\[numeric literal\] existed.*

```
es3e13+{_es>}g

```

Please don't try it online, it won't work!

This waits in a while loop until the current Unix timestamp is equal to the timestamp at the beginning of execution plus 3\*10^13 milliseconds (or ~951.3 years).

# Answer
> 2 votes
# Rust, 55 bytes

```
||std::thread::sleep(std::time::Duration::new(2<<34,0))

```

Try it online! (or not, it will take ~1089 years to do anything interesting)

Rust's `thread::sleep` takes a `Duration` as an input, and those conveniently store the count of seconds as a u64.

# Answer
> 2 votes
# VBA, 27 bytes

This program adds an approximation of 1000 years, in days, to the current time, and instructs the program to wait until that time is encountered.

```
Application.Wait 365242+Now

```

For for a more accurate result, the below may be used at a cost of 41 bytes.

```
Application.Wait DateAdd("yyyy",1000,Now)

```

# Answer
> 2 votes
# Python 3, 46 48 bytes

```
import time
for _ in range(7889):time.sleep(4e6)

```

Try it online!

Based on this answer. Used for loop to circumvent the overflow in `time.sleep()`. `3e10` shows overflow but `3e9` doesn't. No Overflow errors are show on the online interpreters(TIO and ATO) but on attempting on personal computer it does show error. The suggestion by @anatolyg has been implemented, which is working on both interpreters.

## Previous erroneous answer

```
import time
for _ in range(10):time.sleep(3e9)

```

# Answer
> 2 votes
# , 11 bytes

```
    6!:3\i.2^18

```

## Explanation:

* `6!:3`: 'delay' function
* `\`: Loop over the entire following value
* `i.2^18`: A list of values from 0 to (2^18)-1

Thanks to @CriminallyVulgar for the 2^18 idea! Try it online... or maybe don't

# Answer
> 2 votes
# Fortran (GFortran), 42 bytes

```
integer(kind=8)i;i=56**6
call sleep(i)
end

```

Try it online!

Gnu Fortran's `sleep` routine only works with an integer number of seconds. Problem is, the default integer type in GFortran only goes up to `2147483647` which only gets us to less than 100 years, and (according to the `units` utility) we need approx `3.1556926e+10` seconds to get us to 1000 years. But we can tweak `i` to a larger type, using `kind=8`, which works fine with `sleep`.

Setting `i=56**6` gets us to `30840979456` seconds, which is more interesting (and closer to 1000 years) than `i=3e10`. I found this number by messing around with cube roots and higher with gnu `bc -l`. Example: `e(l(3e10)/3)` in `bc` gets the cube root, `e(l(3e10)/6)` gets the 6th root!

I suppose I could have just looped the program a few times instead of faffing about with integer types but where's the fun in that?

# Answer
> 2 votes
# Minecraft Command, 45 bytes

```
/summon wind_charge ~5 ~ ~ {Motion:[-7e-12d]}

```

Summons a wind charge 5 blocks away from the player, with a motion towards the player of 7×10⁻¹² blocks per gametick. The wind charge moves slowly towards the player until it's less than 0.6 blocks away, where it touches the player's hitbox and explodes.

This takes (5 - 0.6) / 7e-12 = 628571428571 gameticks or 31428571429 seconds, which is 0.4% less than 1000 years (assuming each year is 365.2425 days long).

This is what it looks like sped up by a factor of 10¹⁰.

# Answer
> 1 votes
# Red, 9 bytes

```
wait 3e10

```

Try it online!

# Answer
> 1 votes
# Tcl, 23 bytes

```
after 30000000000000000

```

Try it online!

# Answer
> 1 votes
# at, 19 bytes

```
at now + 1000 years

```

# Answer
> 1 votes
# **Python 3, all platforms, 91 bytes**

```
from datetime import *;z=datetime.now()+timedelta(days=365242)
while z>datetime.now(): pass

```

The rules say simple termination is fine, which happens after the while loop is done. I couldn't put it all on one line, because the `while` loop has to start on its own line for the interpreter to recognize it. I also didn't want to use `sleep` since the challenge specifically calls that out as the problem.

# Answer
> 1 votes
# Factor, 10 bytes

```
3e16 sleep

```

Try it online!

Factor's `sleep` word is a generic word that can take either a real number denoting nanoseconds or a duration. 3e16 nanoseconds is within 5% error of 1000 years if my calculations are correct.

More straightforward at the cost of some bytes:

# Factor, 15 bytes

```
1e3 years sleep

```

Try it online!

# Answer
> 1 votes
# Stax, ~~8~~ ~~7~~ 6 bytes

```
ê¼@µ~¼

```

Run and debug it

## Approach

17¹⁰ times: wait for one animation frame at 60fps.

Here's a test for 10 seconds.

# Answer
> 1 votes
# Commodore BASIC (Commodore C64/128, C16/+4, VIC-20, CBM/PET), 92 Tokenised BASIC bytes

A thousand years in the Gregorian Calendar at least 365,240 days, plus two or three days depending on the 400 year rule, whereby each start of a new century is a leap year but only once every 400 years, with the year 2000 being a leap year, but 1900 and 2100 are not leap years. As the next leap year at the start of a century will be 2400 I will assume that you want to sleep for 365,242 days. How do we do this with Commodore BASIC?

A day according to a Commodore BASIC interpreter is 5,184,001 jiffies (or 1/60 of a second), which is actually one 60th too many, so over 365,242 days, we are out by the same number of jiffies, which is about 101 minutes, so we will be sleeping for about 1000 years + 101 minutes based on our assumptions above. You can see an explanation of the Commodore TI and TI$ functions on the 8-BIT Show and Tell YouTube channel here.

Firstly, we need to take a copy of the current system time, which one can set in `HHMMSS` in a 24 hour format like `TI$="123000"` \- we then need a busy loop to wait a second so that the copy of the current time and the system timer are not the same. I am also setting the number of days to wait in the `W` variable, which is 365241 as our counter `D` starts at zero.

```
0 C$=TI$: W=365241: D=0: FOR I=0 TO 937: NEXT I

```

Now, we need to wait until TI$ is equal to our copy stored in C$, each time it is we know that it has been 24 hours and 1/60th of a second. When this is true, we can jump to a sub routine that will add 1 to the number of days, and return. Note that using `STEP 0` in our `FOR/NEXT` loop creates an endless loop with our break condition being in the subroutine on line 2.

```
1 FOR I=0 TO 1 STEP 0: ON -(TI$=C$) GOSUB 2: NEXT I

```

When we jump to the subroutine at line 2, TI$ and C$ may still contain the same values, so we need a busy loop until TI$ is one second ahead again of C$. Then we can add 1 to our day counter, and if the counter has fewer days than our `W` variable set above, we will return from our sub-routine which will wait again until another 24 hours and 1 jiffy has passed.

```
2 ON -(TI$=C$) GOTO 2: D=D+1: IF D<W THEN RETURN

```

The full crunched listing (with removed whitespaces) would look like this:

```
0C$=TI$:W=365241:D=.:FORI=.TO1E3:NEXT
1FORI=.TO1STEP.:ON-(TI$=C$)GOSUB2:NEXT
2ON-(TI$=C$)GOTO2:D=D+1:IFD<WTHENRETURN

```

# Answer
> 1 votes
# YASEPL, 31 bytes

```
=aŔ9+31556952000000`1=bŔ9}2,a

```

terminates when finished.

sets a date to `a`, adds 1000 years in milliseconds, then goes into a while loop that checks if the current date is less than `a`. aka:

```
let a = new Date() + 31556952000000;

do {
  let b = new Date();
} while(b < a);

```

# Answer
> 1 votes
# Uiua, 7 bytes

```
&sl3e10

```

## Explanation

```
&sl3e10
   3e10 # Push 30000000000 to the stack
&sl     # Sleep for that many seconds

```

On Uiua's online pad, `&sl` hangs the page for how many seconds specified. Here's a sample that hangs for 10 seconds.

Unfortunately, 3e10 seconds is only around 951 years, so everyone'll have to wait 49 more. Thankfully it's only 95.07% of a millennium in seconds.

# Answer
> 0 votes
# Scratch (scratchblocks3 syntax), 30 bytes

It's the obvious solution but it's surprisingly short for a Scratch program. Sleeps for exactly 951.3 years + a few milliseconds.

```
when gf clicked
wait(3e10)secs

```

# Answer
> 0 votes
## Pascal, 284 B

This complete Pascal `program` requires a processor supporting features defined by ISO standard 10206 “Extended Pascal”, in particular the `timeStamp` built‑in data type and `getTimeStamp` routine. The program simply performs a busy wait.

```
program p;var r,n:timeStamp;begin getTimeStamp(r);with r do begin
year:=year+1000;day:=day-ord(month=2)*ord(not(0 in[year mod 4]-[year mod 100]+[year mod 400]));repeat
getTimeStamp(n)
until[1=1]=[n.year=year,n.month=month,n.day=day,n.hour=hour,n.minute=minute,n.second=second]end end.

```

The `program` terminates if exactly 1 kiloyears have passed (second granularity), else it is non‑terminating (for instance if the operating system’s scheduler put the `program` in a *waiting state* during the crucial second).

```
program millenniumSleep;
    var
        reference, now: timeStamp;
    begin
        getTimeStamp(reference);
        { We presume `reference.dateValid` and `reference.timeValid` are `true`.
          The processor does feature an operational real‑time clock. }

        with reference do
        begin
            { Add a millennium to `timeStamp`. }
            year ≔ year + 1000;
            { Accommodate for leap day. }
            day  ≔ day − ord(month = 2) *
                ord(not (0 in [year mod 4] − [year mod 100] + [year mod 400]));

            { We presume evaluation of the loop takes at most one second. }
            repeat
            begin
                getTimeStamp(now);
            end
            { The embracing `with reference do` language construct
              allows us to abbreviate `reference.year` to `year` and so forth. }
            until [true] = [now.year = year, now.month = month, now.day = day,
                now.hour = hour, now.minute = minute, now.second = second]
        end
    end.

```

The leap year test has been adopted from a different challenge. The `program` needs to be started before the year `maxInt − 1000`. The value of the built‑in constant `maxInt` is implementation‑defined.

# Answer
> 0 votes
# Kotlin, 25 bytes

```
{Thread.sleep(7L shl 42)}

```

111 followed by 41 zeros (binary) is ~97.56% of 31556952000000 (decimal)

Try it online!

---
Tags: code-golf, date
---


# Question
Title: Give two points with the most similar distances to the origin
Consider an \\$(n+1) \times (n+1) \\$ grid of points places at non-negative integer coordinates. Given two points in the grid at \\$(a, b)\\$ and \\$(c, d)\\$, we know that the distance of the first point to the origin at \\$(0, 0)\\$ is \\$x = \sqrt{a^2 + b^2}\\$ and the distance of the second point to the origin is \\$y = \sqrt{c^2 + d^2}\\$.

Given a positive integer \\$n\\$, the task is to find non-negative integers \\$0 \leq a, b, c, d \leq n \\$ so that \\$|x - y|\\$ is as small as possible but **not** equal to zero.

# Input

Positive integer \\$n\\$

# Output

Two points \\$(a, b)\\$ and \\$(c, d)\\$ that minimize \\$ |\sqrt{a^2 + b^2} - \sqrt{c^2 + d^2}|\\$ under the constraint that \\$ |\sqrt{a^2 + b^2} - \sqrt{c^2 + d^2}| \ne 0\\$.

# Example

If \\$n=7\\$ then \\$(7, 2)\\$, \\$(4, 6)\\$ is a valid output.

# Answer
# Python, 114 bytes

*-1 byte thanks to @Stefan Pochmann*

```
lambda s:[r:=range(s+1)]*0+max([(e:=a*a+b*b)-c*c-d*d==1,e,a,b,c,d]for a in r for b in r for c in r for d in r)[2:]

```

Attempt This Online!

Finds \\$a, b, c, d\\$ where \\$(a^2+b^2)-(c^2+d^2)=1\\$ and \\$a^2+b^2\\$ is maximal.

## Proof

The lower bound on difference between distances when \\$(a^2+b^2)-(c^2+d^2)\>1\\$ is $$\sqrt{n^2+n^2}-\sqrt{n^2+n^2-2}$$ $$\sqrt{2n^2}-\sqrt{2n^2-2}$$ We can show points \\$(n, 1)\\$ and \\$(n, 0)\\$ always have distances closer than this lower bound with some simplification $$\sqrt{n^2+1^2}-\sqrt{n^2-0^2}\<\sqrt{2n^2}-\sqrt{2n^2-2}$$ $$\sqrt{n^2+1}-\sqrt{n^2}\<\sqrt{2}\cdot(\sqrt{n^2}-\sqrt{n^2-1})$$ $$\sqrt{n^2+1}-\sqrt{n^2}\<\sqrt{n^2}-\sqrt{n^2-1}$$ The last statement is easy to see as \\$\sqrt{x}\\$ increases more slowly the further right in the \\$x\\$-axis we go, more formally the second derivative (change in slope) of \\$\sqrt{x}\\$ is always negative.

This means in the solution \\$(a^2+b^2)-(c^2+d^2)=1\\$ will always hold. Maximizing \\$a^2+b^2\\$ is also easy to see and also arises due the second derivatives of \\$\sqrt{x}\\$ being always negative.
> 9 votes

# Answer
# Uiua 0.10.0, 30 bytes SBCS (updated)

```
⍉⊟°ℂ⊏⊢⍏∩▽,⟜±⌵≡/-⌵.☇1⊞⊂.♭⊞ℂ.⇡+1

```

## Old solution, 32 bytes, faster

```
⍉⊟°ℂ⊏+⇡2⊢⍏≡/-◫2⌵.⊏⍏⌵.▽◰⌵.♭⊞ℂ.⇡+1

```

Try on Uiua Pad!

```
⇡+1      # range 0...n
♭⊞ℂ.    # grid of complex values
▽◰⌵.   # remove duplicate lengths
⊏⍏⌵.    # sort by lengths
≡/-◫2⌵. # get differences between adjacent lengths
+⇡2⊢⍏    # get indices for smallest difference
⍉⊟°ℂ⊏   # pick and translate complex to points

```

The new solution is slower because it makes a list of every possible pair of points, but otherwise it does much of the same.
> 5 votes

# Answer
# Jelly, 15 bytes

```
ŻŒċ⁺µ²§½ạ/ȯ1µÞḢ

```

A monadic Link that accepts \\$N\\$ and yields a pair of pairs of integers.

**Try it online!**

### How?

Brute force, although I can't help but think some divisor-based logic could work.

```
ŻŒċ⁺µ²§½ạ/ȯ1µÞḢ - Link: positive integer, N
Ż               - zero-range {N} -> [0..N]
 Œċ             - unordered pairs, with replacement -> points above or on y=x
   ⁺            - repeat -> all pairs of those points (up to reordering)
    µ       µÞ  - sort these pairs of points by:
     ²          -   square all the values
      §         -   sum each pair of squares
       ½        -   square-root these two values
        ạ/      -   reduce by absolute difference
          ȯ1    -   logical OR with 1 (replace zeros with ones)
              Ḣ - head

```
> 5 votes

# Answer
# Vyxal 3, 14 bytes

```
z:Ẋ:Ẋⁿλ²Ṡ√/ȧ1∨

```

Try it Online!

Pretty much just the trivial solution. Uses Jonathan Allan's trick for avoiding returning zero values (well, this is just a port of Jonathan Allan's solution, but it's pretty much straightforward).

### Explanation

```
z:Ẋ:Ẋⁿλ²Ṡ√/ȧ1∨    Full Program
z                 0..x
 :Ẋ               Cartesian Product with itself (gives a list of points)
   :Ẋ             Cartesian Product with itself (gives a list of pairs)
     ⁿλ           Minimum by lambda:
       ²          - Square (vectorized)
        Ṡ         - Sum Each
         √        - Square Root (vectorized)
          /ȧ      - Reduce over Absolute Difference
            1∨    - || 1 (if 0, replace with 1)

```
> 5 votes

# Answer
# JavaScript (ES7), 108 bytes

Returns `[a,b,c,d]`.

This is based on Mukundan314's method.

```
n=>eval(m="for(i=++n**4;i--;a*a+b*b+~(x=c*c+d*d)|x<m||(m=x,o=A))A=[a,b,c,d]=[1,0,3,2].map(j=>i/n**j%n|0);o")

```

Try it online!
> 2 votes

# Answer
# Haskell, 98 bytes

```
f n=tail$minimum[e:l|l@[a,b,c,d]<-mapM id$[0..n]<$"four",e<-[abs$sqrt(a^2+b^2)-sqrt(c^2+d^2)],e>0]

```

Try it online!
> 2 votes

# Answer
# Charcoal, ~~54~~ 43 bytes

```
≔⊕ＮθＩΦ⌈ＥΦＥ…Ｘθ³Ｘθ⁴↨ιθ⁼¹↨Ｅ⪪Ｘι²¦²Σλ±¹⮌⊞ＯιΣＸι²κ

```

Try it online! Link is to verbose version of code. Explanation: Even more brute force than before, but still a port of @Mukandan314's Python answer.

```
≔⊕Ｎθ

```

Input `n` and increment it.

```
Ｅ…Ｘθ³Ｘθ⁴↨ιθ

```

Convert the range from `(n+1)³` to `(n+1)⁴` into base `n+1` so the results all have four base-`n+1` digits `d`, `c`, `b` and `a`.

```
Φ...⁼¹↨Ｅ⪪Ｘι²¦²Σλ±¹

```

Filter on those where `a²+b²=c²+d²+1`.

```
Ｅ...⮌⊞ＯιΣＸι²

```

For each of those, prefix `a²+b²+c²+d²` to `a,b,c,d`.

```
ＩΦ⌈...κ

```

Output the `a,b,c,d` with the maximum sum of squares.
> 2 votes

# Answer
# Wolfram Language (Mathematica), ~~132~~ ~~96~~ 68 bytes

Saved 36 bytes thanks to @lesobrod, Saved 28 bytes thanks to @att

---

68 bytes version. Try it online!

```
ArgMin[{g=Abs[Norm@{x,y}-Norm@{z,}],g>0<=a<=#},a={x,y,z,},Integers]&

```

96 bytes version. Try it online!

```
ArgMin[{g=Abs[Norm@{x,y}-Norm@{z,}],g>0<=a<=#},a={x,y,z,},Integers]&

```

132 bytes version. Try it online!

```
f[n_]:=Module[{r=Minimize[{Sqrt[a*a+b*b]-Sqrt[c*c+d*d],0<=a<=n,0<=b<=n,0<=c<=n,0<=d<=n,a*a+b*b>c*c+d*d},{a,b,c,d},Integers]},r[[2]]]

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), ~~82~~60 bytes

-22 bytes thanks to @att!

```
MinimalBy[Range@#~Tuples~{2,2},N[r={1,-1}.Norm/@#]/Sign@r&]&

```

Significantly different approach from this answer, so separate post.
As is customary in Codegolf *we don’t have to be efficient in performance or running time*.
So here just brute-force selection from all possible tuples. So answer is also all possible combinations, eg for input `7` output is `{{{2, 7}, {4, 6}}, {{2, 7}, {6, 4}}, {{4, 6}, {2, 7}}, {{4, 6}, {7, 2}}, {{6, 4}, {2, 7}}, {{6, 4}, {7, 2}}, {{7, 2}, {4, 6}}, {{7, 2}, {6, 4}}}`

Try it online!
> 2 votes

# Answer
# JavaScript (Node.js), 100 bytes Mukundan314's method

```
n=>(m=g=(a,b,c,d)=>(a?g(a-1,b,c,d):1)/d?a*a+b*b+~(x=c*c+d*d)|x<m||(o=[a,b,c,d],m=x):g(n,a,b,c))()&&o

```

Try it online!

# JavaScript (Node.js), 113 bytes

```
n=>(m=g=(a,b,c,d)=>(a?g(a-1,b,c,d):1)/d?(v=(h=Math.hypot)(a,b)-h(c,d))>m|v<=0||(o=[a,b,c,d],m=v):g(n,a,b,c))()&&o

```

Try it online!

+1 byte like Arnauld's if some issue

```
n=>(
  m=                     // Last Length
  g=(a,b,c,d)=>
    (a?g(a-1,b,c,d):1)   // g(a-1,b,c,d) would return a positive number
    /d?                  // if d is number
      (v=(h=Math.hypot)(a,b)-h(c,d))
                         // Compare length
      >m|v<=0||          // Require it positive. Negative mean (c,d,a,b) is positive
      (o=[a,b,c,d],m=v)  // Update
    :g(n,a,b,c)          // Nest layer
)()&&o                   // Output

```
> 1 votes

---
Tags: code-golf
---