# Question
Title: Write an program that terminates after 60 seconds - Cops' Thread
This is a cops and robbers challenge - Robber's Thread

Write a program that terminates after exactly 60 seconds (or as close to it as possible). For example:

```
#include <unistd.h>
int main(int argc, char **argv){
    sleep(60);
    return 0;
}

```

However, your goal is to write this program such that terminating after exactly 1 minute is essentially *inherent* to the program's execution - it should be difficult to change the program to predictably run for a different amount of time without overhauling the algorithm. The robbers will attempt to change your program such that it terminates after **31** seconds instead of 60, and they will have to do so with a solution whose Levenshtein edit distance is up to half of the length of your submission.

If you do not wish to take advantage of system interrupts or the system clock, you can use either of the following:

* The speed of printing to `stdout` is controlled by the baud rate of the terminal you are printing to. If you wish, you can control the speed of your program by printing to `stdout` with a set baud rate. However, you must also cite an actual piece of hardware or terminal program that has that baud rate as default (e.g. a serial printer with a default print speed of 300 baud).
* If you are working in a language where all operations take some constant amount of time (such as assembly language), you can control the speed of your program by specifying the processor's clock rate. However, this too must be accompanied with a citation of an actual processor chip that runs at that speed (e.g. the 1 MHz 6502 put inside Apple //e and NES boards).

This is cops and robbers, so prepare to rigorously defend your algorithm! If your solution has been cracked, put `[Cracked](link to cracker)` in your header. If your solution remains uncracked after exactly **2 weeks**, it is safe from future cracking attempts - put `Safe` in your header and explain how your algorithm works.

The winner of this challenge is the Safe solution with the most upvotes.

# Answer
# Perl 52 bytes (26 edits allowed) (Safe, technically speaking)

```
sub a{[gmtime+time]->[0]^$x}$x=a;0 until a;0 while a

```

Unfortunately, I don't think it's possible to write an uncrackable Perl program (it should become obvious why if and when this is cracked; being able to edit half the program is just too much), but this algorithm should be very hard to change to wait for any length of time other than 1 minute.

Marking this as safe, as nobody's officially submitted a crack for 14 days (although someone unofficially cracked it by just writing a separate program and commenting out the existing code). The basic idea of the program is as follows: we look at the seconds digit of the time, loop until it changes, then loop until it returns to its original value. This requires quite some changes to alter to a length of time other than 1 minute, 1 hour, or 1 day (although 26 edits is easily enough – you can do some modular arithmetic on the seconds value to determine a new target to wait until – but nobody found that solution).
> 6 votes

# Answer
# Jelly, 30 bytes, cracked

```
69266249554160949116534784œSÆl

```

This can't be tested online since TIO has a 60 second timeout.

### Verification

```
$ time jelly eun '69266249554160949116534784œSÆl'
69266249554160949116534784

real    1m0.033s
user    0m0.433s
sys     0m0.041s

```

### How it works

The natural logarithm (`Æl`) of **69266249554160949116534784** is **59.5**. `œS` sleeps that many seconds before returning its left argument. Adding the wait time to the **500ms** boot time of Jelly (mostly spent loading SymPy and NumPy) gives an execution time of roughly one minute. This is on a third generation Core i7 CPU at 3.40 GHz and an SSD. The boot time will naturally vary on other computers.
> 1 votes

# Answer
# reticular, 11 bytes, Cracked

```
[[3w]5*]4*;

```

Running:

```
λ timecmd reticular test.ret
command took 0:1:0.38 (60.38s total)

```

(`timecmd` link)

## Explanation

```
[[3w]5*]4*;
[      ]4*  execute this 4 times
 [  ]5*     execute this 5 times
  3w        wait 3 seconds
          ; terminate program

```
> 0 votes

# Answer
# Pyth - 5 bytes (distance of 2 allowed) Cracked.

```
.d*T6

```

Mess with it online (though it times out with 60 seconds).
> 0 votes

---
Tags: cops-and-robbers
---


# Question
Title: Write an program that terminates after 60 seconds - Robbers Thread
This is a cops and robbers challenge - Cop's Thread

Each of the cops have been tasked to write a program that terminates after exactly 60 seconds, or as close as possible. For example:

```
#include <unistd.h>
int main(int argc, char **argv){
    sleep(60);
    return 0;
}

```

Your goal is to take any of the uncracked submissions and change it so that it terminates after **31** seconds. If a cop's answer has been up for more than two weeks, it is immune to cracking. The original answer and your edit must have a Levenshtein edit distance of up to half of the original program's length.

The robber with the most cracks wins!

The cops have been allowed to do either of the following if they do not wish to use the system time calls:

* The speed of printing to `stdout` is controlled by the baud rate of the terminal you are printing to. If you wish, you can control the speed of your program by printing to `stdout` with a set baud rate. However, you must also cite an actual piece of hardware or terminal program that has that baud rate as default (e.g. a serial printer with a default print speed of 300 baud).
* If you are working in a language where all operations take some constant amount of time (such as assembly language), you can control the speed of your program by specifying the processor's clock rate. However, this too must be accompanied with a citation of an actual processor chip that runs at that speed (e.g. the 1 MHz 6502 put inside Apple //e and NES boards).

If you encounter a solution with this specification, you cannot change this parameter. (Not that it would help you much anyway, since it's hard to find an upgraded chip or serial output device with a 31:60 speed ratio).

# Answer
> 2 votes
# Jelly, edit distance 5 from 30 bytes

Original:

```
69266249554160949116534784œSÆl

```

Crack:

```
69266249554160949116534784œSÆl**_29$$**

```

I just subtracted 29 from the timeout immediately before the `œS` runs. (`_29` subtracts 29, the dollars control precedence, a bit like parentheses in other languages.)

# Answer
> 1 votes
# reticular, edit distance 4 from 11 bytes

Original:

```
[[**3**w]5*]**4***;

```

Crack:

```
**6w**[[**1**w]5*]**5***;

```

The edit distance we've been given is just way too high to make cracking difficult. There was a lot of freedom in this one, so I aimed for one that preserved the spirit of the original code.

# reticular, edit distance 3 from 11 bytes

I found an improved crack, here it is:

Original:

```
[[3w]5*]**4***;

```

Crack:

```
**1w**[[3w]5*]**2***;

```

# Answer
> 1 votes
# Pyth, 5 bytes, Maltysen

```
.dh*T3

```

`*T3` computes **30**, `h` increments, and `.d` waits for that many seconds.

---
Tags: cops-and-robbers
---


title: Manhattan distance of rotation sequence

text:
# Question
Title: Manhattan distance of rotation sequence
I though this would be a good challenge : http://adventofcode.com/2016/day/1

# Task description

Given a sequence of rotations and distances following the pattern (L|R)\[1-9\]\[0-9\]\*, give the manhattan distance between the start and the ending points, that is the minimal number of vertical and horizontal moves on a grid.

# Examples

For example, if we assume you started facing North:

Following R2, L3 leaves you 2 blocks East and 3 blocks North, or 5 blocks away. R2, R2, R2 leaves you 2 blocks due South of your starting position, which is 2 blocks away. R5, L5, R5, R3 leaves you 12 blocks away.

# Technical details

You can choose the separator between the moves (e.g. : "\n", ", ", or ","). You must give the answer as an integer in base 10.

# Not a duplicate!

It is not a duplicate for multiple reasons :

* The moves are not the same. Here they are **rotations**, not directions.
* I want the Manhattan distance, not the euclidian.

# Answer
# Python 3, ~~109~~ ~~99~~ ~~104~~ 101 bytes

This is a simple answer that uses complex numbers, with input as a space-separated string or a newline-separated string. Golfing suggestions welcome!

**Edit:** -13 bytes thanks to Labo. +5 bytes for converting to an int.

```
d=p=0
for r in input().split():d+=1-2*(r<'R');p+=1j**d*int(r[1:])
print(int(abs(p.real)+abs(p.imag)))

```

**Ungolfing**

```
def manhattan_rotation(seq, nsew=0, pos = 0):
    for rot in seq.split():
        # change direction
        if rot[0] == "L":
            nsew += -1
        else:
            nsew += 1
        # move in that direction rot[1:] times
        pos += 1j ** nsew * int(rot[1:])
    return int(abs(pos.real)+abs(pos.imag))

```
> 4 votes

# Answer
# PHP, 93 bytes

```
while($m=$argv[++$i])${chr(80|3&$d+=(P<$m)-(M>$m))}+=substr($m,1);echo abs($P-$R)+abs($Q-$S);

```

**breakdown**

```
while($m=$argv[++$i])       // loop through arguments:
    ${                      // 5. use as variable name
        chr(                // 4. cast to character (P,Q,R,S)
        80|                 // 3. add 80
        3&                  // 2. modulo 4
        $d+=(P<$m)-(M>$m)   // 1. change direction depending on letter
    )}+=substr($m,1);       // 6. add number to variable
echo abs($P-$R)+abs($Q-$S); // calculate distance, print

```
> 2 votes

# Answer
## Python 2, 86 bytes

```
x=y=0
for d in input().split():c=cmp(d,'M');x,y=int(d[1:])-y*c,x*c
print abs(x)+abs(y)

```

Tracks the current `x` and `y` coordinates. When turning, instead of updating the direction, rotates the current value so that the motion is always in the x-positive direction. Complex numbers were too costly to extract the coordinates from.
> 2 votes

# Answer
# Python 2, ~~103~~ 102 bytes

```
l=c=0
for i in input().split():c+=cmp(i[0],'N');l+=1j**c*int(i[1:])
print int(abs(l.imag)+abs(l.real))

```

**repl.it**

Input is a string of space delimited directions, e.g. `"R5 L5 R5 R3"`.
Prints out the Manhattan distance between the starting location and the destination.

### How?

Starts at the origin of the complex plane, `l=0`;

With a cumulative quarter-right turn counter, `c=0`;

For each instruction, `i`, the rotation is parsed is by comparing the first character of the direction to the character `'N'`, and `c` is adjusted accordingly.

The distance to travel is parsed with `int(i[1:])` and the instruction is enacted by taking that many block sized steps in the direction given by taking the `c`th power of `0+1j` with `1j**c`.

The final Manhattan distance is the sum of the absolute distances from the origin in the two directions - imaginary and real; achieved with `abs(l.imag)+abs(l.real)`
> 1 votes

# Answer
# JavaScript (ES2016), 98 ~~100~~

2 bytes saved thx @Neil

```
d=>d.replace(/.(\d+)/g,(d,l)=>(o+=d>'M'||3,l*=~-(o&2),o&1?x-=l:y+=l),x=y=o=0)&&(x*x)**.5+(y*y)**.5

```

**100** bytes for ES6

```
d=>d.replace(/.(\d+)/g,(d,l)=>(o+=d>'M'||3,l*=~-(o&2),o&1?x-=l:y+=l),x=y=o=0)&&(x>0?x:-x)+(y>0?y:-y)

```

*Less golfed*

```
d => d.replace(/.(\d+)/g,
  (d,l)=>( // L or R in d, distance in l
    o += d>'M' || 3, // orientation in o, used %4
    l *= ~-(o&2), // convert to number and change sign if needed
    o&1 ? x -= l : y += l // move based on orientation
  ), x = y = o = 0)
&& (x>0?x:-x) + (y>0?y:-y)

```

**Test** (ES6)

```
F=
d=>d.replace(/.(\d+)/g,(d,l)=>(o+=d>'M'||3,l*=~-(o&2),o&1?x-=l:y+=l),x=y=o=0)&&(x>0?x:-x)+(y>0?y:-y)

function update() {
  O.textContent=F(I.value)
}

update()
```

```
<input id=I value='R5, L5, R5, R3' oninput='update()'><pre id=O></pre>
```
> 0 votes

---
Tags: code-golf
---


title: Steganographic Squares

text:
# Question
Title: Steganographic Squares
# Steganographic Squares

Your job is to take in a string, and generate an `NxN` image that represents this string. You must also write the algorithm that takes in the image and turns it back into a string as well. The scoring will be will include the byte count of both algorithms:

**"Encryption" Algorithm + "Decryption" Algorithm**.

You should post each separately, with byte-counts for both the encryption and decryption algorithms displayed individually.

---

# Example Algorithm

For instance, here's the "Programming Puzzles and Code Golf" using a simple ASCII based steganographic algorithm in the Blue channel:

```
#2e7250,#6ea972,#04eb6f,#0fc767,#74ab72,#ee6161
#b73b6d,#1aae6d,#f37169,#bda56e,#1fe367,#e99620
#706450,#0d3575,#146b7a,#4ea47a,#2a856c,#95d065
#3f2d73,#cef720,#bab661,#d1b86e,#f22564,#12b820
#0f3d43,#c86e6f,#1ee864,#a66565,#247c20,#c3bb47
#0e296f,#89d46c,#585b66,#c08f20,#455c20,#136f20

```

Actual Image (  )

You can see the blue channel simply holds the ascii values for this image:

```
50 =  80(P) 72 = 114(r) 6f = 111(o) 67 = 103(g) 72 = 114(r) 61 =  97(a)
6d = 109(m) 6d = 109(m) 69 = 105(i) 6e = 110(n) 67 = 103(g) 20 =  32( )
50 =  80(P) 75 = 117(u) 7a = 122(z) 7a = 122(z) 6c = 108(l) 65 = 101(e)
73 = 115(s) 20 =  32( ) 61 =  97(a) 6e = 110(n) 64 = 100(d) 20 =  32( )
43 =  67(C) 6f = 111(o) 64 = 100(d) 65 = 101(e) 20 =  32( ) 47 =  71(G)
6f = 111(o) 6c = 108(l) 66 = 102(f) 20 =  32( ) 20 =  32( ) 20 =  32( )

```

While the rest of the channels hold randomly generated values to "spice up" the variety of colors in the image. When pulling the message back out of the image, we can just simply ignore the other channel values, and pull the hex bit in the blue channel, reconstructing the string:

```
"Programming Puzzles and Code Golf"

```

Notice the spaces that were used to pad the string in the square are not included in the final decrypted output. While you must pad the string in the image, you may assume that the input string will not end with spaces.

---

# Rules

* You must encode 1 character per pixel, the channel chosen to encode the char is arbitrary.
* The channels of the other RGB colors must be randomized, other than the one you're choosing to encode the string into; this means your final non-encoded channels would need to be between `0x0000-0xFFFF` (randomly chosen).
* Expressing the final result as a 2D array of RGB color values is fine `0x000000-0xFFFFFF`, no need to use image creation unless you want to have fun with it or if it's less bytes. If you choose to output as hex strings, prefix the hex string with `#` E.G. `#FFFFFF` or `#05AB1E`. You may separate with tabs, commas, or anything else that would be horizontally sensible, but it must maintain the square pattern; in other words, you must use appropriate newline separation.
* The output must be in a square, and the string must be padded with spaces at the end to accomodate this. This means that `N≈SQRT(Input#Length())`. If the input length is not a perfect square, you should round up on `N` and pad with spaces.
* As stated previously, if you are padding with spaces in the image, you must not include the padded characters in the final "decrypted" output.
* You can assume that:
    + The input string will not end with spaces.
    + The input string will only use printable ASCII characters.
* This is , lowest byte count wins.

# Answer
# 05AB1E, 34 + 12 = 46 bytes

Uses red channel.
05AB1E uses CP-1252 encoding.

**Encode:**

```
DgDtî©n-Äð×JvyÇh`4F15Ý.Rh«}})'#ì®ä

D                                   # duplicate input
 gDtî©n-Ä                           # abs(len(input)-round_up(sqrt(len(input)))^2)
         ð×J                        # join that many spaces to end of input
            v                       # for each char in string
             yÇ                     # get ascii value
               h`                   # convert to base-16 number
                 4F                 # 4 times do:
                   15Ý.Rh           # push random base-16 number
                         «          # concatenate
                          }}        # end inner and outer loop
                            )       # wrap in list
                             '#ì    # prepend a "#" to each element in list
                                ®ä  # split in pieces round_up(sqrt(len(input))) long

```

Try it online!

**Decode:**

```
˜vy3£¦HçJ}ðÜ

˜               # deep flatten input to a list
 v              # for each color in the list
  y3£           # take the first 3 chars
     ¦          # remove the hash sign
      H         # convert from base-16 to base-10
       ç        # get the ascii char with that value
        J       # join to string
         }      # end loop
          ðÜ    # remove trailing spaces

```

Try it online!

**Alternative padding method with equal byte-count**

```
Dgð×J¹gtî©n£

```
> 2 votes

# Answer
# C, 201 (Encoding) + 175 (Decoding) = 376 bytes

**To Encode:**

```
E(char*J){size_t L=ceil(sqrt(strlen(J)));int U;srand(time(NULL));for(int i=0;i<L;i++){for(int f=0;f<L;f++){printf("#%02X%02X%02X ",rand()%256,(U<strlen(J))?(int)J[U]:32,rand()%256);U+=1;}printf("\n");}}

```

Encodes each character of the input string in the green channel of the RGB spectrum while setting the two other channels as random hex values. Takes input through STDIN as a string and outputs to STDOUT a multiline string of hex color code in the shape of a square. Assuming you have Python 3 and ImageMagick installed, and the above file is compiled into a file named `a.out` in the current working directory (CWD), you can directly get the resulting image, named `Output.png`, to the CWD from the textual output using the following command:

```
./a.out "<Multiline Input>"|python3 -c "import sys,subprocess;Input=sys.stdin.read();print('# ImageMagick pixel enumeration: {0},{0},255,rgb\n'.format(len(Input.split('\n')[1].split()))+'\n'.join(['%d,%d:(%d,%d,%d)'%(g,i,int(j[1:][:2],16),int(j[1:][2:4],16),int(j[1:][4:6],16))for g,h in enumerate(Input.split('\n'))for i,j in enumerate(h.split())]))"|convert - -scale 1000% Output.png

```

Here is a sample output image created by the above commamd using `Programming Puzzles and Code Golf` as the input string:

**To Decode:**

```
D(int c,char**U){char T[c];for(int Y=1;Y<c;Y++){char G[2]={U[Y][3],U[Y][4]};T[Y-1]=(char)strtol(G,NULL,16);}int C=c-1;T[C]='\0';while(T[C]==' '){T[C]='\0';C-=1;}printf("%s\n",T);}

```

Takes input through STDIN a sequence of space-separated hex color code strings with each one enclosed in double quotes (`"`) (`char** argv` in `main`) and also, when called in `main`, `int argc` for the integer input. Outputs to STDOUT a single/multi-line string representing the decoded message.

I will try to golf these more over time whenever and wherever I can.

---

Also, if you same both of the methods into the same file, you can use the following `main` method to put it all together with each function getting the correct inputs:

```
int main(int argc,char**argv){if(strcmp(argv[1],"E")==0){Encode(argv[2]);}else{Decode(argc,argv);}}

```

and using this, for encoding you must provide `E` as the first argument to call the encoding method followed by the single string argument, whereas for decoding, all you need to provide is the sequence of space-separated hex color code strings with each one enclosed in double-quotes (`"`).

---

Finally, if you want, you can get the fully prepared, ready-to-use version here, although it is not golfed, but also does not output *any* warnings or errors upon compilation.
> 4 votes

# Answer
# Python 2, ~~164~~ 160 + ~~94~~ 93 = 253 bytes

Saved 1+1 byte thanks to Wheat Wizard.

-5 bytes thanks to Kade

Encoder: string must be enclosed in quotes, e.g. `"CodeGolf"`, output is a color ascii PPM image.

```
from random import*
s=input()
n=int((len(s)-1)**0.5)+1
s=s.ljust(n*n)
r=randint
print"P3 %d %d 255 "%(n,n)+''.join("%d "*3%(r(0,255),r(0,255),ord(c))for c in s)

```

Decoder: Takes input filename as command line argument

```
from sys import*
print''.join(chr(int(c))for c in open(argv[1]).read().split()[6::3]).strip()

```

Usage:

```
 python golf_stegansquare_enc.py > stega.ppm

 python golf_stegansquare_dec.py stega.ppm

```

Example:

Programming Puzzles and Code Golf

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
> 3 votes

# Answer
# Scala, 97 + 68 = 165 bytes

Encryption (97 bytes):

```
s=>s.map(_+((math.random*65535).toInt<<8)).iterator.grouped(math.sqrt(s.size)toInt)withPadding 32

```

Takes a String and retuns an Iterator of Sequences of Integers.

Decryption (68 bytes):

```
a=>" +$".r.replaceAllIn(a.flatten.map(h=>(h&0xFF)toChar)mkString,"")

```

Takes an Iterator of Sequences of Integers and returns a string.

Explanation:

```
s=>                         //define an anonymous function
  s.map(                      //map each char of the string
    _+(                         //to the ascii value plus
      (math.random*65535).toInt)  //a random integer between 0 and 65535
      <<8                         //shifted 8 bits to the left
    )
  )
  .iterator                     //create an iterator
  .grouped(                     //group them in groups of size...
    math.sqrt(s.size)toInt        //sqrt of the size of the input, rounded up
  )withPadding 32               //pad with spaces to make a square

```

.

```
a=>
  " +$"              //take this string
  .r                 //parse it as a regex
  .replaceAllIn(     //replace every occurence of the regex in...
    a.flatten          //a flattened
    .map(h=>           //each element mapped
      (h&0xFF)toChar)    //to the character of the lower 8 bits
    mkString,          //joined to a string
    ""               //with an empty string
  )

```
> 2 votes

# Answer
# Perl, (103+1) + (36+2) = 142 bytes

Text to image encoder (run with `-p` for a 1-byte penalty; `-p0` (for an additional byte of penalties) is necessary if you want to handle newlines in the input string):

```
$_.=$"while($a=(length)**.5)=~/\./;$_=unpack"H*";s/../sprintf"#%04x$&,",rand+4**8/eg;s/(.*?\K,){$a}/
/g

```

Image to text decoder (run with `-p0` for a 2-byte penalty):

```
$\.=chr hex for/..\W/g;$\=~s/ *$//}{

```

This uses the `#abcdef` text-based image format, and encodes in the blue channel. Here's an example of a possible output given `Programming Puzzles and Code Golf` as the input:

```
#b4d250,#bccb72,#43f06f,#4d6767,#74ba72,#269461
#e4f26d,#f63d6d,#701c69,#bbf56e,#6ef967,#d78d20
#4e0d50,#9b2775,#afd37a,#12a47a,#63e46c,#0e9565
#4cad73,#e43420,#6da761,#5a306e,#8fba64,#58f720
#d52443,#b4446f,#fbaf64,#4a4365,#1a5020,#f3ea47
#354c6f,#52cb6c,#11a766,#4c380a,#553820,#b31120

```

Explanation of the encoder:

```
$_.=$"             # append a space ($") to the input ($_)
  while            # as long as the following condition holds:
(($a=length)**.5)  # the square root of the input length (save this in $a)
=~/\./;            # has no decimal points in its string represenation
$_=unpack"H*";     # convert the input from base-256 to hexadecimal
s/../              # replace two characters of the input
  sprintf          # with a string formed from the template
  "#%04x$&,",      # four hex digits, the two matched characters, and a comma
  rand+4**8        # those hex digits are a random number from 0 to 4**8 (= 65536)
/eg;               # and do this for every non-overlapping match
s/(.*?             # find the minimum number of characters needed to match
   \K,)            # replacing the part of the match after the last matched comma
  {$a}/            # a string containing $a commas
/gx                # with a newline, for every non-overlapping match

```

I was really happy this use of `\K` worked; it specifies where to replace, and placing it inside a loop, it seems that the occurrence on the last loop iteration is what counts. So `s/(.*?\K,){$a}/\n/g` will match a minimum-length string of the form *anything* comma *anything* comma … *anything* comma, that has `$a` commas, but the actual replaced part of the match will simply be the last comma. This has the effect of replacing every `$a`th comma with a newline, giving us the square shape for the image.

The big advantage of Perl for this challenge (other than the built-in character string-to-hexadecimal converter, which was incredibly convenient) is that it has a very short decoder (so short, in fact, that although Perl has a builtin for converting hexadecimal to a string, it was shorter not to use it). Here's how it works:

```
$\.=chr      # append to $\ the character code
  hex        # of the hexadecimal-string-to-number-translation
for/..\W/g;  # of each two characters that appear before a
             # non-alphanumeric character (not counting overlapping matches)
$\=~s/ *$//  # delete all spaces at the end of $\
}{           # in this context, this means "implicitly print $\,
             # prevent any other implicit printing"

```

The only instances of two characters immediately before a non-alphanumeric character are the blue channels (which we want to unpack), which appear just before commas and newlines; and the two characters that appear before each `#` other than the first. We don't want the latter category of matches, but they inevitably overlap the former category, and thus will be excluded by the overlapping matches check.
> 2 votes

# Answer
# MySQL, 438 + 237 = 675 bytes

There is a trailing new line at the end of the output, but it does not show up after being decrypted. The hex function (integer overload) would chop off leading 0's, so I had to pad it with a string 0. I could save some bytes if I could declare both functions between the delimiters.

**Encrypt**

```
delimiter //create function a(i text)returns text begin declare r int;declare q,p text;while mod(length(i),sqrt(length(i)))<>0 do set i:=concat(i,' ');end while;set r:=1;set q:="";while r<=length(i) do set p:=",";if mod(r,sqrt(length(i)))=0 then set p:="\r\n";end if;set q:=concat(q,'#',right(concat(0,hex(floor(rand()*256))),2),right(concat(0,hex(floor(rand()*256))),2),hex(mid(i,r,1)),p);set r:=r+1;end while;return q;end//
delimiter ;

```

**Decrypt**

```
delimiter //create function b(i text)returns text begin declare x int;declare y text;set x:=0;set y:="";while instr(i,'#')>0 do set i:=substr(i,instr(i,'#')+5);set y:=concat(y,unhex(left(i,2)));end while;return trim(y);end//
delimiter ;

```

Usage:

```
select a('test')
select b('#7D1874,#FFB465')
select b(a('test'))

```
> 1 votes

# Answer
# C#, 312 + 142 = 454 bytes

Encoding:

```
using System;I=>{var r=new Random();int i=I.Length;int N=(int)Math.Floor(Math.Sqrt(i))+1,S=N*N;while(i++<S){I+=' ';}var R="";for(i=0;i<S;){R+=i%N<1&i>0?"\n":i<1?"":" ";R+="#"+r.Next(256).ToString("X").PadLeft(2,'0')+r.Next(256).ToString("X").PadLeft(2,'0')+((int)I[i++]).ToString("X").PadLeft(2,'0');}return R;};

```

Decoding:

```
using System;I=>{var s=I.Replace('\n',' ').Split(' ');var R="";foreach(var t in s)R+=(char)System.Convert.ToInt32(t[5]+""+t[6],16);return R.TrimEnd(' ');};

```

Full program:

```
using System;
class Steganographic
{
    static void Main()
    {
        Func<string, string> E = null;
        Func<string, string> D = null;

        E=I=>
        {
            var r=new Random();
            int i=I.Length;
            int N=(int)Math.Floor(Math.Sqrt(i))+1,S=N*N;
            while(i++<S){I+=' ';}
            var R="";
            for(i=0;i<S;)
            {
                R+=i%N<1&i>0?"\n":i<1?"":" ";
                R+="#"+r.Next(256).ToString("X").PadLeft(2,'0')+r.Next(256).ToString("X").PadLeft(2,'0')+((int)I[i++]).ToString("X").PadLeft(2,'0');
            }
            return R;
        };

        D=I=>
        {
            var s=I.Replace('\n',' ').Split(' ');
            var R="";
            foreach(var t in s)
                R+=(char)Convert.ToInt32(t[5]+""+t[6],16);
            return R.TrimEnd(' ');
        };

        string encoded = E("Programming Puzzles and Code Golf");
        Console.WriteLine(encoded);
        Console.WriteLine(D(encoded));

        encoded = E("Hello, World!");
        Console.WriteLine(encoded);
        Console.WriteLine(D(encoded));

        Console.Read(); // For Visual Studio
    }
}

```
> 1 votes

# Answer
# Mathematica, 111 + 65 = 176 bytes

**Encoder**

```
Join[255~RandomInteger~{n=⌈Sqrt@Length@#⌉,n,2},ArrayReshape[#,{n,n,1},32],3]~Image~"Byte"&@*ToCharacterCode

```

**Decoder**

```
StringTrim[""<>FromCharacterCode@ImageData[#,"Byte"][[;;,;;,3]]]&

```
> 1 votes

# Answer
# Processing, ~~220~~ ~~209~~ 194 + ~~171~~ ~~167~~ 151 = ~~391~~ ~~380~~ ~~376~~ ~~361~~ 345 bytes

### Update:

Removed useless `noStroke()` and made both for-loops one-statementers.

Removed useless `image(p,0,0);`, gave the decryptor the filename as the parameter

### Encryption Algorithm

```
void g(String h){int s=ceil(sqrt(h.length()));for(int y=0,x;y<s;y++)for(x=0;x<s;rect(x,y,1,1),x++)stroke(h.length()>y*s+x?h.charAt(y*s+x):32,random(255),random(255));get(0,0,s,s).save("t.png");}

```

Calling the function: `g("Programming Puzzles and Code Golf");`

This is a function that takes in a String, and creates the output, before saving it as `t.png`. It uses the `red` value to store the hidden text.

### Decryption Algorithm

```
void u(String f){PImage p=loadImage(f);f="";for(int j=0,i;j<p.height;j++)for(i=0;i<p.width;i++)f+=(char)red(p.get(i,j));print(f.replaceAll(" +$",""));}

```

Call function by: `u(file_name);`

This is also a function that searches for the image specified by the parameter, and then outputs the hidden string (since it is shorter than returning a string).

### Expanded code

*(Encryption Algorithm)*

```
void g(String h) {
  int s=ceil(sqrt(h.length()));
  for(int y=0,x;y<s;y++)
    for(x=0;x<s;rect(x,y,1,1),x++)
      stroke(h.length()>y*s+x?h.charAt(y*s+x):32,random(255),random(255));
  get(0,0,s,s).save("t.png");
}

```

The string is passed when the function is called. The first line of the function calculates the side length of the square by taking the `ceil` of its square root. Then we enter a for-loop, where we set the `stroke` (the colour of the edge) to have the ASCII value of the character as red, and random values for blue and green. After we do this, we create a `rect` (rectangle) with width = `1` and height = `1`, ie a pixel (for some weird reason, I can't use `point` properly). In the last line, the resulting image is then saved as `t.png`.

*(Decryption Algorithm)*

```
void u(String f) {
  PImage p=loadImage(f);
  f="";
  for(int j=0,i;j<p.height;j++)
    for(i=0;i<p.width;i++)
      f+=(char)red(p.get(i,j));
  print(f.replaceAll(" +$",""));
}

```

This function has the name of the file as the parameter (as a string). Then the image in the file is stored in a variable to be used later. After we are done with that, we set the string to `""` instead of creating a new string just to hold the hidden string. Then we iterate through the image via two nested for-loops, and we add on to the string the character value of the red value of the pixel. Finally, we print the resulting string after removing leading spaces from it (using a regex). The reason we print the hidden text instead of returning it is because this way it is shorter and we save bytes.

---

Encrypted challenge raw text:
> 1 votes

# Answer
# Jelly, 40 + 20 = 60 bytes in Jelly's codepage

Encoder (text → image):

```
”#;;ØHX¤¥4¡
»⁶x⁹²¤¤Ob⁴‘ịØHÇ€sj€”,Y
L½Ċç@

```

Try it online!

Decoder (image → text):

```
ḣ2ØHiÐ€’ḅ⁴Ọ
ṣ”#Ç€œr⁶

```

Try it online!

An example output the program could produce (it stores information in the red channel):

```
#504219,#720200,#6F38F1,#67055F,#7228C7,#61AC95
#6DD797,#6D20CB,#6962FA,#6E69B1,#67C41C,#209436
#50CB19,#75C9FC,#7A1B06,#7A695B,#6C5D5B,#6539A6
#735925,#20C80F,#612C38,#6EBF9E,#64C79E,#200915
#4337C5,#6F4704,#64FB5F,#65B2D1,#20E075,#47BC7C
#6F0C16,#6CD8EF,#66060B,#203C6C,#20D6E9,#20C0D7

```

In these larger challenges, Jelly's terseness starts to drop off a bit, needing several "structural" characters to resolve parsing ambiguities, but it's nonetheless still very terse. Here's how the encoder works:

```
Subroutine 1: convert digits to randomly padded hex string
”#;;ØHX¤¥4¡
”#;                     prepend #
    ØHX                 random hexadecimal digit
       ¤                parse ØH and X as a unit
   ;                    append
        ¥               parse ; and ØHX¤ as a unit
         4¡             repeat four times

Subroutine 2: convert string λ to square with size ρ
»⁶x⁹²¤¤Ob⁴‘ịØHÇ€sj€”,Y
 ⁶                      space
   ⁹²                   ρ squared
     ¤                  parse ⁹² as a unit
  x                     repeat string (i.e. ρ² spaces)
      ¤                 parse ⁶x⁹²¤ as a unit
»                       take maximum
Because space has the lowest value of any printable ASCII character,
this has the effect of padding λ to length ρ² with spaces.
       O                take codepoints of string
        b⁴              convert to base 16
           ịØH          use as indexes into a list of hexadecimal digits
          ‘             0-indexed (Jelly uses 1-indexing by default)
              Ç€        run subroutine 1 on each element
                s       split into groups of size ρ
                  €     inside each group
                 j ”,   join on commas
                     Y  join on newlines

Main program: basically just calculates ρ and lets subroutine 2 do the work
L½Ċç@
L                       length of input
 ½                      square rooted
  Ċ                     rounded up to the next highest integer
   ç@                   call subroutine 2 with the original input and the above

```

And here's how the decoder works:

```
Subroutine: convert hexadecimal color string (without #) to character
ḣ2ØHiÐ€’ḅ⁴Ọ
ḣ2                      take first two characters
  ØHi                   find indexes in a string of hexadecimal digits
     Ð€                 for each of those characters
       ’                0-indexed (Jelly uses 1-indexing by default)
        ḅ⁴              convert from base 16
          Ọ             convert integer to character

Main program:
ṣ”#Ç€œr⁶
ṣ”#                     split on # signs
   Ç€                   run the subroutine for each element
     œr⁶                remove spaces from the right

```
> 1 votes

---
Tags: code-golf, graphical-output
---


title: Aircraft Marshalling School

text:
# Question
Title: Aircraft Marshalling School
Given a string representing a series of aircraft marshalling hand signals, write a function or program to calculate the final position of an aircraft following these signals.

***N.B.:*** *Co-ordinates in this challenge are represented as a pair of Cartesian co-ordinates, plus a compass direction heading: `(x, y, h)` where `x` is the x-coordinate, `y` is the y-coordinate, and `h` is one of `N`, `E`, `S`, or `W`.*

You start with an aircraft at `(0, 0, N)` on an imaginary grid, with engines off. Your input is a string containing comma-delimeted pairs of characters, where each pair represents one marshalling signal. You must follow each marshalling signal in turn, and output the co-ordinates in `(x, y, h)` form of the aircraft's final position.

If a signal requires your aircraft to move, assume it moves *one* unit in the required direction for each signal of that type that it receives. If a signal requires your aircraft to turn, assume it turns 90 degrees in the required direction for each signal of that type that it receives.

An aircraft cannot move if its engines are off. If your aircraft's engines are off and you receive a movement/turn signal, do not apply the movement/turn.

## Signals

Each marshalling signal is represented by one pair of characters. The first of the pair represents the position of the marshaller's left arm, *from the aircraft's point of view*, and the second the right arm from the same POV. This handy chart of signals may help.

```
o/  —  START ENGINES (no movement, no turn)
-/  —  CUT ENGINES   (no movement, no turn)
-~  —  TURN LEFT     (no movement, left turn)
~-  —  TURN RIGHT    (no movement, right turn)
~~  —  COME FORWARD  (forward movement, no turn)
::  —  MOVE BACK     (backward movement, no turn)
/\  —  NORMAL STOP   (no movement, no turn)

```

This is not the complete list of marshalling signals, but it's all you're required to support.

## Input

Input is a comma-delimeted string containing pairs of characters. This string will always be valid - you do not have to validate the input.

## Output

Output is a set of co-ordinates as described above. You can return this in any convenient format - if your language supports multiple return values, you may use that; alternatively, you can use a string (the brackets surrounding the co-ordinates are non-compulsory), array, tuple, list, or whatever else you find convenient. The only rule is that it must contain `x`, `y`, and `h` values, in that order.

## Test Cases

```
Input  —  Output
o/,~~,~~,~-,::  —  (-1, 2, E)
::,~-,o/,/\,~~,-~,~~,~~,~~  —  (-3, 1, W)
o/,::,-/,~~,o/,~-,~~,~~,~-  —  (2, -1, S)
o/,~-,~-,::,::,~-,~~,-~  —  (-1, 2, S)
~-,~-,o/,::,::,-/,~~,-~  —  (0, -2, N)

```

# Answer
> 2 votes
# Java 8, 505 bytes

Golfed (with help from @masterX244 for shaving a big chunk off)

```
class f{static boolean T(String u,String v){return u.equals(v);}public static void main(String[]a){java.util.Scanner q=new java.util.Scanner(System.in);String s=q.nextLine();int x=0;int y=0;int d=0;int[][]v={{0,1},{-1,0},{0,-1},{1,0}};int b=1;for(String r:s.split(",")){if(T(r,"o/")||T(r,"-/"))b=~1;if(b<0){if(T(r,"~-"))d=(d+3)%4;if(T(r,"-~"))d=(d+1)%4;if(T(r,"~~")){x+=v[d][0];y+=v[d][1];}if(T(r,"::")){x-=v[d][0];y-=v[d][1];}}}System.out.println("("+x+","+y+","+"NWSE".charAt(d)+")");}}

```

More readable

```
class f {
    static boolean T(String u,String v){return u.equals(v);}
    public static void main(String[] a) {
        java.util.Scanner q=new java.util.Scanner(System.in);
        String s=q.nextLine();
        int x=0;
        int y=0;
        int d=0;
        int[][] val = {
                {0,1},  // N
                {-1,0}, // W
                {0,-1}, // S
                {1,0}   // E
        };
        int b=1;
        for (String r: s.split(",")) {
            // toggle b if either start or stop engine
            if(T(r,"o/") || T(r,"-/"))
                b=~1;
            if(b<0){
                // right
                if(T(r,"~-")) d=(d+3)%4;
                // left
                if(T(r,"-~")) d=(d+1)%4;
                // come forward
                if(T(r,"~~")) {
                    x+=val[d][0];
                    y+=val[d][1];
                }
                // move back
                if(T(r,"::")) {
                    x-=val[d][0];
                    y-=val[d][1];
                }
            }
        }
        System.out.print("("+x+","+y+","+"NWSE".charAt(d)+")");
    }
}

```

# Answer
> 1 votes
# Befunge, ~~201~~ 185 bytes

```
p10p2p3pv
~/3-*95~<v:+-"/"
  v!:-*53_v
 #_7-:v v0-1
vv!:-3_100>p
 _69*-:v NESW v+g01g
v v-*93_g10g\->4+4%10p
v<_100g >*:10g:1\-\2%!**03g+03p10g:2\-\2%**02g+02p
>>~65*`#v_2g.3g.10g9+5g,@

```

Try it online!

Befunge doesn't have a string type as such, so to make the signals easier to compare, each character pair is converted into an integer using the formula `(c1 - 45)/3 + c2 - 47`. This can mean we'll get false matches on invalid input, but that's doesn't matter if the input is guaranteed to be valid.

The rest of the code is based around the manipulation of four "variables": the *engine* state (1 or 0), the *heading* (0 to 3 for NESW), and the *x* and *y* positions. The calculations for each signal are then as follows:

**Start engine:** `engine = 1`
**Cut engine:** `engine = 0`
**Turn left:** `heading = (heading - engine + 4) % 4`
**Turn right:** `heading = (heading + engine) % 4`
**Movement:** (where *dir* is 1 for forward and -1 for backwards)
`y += dir*engine*(1-heading)*!(heading%2)`
`x += dir*engine*(2-heading)*(heading%2)`

Once we reach the end of the input sequence, it's then just a matter of outputting the *x*, *y*, and *heading* (converted to a char with a simple table lookup).

# Answer
> 1 votes
# Python 2.7.12, 295 bytes

```
from operator import*
l=[0,0]
m=[['N',[0,1]],['E',[1,0]],['S',[0,-1]],['W',[-1,0]]]
n=0
x=raw_input()
for c in x.split(','):
 if'o/'==c:n=1
 if'-/'==c:n=0
 if n:
    if'-~'==c:m=m[-1:]+m[:-1]
    if'~-'==c:m=m[1:]+m[:1]
    if'~~'==c:l=map(add,l,m[0][1])
    if'::'==c:l=map(sub,l,m[0][1])
print l+[m[0][0]]

```

The first level of indentation after `for` uses a single `\s`. The indentation of the second level uses a single `\t`. (the wysiwyg replaces `\t` with multiple spaces so please keep this in mind when testing for size)

# Answer
> 1 votes
# Python 2, 142 bytes

```
s=raw_input()
e=p=0;d=1
while s:exec'd-=e d+=e p+=1j**d*e e=0 0 e=1 p-=1j**d*e 0'.split()[ord(s[0])+ord(s[1])*2&7];s=s[3:]
print p,'ESWN'[d%4]

```

Example:

```
% python2.7 ams.py <<<'o/,~~,~~,~-,::'
(-1+2j) E

```

This prints complex numbers, which should be okay, I think? The `x`, `y`, `h` order is still there, and the `'j'` doesn’t cause any confusion. Tell me if I should change it.

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


title: Simplify binary

text:
# Question
Title: Simplify binary
# Challenge

Given a binary number as input through any means, "simplify" the number using a full program or a function.

# Input

```
[binary]

```
* `binary` is a number in binary that is over 0.

# Output

Take the input, convert it to base 10 without using a builtin, then if that number contains only 1s and 0s, convert it into a base 10 number as if it were another binary number. Repeat the process until the number cannot be read in binary and output that number.

# Other information

* If the input is 1, simply output `1`. Your program should not go on infinitely simplifying 1.
* This is code golf, so shortest answer in bytes by Tuesday (November 17th) wins.
* If anything is confusing, leave a comment specifying what I need to clear up and I will edit it accordingly.
* Builtins for base conversion are not allowed.

# Examples

```
     Input | Output

         1 | 1
      1010 | 2
      1011 | 3
   1100100 | 4
   1100101 | 5
1111110011 | 3

```

# Answer
> 14 votes
# Pyth, ~~20~~ 16 bytes

```
u?-GTG`u+yNsTG0z

```

*4 bytes thanks to Jakube*

Half of the code (`u+yNsTG0`) is simply the base conversion code.

Test Suite

```
u?-GTG`u+yNsTG0z
                    z = input() (The string of 1s and 0s)
                    T = 10
u              z    Apply until the value stops changing, starting with z
                    G is the current value, a string of 0s and 1s.
 ?-GT               If G - T, e.g., G with the digits 1 and 0 removed is not empty,
     G              Return G, to end the iteration.
       u     G0     Else, reduce over G with initial value 0.
         yN         Double the running total
        +  sT       and add the next digit, cast to an int.
      `             Convert to string.

```

The input `1` is handled by the fact that `u` notices the value has stopped changing.

# Answer
> 8 votes
# CJam, ~~24~~ 23 bytes

```
q{:~{1$++}*s__,(As*-!}g

```

Try it online in the CJam interpreter.

### How it works

```
q                        Read all input.
 {                   }g  Do:
  :~                       Evaluate each character. Maps '0' -> 0 and '1' -> 1.
    {    }*                Fold; for each integer but the first:
     1$                      Copy the second-topmost integer.
       ++                    Add all three integers on the stack.
           s__             Cast to string and push two copies.
              ,(           Calculate string length and subtract 1.
                As         Push the string "10".
                  *        Repeat the string length-1 times.
                   -       Remove its elements from the string representation
                           of the integer.
                    !      Apply logical NOT.
                         If `!' pushed 1, repeat the loop.

```

# Answer
> 7 votes
## Pip, ~~28~~ 27 bytes

```
Ta=1|aRMta:$+(^a)*2**RV,#aa

```

Takes input as a command-line argument. We want to loop until `a=1` or `a` contains some character(s) besides 0's and 1's. This latter condition is tested by `RM`'ing all characters in `t` = `10` from `a`. If there's anything left, the condition is truthy.

Inside the loop, the conversion works as follows:

```
a:$+(^a)*2**RV,#a

              ,#a  range(len(a))
            RV     reversed
         2**       2 to the power of each element
    (^a)*          multiplied item-wise with each digit in split(a)
  $+               Sum
a:                 and assign back to a

```

Putting `a` at the end auto-prints it.

A recursive solution in 28 bytes:

```
a<2|aRMt?a(f$+(^a)*2**RV,#a)

```

# Answer
> 6 votes
## Python 2, 52

```
f=lambda n:n>1<'2'>max(`n`)and f(n%10+2*f(n/10))or n

```

It's easier to think of this as two recursive functions:

```
g=lambda n:n and n%10+2*g(n/10)
f=lambda n:n>1<'2'>max(`n`)and f(g(n))or n

```

The function `g` converts a decimal value to binary, and the function `f` applies `g` repeatedly is long as its argument is made of digits 0 and 1 (`'2'>max(`n`)`) and is not `1`. The golfed code collapses them into a single function by inserting the definition of `g(n)` for `f(n)`, replacing the recursive call to `g` with `f`. The base case of `n=0` of `g` is automatically handled by the check `n>1`.

# Answer
> 4 votes
# Prolog, ~~220~~ 212 bytes

```
:-use_module(library(clpfd)).
x(B,N):-reverse(B,C),foldl(y,C,0-0,_-N).
y(B,J-M,I-N):-B in 0..1,N#=M+B*2^J,I#=J+1.
b(N,I):-N>47,N<50,I is(N-48).
p(N):-N>1,number_codes(N,L),maplist(b,L,Y),x(Y,B),p(B);write(N).

```

**Explanation**
**p** is the main function and performs the following steps (with help from b,x,y):

* checks if current number is bigger than 1
* converts integer to list of ascii representations of digits
* checks that all numbers are 0 or 1
* converts ascii list to binary integer list
* converts binary integer list to decimal number
* recurses
* prints when a predicate fails.

**Edit:** Saved 8 bytes by unifying the p-clauses with OR.

# Answer
> 3 votes
# Mathematica ~~107~~ 106

With a byte saved by DLosc.

```
j@d_:=(p=0;v=IntegerDigits@d;
Which[d<2,1,Complement[v,{0,1}]=={},j@Fold[#+#2 2^p++&,0,Reverse@v],1<2,d])

```

Break the input into its digits. If the input is 1, output 1.

If the input is a number consisting of 0's and 1's, convert that to decimal and run it through again.

Otherwise, return the input.

---

```
j[1]

```

> 1

---

```
j[11010001]

```

> 209

---

```
j[1111110001]

```

> 1009

---

```
j[1111110011]

```

> 3

The first step yields 1011 which in turn yields 3.

---

Here we test starting with 1011.

```
j[1011]

```

> 3

# Answer
> 3 votes
# Javascript, 132, 123 bytes

Well, it's not the best answer, but..

FYI, if an invalid input is given, it displays the same to the user.

```
function c(x){while(x!=0&&!/[2-9]/.test(x)){for(i=r=0;x;i++)r+=x%10*Math.pow(2,i),x=parseInt(x/10);x=r}alert(x)}c(prompt())
```

# Answer
> 2 votes
# Mathematica, ~~62~~ ~~59~~ ~~55~~ 48 bytes

Saved 7 bytes thanks to Martin Büttner.

```
#//.a_/;Max[b=IntegerDigits@a]<2:>Fold[#+##&,b]&

```

# Answer
> 2 votes
# JavaScript ES6, 52

As a function. The function argument must be either a string of binary digits or a number whose decimal representation contains only 1 and 0.

Test running the snippet below in an EcmaScript 6 compliant browser - implementing arrow functions, template strings and spread operator (I use Firefox)

```
f=s=>s<2|[...s+''].some(c=>(n+=+c+n,c>1),n=0)?s:f(n)

// To test
console.log=(...x)=>O.innerHTML+=x+'\n';

// Basic test cases
;[[1,1],[1010,2],[1011,3],[1100100,4],[1100101,5],[1111110011,3]]
.forEach(t=>console.log(t[0]+' -> '+f(t[0])+' expected '+t[1]))

function longtest() {
  var o=[],i;
  for (i=1;i<1e6;i++)
    b=i.toString(2),v=f(b),v!=i?o.push(b+' '+v):0;
  O.innerHTML=o.join`\n`
}
```

```
Click to run the long test <button onclick="longtest()">go</button>
<pre id=O></pre>
```

# Answer
> 1 votes
# , 37 chars / 54 bytes

```
↺;ï>1⅋(⬯+ï)ĉ/^[01]+$⌿);)ï=+('ᶀ'+ï);ôï

```

`Try it here (Firefox only).`

Not sure if the `+` operator counts as a built-in for binary conversion...

# Answer
> 1 votes
# Javascript (ES7) 87 80 78 77 74 bytes

Snippet demo for supporting browsers (currently only Firefox nightly supports the exponential operator)

```
f=x=>[...x].reverse(i=y=j=0).map(z=>(j|=z,y+=z*2**i++))&&j<2&y>1?f(y+[]):x
```

```
<input type="text" id="x" value="1111110011"><button onclick="o.innerHTML=f(x.value)">Run</button><div id="o"></div>
```

```
f=x=>
[...x].reverse(i=y=j=0) // reverse string as array, initialize vars
.map(z=>( // iterate over the all chatacters
    j|=z, // keep track of whether a digit higher than 1 is encountered
    y+=z*2**i++ // build decimal result from binary
))&&
j<2&y>1? // if we encountered only 1's and 0's and result > 1
    f(y+[]) // then call recursively and cast to a string
    :x // else return x

```

# Javascript (ES6) 81 bytes

Snippet demo for supporting browsers

```
f=x=>[...x].reverse(i=y=j=0).map(z=>y+=z*Math.pow(2,i++,j|=z))&&j<2&y>1?f(y+[]):x
```

```
<input type="text" id="x" value="1111110011"><button onclick="o.innerHTML=f(x.value)">Run</button><div id="o"></div>
```

# Answer
> 1 votes
## Perl 6, 67 bytes

```
get,{$_=0;for $^a.comb {$_+<=1;$_+=$^b};$_}...1|/<-[01]>/;say $_//1

```

# Answer
> 1 votes
# PHP, 210 204 bytes

It's my first time posting here, so hope you guys will like it ! Even if it's obviously not the best way to write it, I'm still glad to show it off here !

## The Code

```
<?function j($a){$c=0;if($a==1){return 1;}else{if(preg_match("#^[01]+$#",$a)){$b=strlen($a);$a=str_split($a);foreach($a as$d){$c+=($d==0?0:2**($b-1));$b--;}return j($c);}else{return$a;}}}echo j($_GET[0]);

```

I've made a recursive function "j" that will first check if the input is equal to 1. If so, the function returns 1 as expected, else it'll split the number in an array to calculate the decimal value, but only if the number is a binary one. If it's not, it'll return the number as is.

## Ungolfed code

```
<?
function j($a) {
  $c = 0;
  if ($a == 1) {
    return 1;
  }
  else {
    if (preg_match("#^[01]+$#", $a) {
      $b = strlen($a);
      $a = str_split($a);
      foreach ($a as $d) {
        $c += ($d == 0 ? 0 : 2 ** ($b - 1));
        $b--;
      }
      return j($c);
    }
    else {
      return $a;
    }
  }
}
echo j($_GET[0]);

```

I've used a "foreach" statement instead of my initial "for" one, allowing me a gain of 6 bytes but I'm pretty sure there's a lot more to do.

# Answer
> 1 votes
# PHP, ~~114~~ 112 bytes

also works for `0`. Run with `-r`.

```
for($n=$argv[1];count_chars($s="$n",3)<2&$s>1;)for($i=$n=0;""<$c=$s[$i++];)$n+=$n+$c;echo$s;

```

`count_chars($s,3)` returns a string containing all characters from the string (like `array_unique` does for arrays). For binary numbers, this will be `0`, `1` or `01`. For other numbers, this will contain a digit larger than `1`, so `<2`will return true only for binary numbers.

`&$s>1` is needed for the special case `1`.

The rest is straight forward: Loop through the bits with shifting the value and adding the current bit, finally copy the number (cast to string) to $s for the outer loop test.

# Answer
> 0 votes
## CoffeeScript, ~~92~~ 89 bytes

```
f=(x)->x>1&/^[01]+$/.test(x)&&f(''+x.split('').reverse().reduce ((p,v,i)->p+v*2**i),0)||x

```

## JavaScript (ES6), ~~105~~ ~~101~~ 90 bytes

```
f=y=>y>1&/^[01]+$/.test(y)?f(''+[...y].reverse().reduce(((p,v,i)=>p+v*Math.pow(2,i)),0)):y

```

## Demo

Only works in ES6-compliant browsers such as Firefox and Microsoft Edge

```
f=y=>y>1&/^[01]+$/.test(y)?f(''+[...y].reverse().reduce(((p,v,i)=>p+v*Math.pow(2,i)),0)):y

// Snippet stuff
$(`form`).submit((e) => {
  document.getElementById(`y`).textContent = f(document.getElementById(`x`).value);
  e.preventDefault()
})
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <label>Input:
    <input pattern=^[01]+$ required id=x>
  </label>
  <button type=submit>Go</button>
  <p>Output:
    <output id=y></output>
  </p>
</form>
```

# Answer
> 0 votes
# Scala, 128 bytes

```
def b(s:String):String=if(s.matches("[10]{2,}"))b(""+s.reverse.zipWithIndex.collect{case('1',i)=>Math.pow(2,i)}.sum.toInt)else s

```

# Answer
> 0 votes
## Matlab (115)

```
@(a)num2str(sum((fliplr(a)-48).*arrayfun(@(x)2^x,0:nnz(a)-1)));a=ans(input('','s'));while(find(a<50))a=ans(a);end,a

```

---

* The anonymous function is number type conversion (`bin2dec`)

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


title: Official Dyalog APL 2016 Year Game

text:
# Question
Title: Official Dyalog APL 2016 Year Game
If you think this could be fun, but too much work, consider participating in this much smaller challenge.

---

A bit of fun (and possibly frustration!) for 2016... Dyalog's "puzzle of the year". Enjoy!

# The Objective

Find Dyalog APL (download) expressions (other languages are allowed, see *Eligibility* below) involving exactly the digits 2 0 1 6 in that order to equal the numbers 0 to 100. For example:

`20=16`
`×2016`
`2⌊016`
`2+0+1*6`
...

The aim is to use as few characters as possible in each expression (the minimum number of characters for an expression is 5 – the four digits 2 0 1 6 and a single primitive function/operator).

# The Rules

* Each expression must contain the digits 2 0 1 6 (in that order) and no other digits. Pre-set constants and variables are also not allowed.
* In addition to the four digits 2 0 1 6, only built-in symbols and names, parentheses/braces, spaces, high minus signs and decimal points can be used. The resultant expressions must be deterministic (that is, give the same result on repeated evaluations). For non-APLs, functions/operators with a name are also allowed; same rules as here.
* Assume all default settings for your language. For Dyalog APL, this means `⎕ML` and `⎕IO` are both 1, and `⎕PP` is 10.
* Each entry comprising correct expressions for all the numbers from 0 to 100 inclusive will be rated according to the number of characters used by those expressions excluding redundant spaces (minimum 505 for all 101 expressions).

# Eligibility

Anyone can enter. You may answer in any language, but only APL answers will be considered for accepting. If you use another language than APL, you may use snippets, programs, functions, etc. as alternatives to expressions, and you may print, leave the number in an accessible memory location, or otherwise return the result, as long as your code directly evaluates to the desired number as any standard numeric data type for your language.

# Closing Date

30 November 2016.

# Prizes

* Have your answer accepted
* Be immortalised in Dyalog's 2016 Hall of Fame!

# Submitting Your Entry

After 30 November 2016, I will accept the shortest answer, and submit your answer, in *your* name, to Dyalog's 2016 Hall of Fame.

# FAQ

* Is `J` (e.g. 37=`⌈⍟!20J16`) allowed?
* No: *In addition to the four digits 2 0 1 6, only only built-in symbols and names, parentheses/braces, spaces, high minus signs and decimal points can be used.*
* Is output as a string acceptable?
* No: *equal the numbers 0 to 100.*
* Physical digits, or data digits?
* Data digits, as per OP: same rules as here, where one of the examples contain `LOG10(`.
* Is assigning variables then using them as part of the expression (e.g. 56=`a+16+a←20`) allowed?
* Yes, but you may not use an assignment from one expression in another one.

---

I have explicit written permission to post this challenge here from the original author of this challenge. Feel free to verify by following the provided link and contacting the author. I gave the original competition author the link to this page within the minute I posted it, so they can check if I submit someone's answer as my own.

# Answer
> 8 votes
# Jelly, 686 bytes

```
20=16
20>16
2+0%16
201%6
20%16
20%16‘
201a6
20>1+6
20%16Ḥ
2016DS
20Ho16
2016BL
20:1.6
20_1_6
20×1_6
20+1_6
20&16
20:+16
2+0+16
20+1^6
20|16
20|16‘
20|16‘‘
20%16!’
20%16!
20²:16
20H+16
20+1+6
20×1_6Ḥ
20×1_6Ḥ‘
20+1_6Ḥ
2016&½’
2016&½
201:6
201:6‘
20Cạ16
20+16
20+16‘
20+1^6Ḥ
20|16Ḥ’
20|16Ḥ
20|16Ḥ‘
20|16‘Ḥ
2016½Ḟ’
2016½Ḟ
2016½Ċ
2016½Ċ‘
20Ḥ+1+6
2r0×16S
201a6‘²
20²:16Ḥ
2r016+S
201ÆC+6
20&16ÆN
20H_1×6
20ạC+16
20Ḥ+16
20_1×6H
20_1×6H‘
20_1×6H‘‘
20+1_6ḤḤ
2+0+16ÆN
20:.16H
20+1×6H
2²+0×16
201:6Ḥ’
201:6Ḥ
201Ḥ:6
201Ḥ:6‘
20Cạ16Ḥ’
20Cạ16Ḥ
20+16Ḥ’
20+16Ḥ
20+16Ḥ‘
20+16Ḥ‘‘
20+ÆN_16
20+1^6ḤḤ
20+1^6ḤḤ‘
20×16HH’’
20×16HH’
20×16HH
20×16HH‘
20|16Ḥ‘Ḥ
20|16Ḥ‘Ḥ‘
20|16‘ḤḤ
201½×6Ḟ
201½×6Ċ
20ÆN+16
2016½ḞḤ
20Æn16¡
20r16S
20r16S‘
20r16S‘‘
20Ḥ+1+6Ḥ’
20Ḥ+1+6Ḥ
20ḤḤ+16’
20ḤḤ+16
20ḤḤ+16‘
201a6‘²Ḥ
201’Ho6’
201’Ho6

```

I wrote about 50 of these, then autogenerated the rest by appending  (×2) and `‘’` (±1) as needed. I’ll improve them later!

# Answer
> 9 votes
## Hexagony, 888 bytes

Okay, first some ground rules for Hexagony, in case anyone wants to beat this:

* I'm interpreting "snippet" as a linear piece of code that can be dumped into any sufficiently large program, provided the current and adjacent memory edges are zero.
* The snippet has to be entered from the left and exited from the right. I'd be able to save quite a bunch of bytes without that (e.g. `2|016` for 22), but it seems most in the spirit of the challenge.
* The snippet "produces" a given number, if any memory edge (not necessarily the current one) holds that value after execution.
* The rule forbidding any other numbers in the snippet affects both other digits as well as any letters, since they effectively act as integer literals in Hexagony. (Those would save a ton of bytes.)

So here is the list. I did test most of them but not all (some are trivial modifications of others), so I hope I didn't make any mistakes:

```
2016
20&1}6
2}016
2)}016
20{16'-
201}6(
201}6
201}6)
2}016":
2(0(}16
2(0}16
2(0)}16
)2}016
)2)}016
20}16((
20}16(
20}16
20}16)
20}16))
20(}16
20}16
20)}16
20))}16
20)))}16
20}1)6((
20}1)6(
20}1)6
20}1)6)
201{6)':
2)0(}16
2)0}16
2)0)}16
2{016'*
201{6':
2{016)'*
20}1))6(
20}1))6
20}1))6)
20}1))6))
2))0(}16
2))0}16
2))0)}16
2))0))}16
2))0)))}16
20)){1)'6*
2){016('*
2){016('*)
2){016'*(
2){016'*
2){016'*)
2)))0}16
2){016)'*
2){016)'*)
2{01)6)'*(
2{01)6)'*
2{01)6)'*)
2{01)6)'*))
2{01)6)'*)))
2))))0((}16
2))))0(}16
2))))0}16
2))))0)}16
2)0){1)'6*
2)){016'*(
2)){016'*
2)){016'*)
2)){016'*))
2)){016'*)))
2{01))6('*(
2{01))6('*
2{01))6'*((
2{01))6'*(
2{01))6'*
2{01))6'*)
2{01))6)'*
2){01)6('*
2){01)6'*((
2){01)6'*(
2){01)6'*
2){01)6'*)
20{1)))'6*
2){01)6)'*
2){01)6)'*)
2){01)6)'*))
2){01)6))'*
2){01)6))'*)
2){01)6))'*))
2){01)6)))'*
2{01)))6(('*
2{01)))6('*(
2{01)))6('*
2{01)))6'*(
2{01)))6'*
2{01)))6'*)
2{01)))6)'*
2{01)))6)'*)
2{01)))6))'*
2(01((((}16
2(01(((}16
2(01((}16
2(01(}16

```

I got a bit lazy towards the end, so I'm sure this isn't optimal. Might be interesting (and possible) to brute force these.

# Answer
> 8 votes
# J, ~~1041~~ ... 838 bytes

~~981~~ ~~961~~ ~~952~~ ~~860~~ ~~859~~

I got a little lazy to the end, but it should be more fixed than less. ~~I don't think I'll ever overtake Hexagony, but you never know!~~ beating hexagony! Saved 9 bytes thanks to Zgarb! and so much more to Lynn!

```
20=16
*2016
2[016
2+01[6
20-16
p:2[016
201]6
2+0-1-6
-:20]16
2+01+6
-:20[16
p:20-16
+/2$01]6
<:20-1]6
20-1]6
<:20]16
20]16
p:201]6
2+016
20-1[6
20[16
20+1[6
20++~1[6
+/q:2016
20-(+:1)-6
<:20+1]6
20+1]6
20+1+6
+:20-1]6
p:2+01+6
-2-+:016
<:2*016
2*016
>.201%6
<.201%6
<:20+16
20+16
20+>:16
+~20-1[6
-20-p:16
+:20[16
p:2*01*6
>:p:2*01*6
<:<.%:2016
<.%:2016
>.%:2016
+/q:*:2016
p:20-1]6
>:p:20-1]6
*:2+0-1-6
+:20-1-6
20++:16
<.%:20^%:1+6
20+#i:i:16
*/2,01]$~-:6
<:<.o.2+016
<.o.2+016
>.o.2+016
<:p:20]16
p:20]16
>:p:20]16
2+p:016
<.o.20[16
<:2^01]6
2^01]6
>:2^01]6
<:p:2+016
p:2+016
>:p:2+016
>:>:p:2+016
<:p:20-1[6
p:20-1[6
+/+~20 16
p:20[16
>:p:20[16
>:>:p:20[16
-:+/2+i.016
<:<:p:20+1[6
<:p:20+1[6
20+p:16
20*.16
*:2+01+6
>:*:2+01+6
p:20++~1[6
<.o.20+1+6
>.o.20+1+6
>:>.o.20+1+6
<.o.+:20-1]6
>.o.+:20-1]6
p:+/q:2016
>:p:+/q:2016
<.o.p:2+01+6
>.o.p:2+01+6
(*:-:20)-1+6
>:(*:-:20)-1+6
<:(++:)2*016
(++:)2*016
p:20-(+:1)-6
2**~p:-:01]6
<:*:-:20[16
*:-:20[16

```

# Highlights and Notes

I used prime numbers *a lot* in this. In fact, I used `p:` (the Nth prime) function *37* times in this thing.

```
 *:-:20[16

```

90 was made using a fork. Yay! It's approximate to this:

```
(*+&1)2+01+6

```

Translated as

```
inc =: + &1
mul =: *
nin =: 2 + 1 + 6
NB. since (f g) y = y f (g y):
  (mul inc) nin   = nin mul (inc y)
                  =  9   *    9+1
                  =  90

```

54 uses a shaping ravel!

```
*/2,01]$~-:6

```

Is equivalent to

```
*/ 2 , $~ -:6
*/ 2 , -:6 $ -:6
*/ 2 , 3 $ 3
*/ 2 , 3 , 3 , 3
   2 * 3 * 3 * 3
   54

```

# Answer
> 7 votes
# JavaScript, 1021 bytes

Fixed and saved two bytes thanks to Charlie Wynn and ETHProductions.

```
201&6
-~!2016
2%016
201%6
20%16
2^0^1^6
2*0*1+6
2|0|1|6
2*01+6
2-~01+6
~2+016
~2+016
2^016
20-1-6
2|016
20+1-6
20&16
2-~016
2.0+16
20^1+6
20|16
-~20|16
20*1|6
20|1|6
-2*~01*6
20-1+6
20+1*6
20+1+6
2*016
-~(2*016)
2*-~016
~-(2.0*16)
2.0*16
-~(2.0*16)
2.0*-~16
~-20+16
20+16
-~20+16
-~-~20+16
-~2*~-016
20*-~1.6
~-(-~2*016)
-~2*016
~-~-(~2*~016)
~-(~2*~016)
~2*~016
20<<1|6
20*-~1-~6
~2*~-~016
-~(~2*~-~016)
~-~(~-~2*~-016)
~2*~-~-~016
-~-~2*~-016
20*-~-~1+~6
20*-~-~1-6
20*-~-~1-~-6
-~-~2*016
-~20*-~-~1-6
-~-~(-~-~2*016)
~-(20*~-~(1-6))
~-~2*~016
-~(20*~-~(1-6))
-~-~(20*~-~(1-6))
-~20*~-~(1-6)
~-~2*~-~016
20*-~-~1+~-6
20*-~-~1+6
20*-~-~1-~6
~-~2*~16
-~20*-~-~1+6
-~-~-~2*016
~-(~-~2*~-~16)
~-~2.0*~-~16
-~(~-~2*~-~16)
20*-~-~-~1-6
~-~-~2*~016
~-20*~(1-6)
-~(~-20*~(1-6))
~-~-(20*~(1-6))
~-(20*~(1-6))
20*~(1-6)
-~(20*~(1-6))
~-~-(~20*-~(1-6))
~-(~20*-~(1-6))
~20*-~(1-6)
20*-~-~-~1+~-6
20*-~-~-~1+6
20*-~-~-~1+-~6
20*-~-~-~1+-~-~6
~-(~-~-20*-(1-6))
~-~-20*-(1-6)
-~(~-~-20*-(1-6))
~-~-~-(~-20*-(1-6))
~-~-(~-20*-(1-6))
~-(~-20*-(1-6))
~-20*-(1-6)
-~(~-20*-(1-6))
~-~-~-(20*-(1-6))
~-~-(20*-(1-6))
~-(20*-(1-6))
20*-(1-6)

```

# Answer
> 7 votes
# JavaScript (ES7), 836 bytes

Everything should work in any browser except 81, 88, and 97, which use the new `**` operator.

Mostly everything here was done by hand. I've been working on a brute-forcer to improve anything that can be improved. Currently it has saved 103 bytes on various items.

```
  0: 201&6
  1: 2-01%6
  2: 2%016
  3: 201%6
  4: 20%16
  5: 201%~6
  6: 2%01+6
  7: 2-01+6
  8: 2*01+6
  9: 2+01+6
 10: 2-~01+6
 11: ~2+016
 12: 2^016
 13: 20-1-6
 14: 2|016
 15: 20+1-6
 16: 2+016
 17: 2-~016
 18: 2+0+16
 19: 20-1%6
 20: 20|16
 21: 20+1%6
 22: 20*1|6
 23: 20+1|6
 24: 20+~1+6
 25: 20-1+6
 26: 20*1+6
 27: 20+1+6
 28: 2*016
 29: 20-~1-~6
 30: -2*~016
 31: 20|~-16
 32: 20*1.6
 33: 20*~1^~6
 34: -20*~1-6
 35: 20+~-16
 36: 20+16
 37: 20-~16
 38: 20-~-~16
 39: -~2*~-016
 40: 20<<1%6
 41: -20*~1-~!6
 42: ~2*-016
 43: ~20^-1<<6
 44: ~20*~1^6
 45: ~2*~016
 46: 20<<1|6
 47: -20*~1-~6
 48: ~20*~1+6
 49: ~20*~1-~6
 50: ~2/.01/-6
 51: ~2.0*~16
 52: 20|1<<~-6
 53: -20*~-~1+~6
 54: ~2.0*~-~16
 55: -20*~-~1-~-6
 56: ~-~2*-016
 57: ~20*~-~1-6
 58: -20*~-~1^6
 59: ~(20/~1*6)
 60: -20/~1*6
 61: ~2^0-1<<6
 62: -2^0-1<<6
 63: ~20/~1*6
 64: 2-01<<6
 65: 2+~0|1<<6
 66: 2|01<<6
 67: 2-~0|1<<6
 68: 2*~!0*~16
 69: ~20*~-~1+6
 70: 20/~1*~6
 71: -~(20/~1*~6)
 72: 2+~0/.1*~6
 73: -20<<-~1^~6
 74: -20<<-~1^-6
 75: ~-~-~2*~016
 76: ~-20*(~1+6)
 77: ~-~20/~1*-~6
 78: ~-20<<-~1|6
 79: -20<<-~1^~!6
 80: 20*(~1+6)
 81: ~2*~0**(~1+6)
 82: ~-~-20|1<<6
 83: ~-20|1<<6
 84: 20|1<<6
 85: -~20|1<<6
 86: 20<<-~1|6
 87: 20<<-~1|-~6
 88: .2**~!0|1<<6
 89: ~20*~-~-~1+~-6
 90: ~2*~!0*~-16
 91: ~20*~-~-~1-~6
 92: ~-2/.01+~-~6
 93: ~-2/.01+~6
 94: ~-2/.01-6
 95: ~-20*1*~-6
 96: 2+01<<~-6
 97: ~2+.01**~.6
 98: ~-2/.01^6
 99: ~-2/.01+~.6
100: 20*1*~-6

```

## Brute-forcer

It ain't the prettiest code, but that doesn't seem to matter around these parts.

**WARNING: Do not run** unless you are prepared for your browser/engine to freeze for a few minutes. Nobody likes to calculate 7 nested loops.

```
var a=new Array().fill("000000000000000000000000000"), // An array of non-solutions to start
    time=new Date(),                                   // For timing how long this takes
    o=["","+","-","*","/","%","&","|","^",".","<<"],   // Operators for between numbers
    p=["",".","~.","-","~","~-","-~","~-~","~-~-","~!"];        // Prefixes for each number
for(i=0;i<o.length;i++)
for(j=0;j<o.length;j++)
for(k=0;k<o.length;k++)
for(I=0;I<p.length;I++)
for(J=0;J<p.length;J++)
for(K=0;K<p.length;K++)
for(L=0;L<p.length;L++) {      // 7 nested loops = O(len(o)^3 * len(p)^4)
    z=      p[I]+2
      +o[i]+p[J]+0
      +o[j]+p[K]+1
      +o[k]+p[L]+6;            // Put all the current chars in one string.
    try { v=eval(z) }          // Try setting v to the evaluated value of z.
    catch(e) { v=-1 }          // If an error occurs, set v to -1.
    if( (v === (v|0)) &&       // If v is an integer, and
        v>=0 && v<=100 &&      // v is between 0 and 100, inclusive, and
        z.length<a[v].length ) // z is shorter than the current entry,
        a[v]=z;                // overwrite the current entry.
}

console.log("time: " + ((new Date()-time)/1e3) + "seconds\n"
           + "length: " + (a.join("").length) + "\n"
           + a.map((x,y) => y + ": " + x).join("\n"))

```

# Answer
> 7 votes
# Dyalog APL (This is a joke, please don't submit), 25,957 bytes.

```
2016⊢≢⍬
2016⊢(⊢+≢)≢⍬
2016⊢(⊢+≢)(⊢+≢)≢⍬
...

```

Yeah, this is a joke entry, we need an APL solution, even if it's completely horrible. Works by incrementing `≢⍬` (`0`) `n` times. I don't want to give any secrets away from my actual submission.

Obviously could be golfed much more.

# Answer
> 5 votes
## PowerShell v3+, ~~1575~~ 1499 bytes

```
2*0*16
2*0+1%6
2%016
201%6
20%16
2*0+-1+6
2*0+1*6
2*0+1+6
2+0*1+6
2+01+6
2*(0-1+6)                #10
2*($a=01)*6-$a           ################################## First variable
2*01*6
20-1-6
20*1-6
20+1-6
2*0+16
!!20+16                  ################################## First Boolean not
2+016
2+!0+16
20+!16                   #20
20+1+!6
!2+0x16                  ################################## First use of 0x16
(20+1)-bor6              ################################## First binary or
2+0x16
20-1+6
20*1+6
20+1+6
20+($a=1)+6+$a
20+($a=1)+6+$a+$a
2*-bnot-016              #30 ############################## First binary not
-bnot(-2*016)
2*016
-(-bnot(2*016))
-2*-bnot016
-bnot(-20)+16
20+16
20-(-bnot16)
-(-bnot20)-(-bnot16)
(20-shl1)-!!6            ################################## First binary shl
(20-shl1)+!6             #40
(20-shl1)+!!6
($a=2)*0x16-$a
($a=2)*0x16-$a/$a
2*0x16
-(-bnot2)*(-bnot-016)
(20-shl1)+6
$a=20;$b=1;$a+$a+$b+6
-(-bnot2*016)
2*0+($a=1+6)*$a
(20-shr($a=1))*(6-$a)    #50
(-bnot2)*(-bnot016)
20+($a=16)+$a
($b=20*($a=1)+6)+$b+$a
($a=20+1+6)+$a
($a=20+($b=1)+6)+$a+$b
($a=20)+16+$a
(($a=(2+!0))+16)*$a
(20-shr($a=1))*6-$a-$a
(20-shr($a=1))*6-$a
(20-shr1)*6              #60
(20-shr($a=1))*6+$a
(($a=2)*0+1-shl6)-$a
-bnot-(2*0+1-shl6)
2*0+1-shl6
(2*0+($a=1)-shl6)+$a
(-bnot2)*-0x16
($a=201)/($a%6)
20+($a=16)+$a+$a
20+($a=16)+$a+$a+$a/$a
-($a=2)*-bnot016*$a+$a   #70
2*01*($a=6)*$a-$a/$a
2*01*($a=6)*$a
($a=2+01+6)*$a-$a+$a/$a
($a=2)*01*($b=6)*$b+$a
($a=20)+16+$a+$a-$a/$a
($a=20)+16+$a+$a
($a=20)+16+$a+$a+$a/$a
2*01*($a=6)*$a+$a
($a=20)%16*$a-$a/$a
($a=20)%16*$a            #80
($a=2+01+6)*$a
($a=2)*0x16*$a-$a*$a-$a
20+(($a=1)-shl6)-$a
20+(1-shl6)
20+(($a=1)-shl6)+$a
($a=2)*0x16*$a-$a
($a=2)*0x16*$a-$a/$a
($a=2)*0x16*$a
($a=2)*0x16*$a+$a/$a
($a=2)*0x16*$a+$a        #90
($a=2)*0x16*$a+$a+$a/$a
($a=2)*0x16*$a+$a+$a
20*(-1+($a=6))-$a-$a/$a
20*(-1+($a=6))-$a
20*($a=-1+6)-$a
2*(!0+1+($a=6))*$a
20*(($a=-1)+6)+$a+$a+$a
($a=2)*($b=01+6)*$b
20*(($a=-1)+6)+$a
20*(-1+6)                #100

```

100% manually golfed - no brute force programs or other aids enlisted.
~~I feel that 1500 is *maybe* within reach~~
**Sub-1500 achieved!** Let's see how well I can do on getting this lower. (NB - This was only tested in v4, but should work in v3 and v5 without modification. Will not work in v2 or v1 as those versions did not have bitwise shift operators.)

Key points are marked with `##.hashes.##` in the above code.

**#11** is the first assignment to variable `$a`. Unlike some other languages, variables don't need to be pre-initialized for parsing, and it's only during execution that variables are resolved. Since the `($a=01)` is surrounded by parens, it's evaluated first and so the second `-$a` is equivalent to `-1`. This is used rather extensively from here on out, and is one of the biggest things keeping the bytecount down.

**#17** shows the first use of `!` for Boolean not. In PowerShell, types are pretty loosely cast, so if casting can be implied, it'll work. Here, we're using the fact that `!!20` equals `!$false`, which is `$true`, which can be implicitly cast as `[int]1`, which results in `17`. This is used several times to either get another `1` or make a portion go to `0`.

**#22** Showcases the `0x` hexadecimal cast operator, here turning `0x16` into `22`. However, since `0x16` is the only number we can get, its usefulness is limited.

**#23** has the `-bor` operator, for "binary or." However, since both `-bor` and `-bxor` have *lower* precedence than simple arithmetic operators, using them usually requires parens, which severely limits usefulness. This is the only one I've found where it's shorter to use the binary or operator (I eliminated the `-bxor` operator from 22).

**#30** is the first time the `-bnot` operator is introduced. This is the "binary not" operator, and functions similarly to `~` in (e.g.) JavaScript. However, it usually needs parens, since the negation will show as `--bnot` and result in a parse/syntax error, and since it's five characters compared to one for `~`, it gets used sparingly.

**#39** is the first use of our binary shift operators, `-shl` and `-shr`. These are similar to `<<` or `>>` in other languages, but are explicitly dyadic, meaning we need a number on both sides for them to work, which limits their usefulness in this challenge. Additionally, their precedence isn't explicitly called out in documentation, but testing shows them to be lower than simple arithmetic, meaning that parens need to be used liberally, so they don't make as much of an appearance as in other language answers.

# Answer
> 4 votes
## CJam, ~~792~~ 791 bytes

I kind of got lazy near the end, a lot of them just ended up being increments and decrements (101 is a lot!), although I'm not sure if there is any other way for a few of the numbers. There's still plenty of time to golf it if I need to.

Around #40 there are some winky faces ;)

```
2016!          e# 0
2016g
2016g)
201 6%
20 16-
20)16-
20 1>6*
20 1>6+
201mQ6-
201mQ6-)
2 01 6*(*      e# 10
2 01*6*(
2 01*6*
2~016+
-2 016+
2)016(|
20;16
2(016+
2 016+
2)016+
20 16|         e# 20
20)16|
20 1*6|
20 1|6|
20 16mQ+
20_*16/
20 1 6*+
20 1+6+
20 1)6++
20)1)6++
2 016(*        e# 30
2 016*(
2 016*
201 6/
2 016)*
20(16+
20 16+
20)16+
20)16)+
20_+16;(
20_+16;        e# 40
20_+16;)
20)_+16;
20)_+16;)
20(1m<6+
2)016(*
20 1m<6+
2)016*(
2)016*
2)016*)
2)016)*(       e# 50
2)016)*
20 16_++
20)1 6(m<+
20(_16++
20_16++(
20_16++
20_16++)
20)_16++
20)_16++)
20 16mQ(*      e# 60
20 16mQ(*)
2 01*6#((
2 01*6#(
2 01*6#
2 01*6#)
201_+6/(
201_+6/
201_+6/)
201mQ6(*(
201mQ6(*       e# 70
20_16_+++(
20_16_+++
20_16_+++)
20)_16_+++
20(16mQ*(
20(16mQ*
20(16mQ*)
20_16^*((
20_16^*(
20_16^*        e# 80
2)016mQ#
201mQ6*((
201mQ6*(
201mQ6*
201mQ6*)
201mQ6*))
201mQ6*)))
[20_16__]:+
[20_16__]:+)
[20)_16__]:+   e# 90
[20_16)__]:+
[20__16_]:+
20(1*6(*((
20(1*6(*(
20(1*6(*
20(1*6(*)
201mQ6)*(
201mQ6)*
20 1*6(*(
20 1*6(*       e# 100

```

# Answer
> 3 votes
# Mathematica, ~~2912~~ ~~2502~~ ~~2282~~ 2180 bytes

Could *definitely* be golfed further. Mostly just solves a few separate Frobenius equations, which yields O(*n*) length solutions. The rest were generated by my brute-forcer.

```
2 0 16
2-01^6
2 01^6
2+01^6
20-16
2 0-1+6
201;6
2-01+6
2 01+6
2+01+6
a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c+c+c+c+c+c+c+c+c+c
a=20;16;a+a+a+a+a

```

# Answer
> 2 votes
# JavaScript, 5244 chars

Could probably be golfed a lot further. Test in the Chrome console. I kinda gave up at 10.

```
201&6
!!2016
2%016
20+~16
20-16
-2+0+1+6
2*0*1+6
2*0+1+6
2*01+6
2+01+6
-~-~-~-~-~-~20-16
-~-~-~-~-~-~-~20-16
-~-~-~-~-~-~-~-~20-16
-~-~-~-~-~-~-~-~-~20-16
20*1-6
!!2+016
2+016
!!20+16
2.0+16
2+!0+16
20+!16
20+!!16
-~20+!!16
-~-~20+!!16
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16
2*016
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16
(2+0)*16
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~20-16
20+16
-~20+16
-~-~20+16
-~-~-~20+16
-~-~-~-~20+16
-~-~-~-~-~20+16
-~-~-~-~-~-~20+16
-~-~-~-~-~-~-~20+16
-~-~-~-~-~-~-~-~20+16
-~-~-~-~-~-~-~-~-~20+16
-~-~-~-~-~-~-~-~-~-~20+16
-~-~-~-~-~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-~-~-~-~-~-~-~-~-~-~-~-~20+16
20*-(1-6)

```

# Answer
> 1 votes
# Java 7, 1,083 bytes

For the byte-count I've only counted the expressions itself between the parenthesis. So I've excluded the `System.out.println`s and `class`. Including those it would be **3,049 bytes**.
PS: Not entirely sure if the int-cast for `72` is valid.. Although it does add 5 bytes anyway..

```
201&6
2-01%6
2%016
201%6
20-16
201%~6
2%01+6
2-01+6
2*01+6
2+01+6
~2+016
~2+016
2^016
20-1-6
2|016
20+1-6
2+016
2-~016
2+0+16
20-1%6
20|16
20+1%6
20*1|6
20|1|6
20+~1+6
20-1+6
20*1+6
20+1+6
2*016
20-~1-~6
-2*~016
20|~-16
(2+0)*16
20*~1^~6
-20*~1-6
20+~-16
20+16
20-~16
20-~-~16
-~2*~-016
20<<1%6
~-(-~2*016)
~2*-016
~20^-1<<6
~20*~1^6
~2*~016
20<<1|6
-20*~1-~6
~20*~1+6
~20*~1-~6
-20/~1*~-6
~2*~-~-~016
20|1<<~-6
-20*~-~1+~6
20*-~-~1-6
-20*~-~1-~-6
~-~2*-016
~20*~-~1-6
-20*~-~1^6
~(20/~1*6)
-20/~1*6
~2^(0-1)<<6
-2^(0-1)<<6
~20/~1*6
(2-01)<<6
(2+~0)|1<<6
2|01<<6
2-~0|1<<6
~-~2*~16
~20*~-~1+6
20/~1*~6
-~(20/~1*~6)
~-~(int)2.0*~-~16
-20<<-~1^~6
-20<<-~1^-6
~-~-~2*~016
~-20*(~1+6)
~-~20/~1*-~6
~-20<<-~1|6
~-(20*~(1-6))
20*(~1+6)
-~(20*~(1-6))
~-~-20|1<<6
~-20|1<<6
20|1<<6
-~20|1<<6
20<<-~1|6
20<<-~1|-~6
-~-~20*(~1+6)
~20*~-~-~1+~-6
~-~-20*-(1-6)
~20*~-~-~1-~6
~20*~-~-~1-~-~6
~2^~-~01<<~-6
-2^~-~01<<~-6
~-20*1*~-6
(2+01)<<~-6
-~(~2*~-~0*16)
~-~-(20*-(1-6))
~-(20*1*~-6)
20*-(1-6)

```

**Ungolfed & test code:**

Try it here.

```
class M{
  public static void main(String[]a){
    System.out.println(201&6);
    System.out.println(2-01%6);
    System.out.println(2%016);
    System.out.println(201%6);
    System.out.println(20-16);
    System.out.println(201%~6);
    System.out.println(2%01+6);
    System.out.println(2-01+6);
    System.out.println(2*01+6);
    System.out.println(2+01+6);
    System.out.println(~2+016);
    System.out.println(~2+016);
    System.out.println(2^016);
    System.out.println(20-1-6);
    System.out.println(2|016);
    System.out.println(20+1-6);
    System.out.println(2+016);
    System.out.println(2-~016);
    System.out.println(2+0+16);
    System.out.println(20-1%6);
    System.out.println(20|16);
    System.out.println(20+1%6);
    System.out.println(20*1|6);
    System.out.println(20|1|6);
    System.out.println(20+~1+6);
    System.out.println(20-1+6);
    System.out.println(20*1+6);
    System.out.println(20+1+6);
    System.out.println(2*016);
    System.out.println(20-~1-~6);
    System.out.println(-2*~016);
    System.out.println(20|~-16);
    System.out.println((2+0)*16);
    System.out.println(20*~1^~6);
    System.out.println(-20*~1-6);
    System.out.println(20+~-16);
    System.out.println(20+16);
    System.out.println(20-~16);
    System.out.println(20-~-~16);
    System.out.println(-~2*~-016);
    System.out.println(20<<1%6);
    System.out.println(~-(-~2*016));
    System.out.println(~2*-016);
    System.out.println(~20^-1<<6);
    System.out.println(~20*~1^6);
    System.out.println(~2*~016);
    System.out.println(20<<1|6);
    System.out.println(-20*~1-~6);
    System.out.println(~20*~1+6);
    System.out.println(~20*~1-~6);
    System.out.println(-20/~1*~-6);
    System.out.println(~2*~-~-~016);
    System.out.println(20|1<<~-6);
    System.out.println(-20*~-~1+~6);
    System.out.println(20*-~-~1-6);
    System.out.println(-20*~-~1-~-6);
    System.out.println(~-~2*-016);
    System.out.println(~20*~-~1-6);
    System.out.println(-20*~-~1^6);
    System.out.println(~(20/~1*6));
    System.out.println(-20/~1*6);
    System.out.println(~2^(0-1)<<6);
    System.out.println(-2^(0-1)<<6);
    System.out.println(~20/~1*6);
    System.out.println((2-01)<<6);
    System.out.println((2+~0)|1<<6);
    System.out.println(2|01<<6);
    System.out.println(2-~0|1<<6);
    System.out.println(~-~2*~16);
    System.out.println(~20*~-~1+6);
    System.out.println(20/~1*~6);
    System.out.println(-~(20/~1*~6));
    System.out.println(~-~(int)2.0*~-~16);
    System.out.println(-20<<-~1^~6);
    System.out.println(-20<<-~1^-6);
    System.out.println(~-~-~2*~016);
    System.out.println(~-20*(~1+6));
    System.out.println(~-~20/~1*-~6);
    System.out.println(~-20<<-~1|6);
    System.out.println(~-(20*~(1-6)));
    System.out.println(20*(~1+6));
    System.out.println(-~(20*~(1-6)));
    System.out.println(~-~-20|1<<6);
    System.out.println(~-20|1<<6);
    System.out.println(20|1<<6);
    System.out.println(-~20|1<<6);
    System.out.println(20<<-~1|6);
    System.out.println(20<<-~1|-~6);
    System.out.println(-~-~20*(~1+6));
    System.out.println(~20*~-~-~1+~-6);
    System.out.println(~-~-20*-(1-6));
    System.out.println(~20*~-~-~1-~6);
    System.out.println(~20*~-~-~1-~-~6);
    System.out.println(~2^~-~01<<~-6);
    System.out.println(-2^~-~01<<~-6);
    System.out.println(~-20*1*~-6);
    System.out.println((2+01)<<~-6);
    System.out.println(-~(~2*~-~0*16));
    System.out.println(~-~-(20*-(1-6)));
    System.out.println(~-(20*1*~-6));
    System.out.println(20*-(1-6));
  }
}

```

---
Tags: code-golf, restricted-source, programming-puzzle, expression-building, apl
---


title: Help me I'm lost in the ocean!

text:
# Question
Title: Help me I'm lost in the ocean!
**Introduction**

Today I went fishing alone with my canoe, unfortunately I fell asleep and the stream brought me away, I lost my oars, now it's night and I am lost in the ocean! I can't see the coast so I must be far away!

I have my cell phone but is malfunctional because it got wet by the salty water, I can't talk or hear anything because the mic and phone speaker are broken, but I can send SMS to my friend who is on the coast's beach!

My friend has a very powerful torch and he raised it on top of bamboo's canes to show me the right direction, but I can’t row because I have no oars, so I must tell him how far I am so he can send someone to catch me!

My friend told me that he is keeping the torch at 11.50 meters on the sea level, and I can see the light right over the horizon. Now I only remember from the school that the Earth radius should be 6371 Km at the sea level, and I’m sittin in my canoe so you can assume that my eyes are at sea level too.

**Task**

Since the currents are moving me moment by moment, my friend is raising the torch from time to time (now it’s at 12.30 meters), please write a full program or function that will help me to calculate the distance from my friend’s position!

Here is a diagram (not to scale):

The orange point labelled `M` is me, the red point labelled `T` is the torch. The green line is the linear distance between `M` and `T`

**Input**

Take from standard input the torch height `h` in meters at the sea level, which I see right on top of the horizon, in the form of a floating point number with two decimals precision (with the accuracy of 1 centimeter or 0.01 meters), in the range from 0 to 100 included.

**Output**

You should return the euclidean length of the green line with the accuracy of 1 cm. For example if you output in meters, should be with two decimals (at least). The output can be either meters or kilometers, but respecting the accuracy.

**Test cases:**

All values in meters.

```
11.5 > 12105.08
13.8 > 13260.45

```

**Rules**

Shortest code wins.

# Answer
> 4 votes
# 05AB1E, ~~13~~ ~~12~~ 10 bytes

Saved 2 bytes thanks to Emigna.

Since there is no trigonometric functions to be called using OP's assumption that the earth is locally a plane, it becomes possible to make an 05AB1E solution.

```
•1#oC•+¹*t

           For understanding purposes input is referred to as 'h'
•1#oC•     Push 12742000 [ = 2*R, where R is the radius of earth]
      +    Compute 2*R+h
       ¹*  Multiply by h. Result is (2*R*+h)*h
         t Take the square root of it and implicitly display it

```

Try it online!

# Answer
> 4 votes
# Python, ~~34~~ 26 bytes:

(*-8 bytes thanks to Osable!*)

```
lambda i:(i*(i+12742))**.5

```

An anonymous lambda function. Takes input in kilometers and outputs in kilometers. Invoke as `print(<Function Name>(<Input>))`.

# Answer
> 4 votes
# PHP, 34 bytes

```
<?=sqrt((12742e3+$h=$argv[1])*$h);

```

**breakdown**

```
   r^2+x^2=(r+h)^2      # Pythagoras base
   r^2+x^2=r^2+2rh+h^2  # right term distributed
       x^2=    2rh+h^2  # -r^2
       x =sqrt(2rh+h^2) # sqrt

```

so far, this is identical to the old Mathematica answer

```
sqrt(2*6371e3*$h+$h*$h) # to PHP
sqrt(14742e3*$h+$h+$h)  # constants combined
sqrt((14742e3+$h)*$h)   # conjugation to save a byte
((14742e3+$h)*$h)**.5   # same size

```

now all that´s left to do is to add input `=$argv[1]` and output `<?=` \- done

# Answer
> 4 votes
# dc, ~~16~~ 11 bytes:

```
?d12742+*vp

```

Prompts for input through command line in kilometers and then outputs distance in kilometers.

## Explanation

```
?           # Prompt for input
 d          # Duplicate the top-of-stack value
  12742     # Push 12,742 onto the stack
       +    # Pop the top 2 values of the stack and push their sum
        *   # Pop top 2 values of the stack and push their product
         v  # Pop the remaining value and push the square root
          p # Output the result to STDOUT

```

This takes advantage of the following:

```
((6371+h)**2-6371**2)**.5
=> ((6371**2+12742h+h**2)-6371**2)**0.5
=> (h**2+12742h)**0.5
=> (h*(h+12742))**0.5

```

# Answer
> 4 votes
# jq, 18 characters

```
(12742e3+.)*.|sqrt

```

Yet another copy of the same formula.

Sample run:

```
bash-4.3$ jq '(12742e3+.)*.|sqrt' <<< 11.5
12105.087040166212

```

On-line test

# Answer
> 4 votes
# Haskell, 22 bytes

```
d h=sqrt$h*(h+12742e3)

```

Usage:

```
Prelude> d 11.5
12105.087040166212

```

---

### Pointfree: (23 bytes)

```
sqrt.((*)=<<(+12742e3))

```

# Answer
> 3 votes
## R, 29 bytes

```
h=scan();sqrt(h^2+2*h*6371e3)

```

Takes input from stdin

# Answer
> 2 votes
## Mathematica, 16 bytes

Either of these works for both input and output in kilometres:

```
(12742#+#*#)^.5&

```

```
((12742+#)#)^.5&

```

This is a simple application of Pythagoras to the problem:

```
   x*x + R*R = (R+h)*(R+h)
=> x*x = (R+h)*(R+h) - R*R
       = R*R + 2*R*h + h*h - R*R
       = 2*R*h + h*h
=>   x = √(2*R*h + h*h)

```

# Answer
> 2 votes
# Jelly, 9 bytes in Jelly's code page

I decided to have a go at writing the program in a golfing language. I actually found a more efficient algorithm than the one other people are using (at least over short distances like the one in the question), but it requires literal floating-point numbers which Jelly doesn't seem to be able to compress, so Pythagoras it is.

```
+“Ȯịż’×µ½

```

Explanation:

```
 “Ȯịż’     12742000, compressed base-250
+          add to argument
      ×    multiply with original argument
       µ   separator to avoid what would otherwise be a parsing ambiguity
        ½  square root everything seen so far
           implicit output at EOF

```

The need for the `µ` separator irks me, but I think it's unavoidable; Jelly has already saved a byte over 05AB1E via being able to guess what arguments many of the commands need, but in this case it can't correctly guess to the end, so I needed to give it a hint.

# Jelly, 7 bytes in Jelly's code page

```
×“Ȯịż’½

```

As I explained in my other answer, the series approximation to the Pythagoras approximation actually produces better results over the lengths included in the question (at least, they're closer to the example outputs), and also has a shorter formula. While I was writing it, I realised that instead of calculating the square root of 12742000 in advance, I could multiply the number by 12742000 first, and then square root both at the same time. This is basically equivalent to the other formula without the addition, and as such, it can be produced from the previous program via removing the addition from it. This saves two bytes, as it now parses unambiguously and so we don't need a `µ` any more.

# Answer
> 2 votes
# Ruby, 23

23 bytes, in Km

```
->h{(h*h+h*12742)**0.5}

```

25 bytes, in m

```
->h{(h*h+h*12742e3)**0.5}

```

# Answer
> 1 votes
# Tcl, 49 bytes:

```
set A [get stdin];puts [expr ($A*($A+12742))**.5]

```

Well, I am brand new to Tcl, so any tips for golfing this down is highly appreciated. Like my other answers, prompts for command line input in kilometers and outputs in kilometers. Essentially a Tcl adaptation of my existing `dc` and `python` answers.

# Answer
> 1 votes
# x86\_64+SSE machine code, 16 bytes

The bytes of the program are on the left (in hexadecimal), there's a disassembly on the right to make it a bit easier to read. This is a function that follows the normal x86\_64 convention for functions taking and returning a single-precision floating point number (it takes the argument in %xmm0 and returns its answer in the same register, and uses %xmm1 and %eax as temporaries; these are the same calling conventions a C program will use, and as such you can call the function directly from a C program, which is how I tested it).

```
b8 80 19 5f 45          mov    $0x455f1980,%eax
66 0f 6e c8             movd   %eax,%xmm1
0f 51 c0                sqrtps %xmm0,%xmm0
0f 59 c1                mulps  %xmm1,%xmm0
c3                      retq

```

Even with a disassembly, though, this still needs an explanation. First, it's worth discussing the formula. Most people are ignoring the curvature of the earth and using Pythagoras' formula to measure the distance. I'm doing it too, but I'm using a series expansion approximation; I'm only taking the term relating to the first power of the input, and ignoring the third, fifth, seventh, etc. powers, which all have only a very small influence at this short distance. (Besides, the Pythagoras approximation gives a low value, whereas the later terms in the series expansion serve to reduce the value; as such, by ignoring a minor factor that would serve to push the approximation in the wrong direction, I actually happen to get a more accurate result by using a less accurate formula.) The formula turns out to be √12742000×√h; as a single-precision floating-point number, √12742000 is `0x455f1980`.

The next thing that might confuse people is why I'm using vector instructions for the square root and the multiply; `%xmm0` and `%xmm1` can hold four single-precision floating point numbers each, and I'm operating on all four. The reasoning here is really simple: their encoding is one byte shorter than that of the corresponding scalar instructions. So I can make the FPU do a bunch of extra work square-rooting and multiplying zeroes in order to save myself two bytes, in a method that's very reminsicent of the typical golfing language algorithm. (I called x86 assembler the golfing language of assemblers in chat a while back, and I still haven't changed my mind on that.)

From there, the algorithm's very simple: load `%xmm1` with √12742000 via `%eax` (which is shorter in terms of bytes than loading it from memory would be), square-root the argument (and three zeroes), multiply corresponding elements of `%xmm1` and `%xmm0` (we only care about the first element), then return.

# Answer
> 1 votes
# JavaScript (ES6), ~~31~~ 25 bytes

Displays the value in metres

```
//the actual code
f=h=>(h*h+12742e3*h)**0.5

console.log(f(11.5));
console.log(f(13.8));
```

# Answer
> 1 votes
# Minkolang v0.15, 22 bytes

```
ndd*$r'12742000'*+1MN.

```

Try it online!

```
n                               gets input in the form of a number
 dd                             duplicates it twice
   *                            multiplies 2 of the duplicates with each other
                                STACK: [h, h*h]
    $r                          swap top two stack values
                                STACK: [h*h, h]
      '12742000'*               push this number and multiply the original input by it
                                STACK: [h*h, h*12742000]
                 +1M            adds the two values and takes their square root
                                STACK: [sqrt(h*h+h*12742000)]
                    N.          output as a number and end program

```

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