title: Contradictory Polyglots

text:
# Question
Title: Contradictory Polyglots
Well, everyone loves **Polyglots**. You will be given two integers, in any standard form of input (no hardcoding). Your task is to write a **polyglot** which finds the minimum value in a language and the maximum value between the two numbers in the other language, and performs the following operations:

* The code which finds the maximum value must also compute their sum.
* The program which finds the minimum value must also compute the result of their subtraction (`max - min`)
* *Here is the "tricky part"*: If the two numbers are equal, both the programs must not output/ return anything (both to `STDOUT` and `STDERR` or any other `return` method)
* See the *Output specs* section for more details about formatting

---

## Input

As stated above, two integers taken as input in any **standard method**, common to both languages.

## Output specs

* For the program which finds the `max`, the format should be: `max_value, addition result`
* For the program which finds the `min`, the format should be `min_value, subtraction result (max - min)`
* The results can be printed, with any clear delimiter (,`\n`,`,` or whatever else you want), returned from the function as a string containing the two expected values with a delimiter or as a list of numbers (e.g: `[max_value,sum]`)

---

## Examples:

```
Input   || Max Language Output || Min Language Output

100, 40 || 100, 140            || 40, 60
63, 67  || 67, 130             || 63, 4
-45, -5 || -5, -50             || -45, 40
21, 21  ||                     ||
-1, 1   || 1, 0                || -1, 2

```

---

## Scoring:

This is , so try to write the shortest code to get the desired results, while taking note that **Standard Loopholes** are strictly disallowed. You must use two different languages, not other versions of the same language (e.g: `Python 2`-`Python 3` pairs are not valid)

# Answer
# 05AB1E / Jelly, ~~21~~ 20 bytes

-1 byte after asking for some help - thanks Emigna! (``` will `push(uwrapped(pop()))`)

Raw bytes (the dump to the right shows what my Windows machine displays):

```
60 ca 69 b9 5a 73 4f 29 71 93 18 fa 2c d3 f7 d3    `Êi¹ZsO)q..ú,Ó÷Ó
cd 04 18 2f                                         Í../

```

Both take input from STDIN and output to STDOUT as a list representation `[x, y]`.

The max language is 05AB1E:

```
`Êi¹ZsO)q“.ú,Ó÷ÓÍ../

```

Where the `.` represent unprintable bytes in it's codepage (cp1252), and probably here in whatever you are using (0x18=`CAN` and 0x04=`EOT`).

Try the 05AB1E version

The min language is Jelly:

```
İ__iỤZs0)qƓð«,ạẋạṠ¥ð/

```

Try the Jelly version.

### How?

05AB1E:

```
`Êi¹ZsO)q“.ú,Ó÷ÓÍ../ - parsed left to right, executed as parsed
                     - implicit input taken
  i                  - If:
`                    -     push(unwrapped(pop()))
 Ê                   -     push(pop()!=pop())
                     - ...Then:
   ¹                 -     push(1st item from input history)
    Z                -     push(max(top of stack))
     s               -     push(reverse(pop(),pop()))
      O              -     push(sum(pop()))
       )             -     wrap(pop())
        q            -     quit - implicit print of top of stack
         “.ú,Ó÷ÓÍ../ - unexecuted and unparsed string

```

Jelly:

```
`ȮiỤZs0)qƓð«,ạẋạṠ¥ð/ - parsed left to right, not executed until parsed
`ȮiỤZs0              - a dyadic chain which would error if executed (monad from dyad, index of, grade up, transpose, split into chunks of length 0)
       )q            - currently unassigned code points each currently creates a new link
         Ɠ           - read and evaluate a line of input
          ð       ð  - dyadic chain separations
                   / - reduce by:
           «         -     minimum(left, right)
             ạ       -     absolute difference(left, right)
            ,        -     pair(result)
                 ¥   -     last two links as a dyad:
               ạ     -         absolute difference(left, right)
                Ṡ    -         sign(result) (i.e. {0:0, +x:1, -x:-1} but -x never happens)
              ẋ      -     repeat list left right times
                     - implicit print

```
> 6 votes

# Answer
# C and C++ (gcc), ~~117~~ 107 bytes

*-10 bytes thanks to @Steadybox!*

```
#include<stdio.h>
int f(int a,int b){auto c=.5;a-b&&printf("%d %d",c?b<a?b:a:a>b?a:b,c?a-b>0?a-b:b-a:a+b);}

```

**Explanation:** In C, `auto c=.5` declares an integer variable with the auto storage class (which is the default), which is then initialized to 0, whereas in C++11 it declares a double, which is initialized to 0.5. So the variable's value will be truthy in C++ and falsy in C.

**C - max language:** Try it online!

**C++ - min language:** Try it online!
> 18 votes

# Answer
# Python 3 / Jelly, 42 bytes

Using Jelly's code-page to encode the file.

Raw bytes:

```
6c 61 6d 62 64 61 20 78 2c 79 3a 5b 6d 61 78 28    lambda x,y:[max(
78 2c 79 29 2c 78 2b 79 5d 2a 28 78 21 3d 79 29    x,y),x+y]*(x!=y)
0a 23 7f fa 2c d3 f7 d3 cd 04                      .#.ú,Ó÷ÓÍ.

```

Both define an unnamed dyadic function.

Python (the max language) sees:

```
lambda x,y:[max(x,y),x+y]*(x!=y)
#\x7fú,Ó÷ÓÍ\x04

```

Tests as Python.

Jelly (the min language) sees:

```
lambda x,y:[max(x,y),x+y]*(x!=y)½#
«,ạẋạṠ¥

```

Tests as Jelly.

### How?

Jelly interprets 0x0a as `½`, the square root atom while Python interprets it as a newline. In Jelly 0x7f is interpreted as a separation between links (functions) and is represented by either a newline or a pilcrow in it's codepage. For Jelly the last link is the main function - here it does not call the link above (which the interpreter does still need to parse correctly). In Python 0x23, `#` instructs that anything after it and before 0x0a, a newline, is a comment.

The Python code that gets executed:

```
lambda x,y:[max(x,y),x+y]*(x!=y)
lambda x,y:                      - A function taking two inputs, x and y
           [        ,   ]        - A list with two items
            max(x,y)             - take the maximum of x and y
                     x+y         - x plus y
                           x!=y  - x not equal to y?
                         *(    ) - multiply - True is treated as if it were 1, False as if it were 0

```

The Jelly code that gets executed:

```
«,ạẋạṠ¥ - A dyadic link (function of two variables): x, y
«       - minimum(x, y)
  ạ     - absolute difference(x, y)
 ,      - pair left with right (creating a list)
      ¥ - last two links as a dyad:
     ạ  -     absolute difference(x, y)
    Ṡ   -     sign(result) (i.e. {0:0, +x:1, -x:-1} but -x never happens)
   ẋ    - repeat the list to the left right times (either the same list or an empty list)
        - return the result

```
> 9 votes

# Answer
# Ruby / Python 3, 102 bytes

Ruby returns max/sum, Python returns min/difference. Input is an array object read from STDIN.

```
a=eval((0and gets or input()))
b=a.sort()
x,y=(b or a)
z=0 or 1
x==y or print([[y,x][z],[x+y,y-x][z]])

```

Try it online: Ruby

Try it online: Python

The main quirk used here is the use of the truthy `0` in Ruby, which is falsy in Python. The other thing worth mentioning is that Python's `sort` function modifies the list in-place and returns `None`, while Ruby's doesn't and returns the sorted array, hence the need to use `b or a` to get the min/max.

Python 3 is required because Python 2 complains if you try to call `print` after the `or` statement in the last line.
> 8 votes

# Answer
# Java/AWK, ~~219~~ ~~217~~ ~~212~~ 196 bytes

```
/*#\/* /
{$0=((x=$1)<y=$2)?x" "y-x:y" "x-y}x!=y
#*/interface B{static void main(String[]A){Integer x=Integer.parseInt(A[0]);int y=x.parseInt(A[1]);System.out.print(x==y?"":(x<y?y:x)+" "+(x+y));}}

```

Try it online!

Java outputs the max and sum, AWK outputs min and difference. No output for either if the inputs are identical.

This is my first polyglot and first TIO :)
> 4 votes

# Answer
# JavaScript (ES6)/ QBasic, ~~172~~ 171 bytes

```
'';f=x=>{m=Math.max(...x);s=Math.min(...x);if(x[0]!=x[1])alert([m,m-s])}/*
INPUT c
LET m=c
LET s=c
INPUT n
IF n>c THEN m=n
IF n<c THEN s=n
IF n<>c THEN PRINT m,m+s
END
'*/

```

Based on this solution of mine of a similar question.

This solution too use the comment approach!

JavaScript is the min-language. It takes in an array containing numbers as input. Outputs two numbers separated by `,` (1st number is the smallest value of the input-array and 2nd number is the difference of the greatest and the smallest values of the input-array) by `alert()`ing. Does not `alert()` anything if the numbers are equal. You can call the function like `f([100,40])`.

QBasic is the max-language. Repeatedly asks for input, twice. Prints the largest number of the input-numbers as well as the sum of largest and smallest numbers of the input. Does not `PRINT` anything if the numbers are equal.

---

## How does it work?

In QBasic (a language of structured BASIC family; it does not require line numbers), `'` marks the beginning of a comment which goes till the end of the line. Whereas in JavaScript, it marks the start of a string. So, the whole first line is marked as a comment in QBasic but in JavaScript, the line is executed (and this line contains the JavaScript part that computes the smallest number and the difference of greatest and smallest numbers, as well as a `/*` at the end which starts a comment in order to hide the rest of the QBasic code from JavaScript interpreter.)

The code from second line to second-last line contains the QBasic code to compute the greatest number and the sum of greatest and smallest number (the code is very self-explanatory).

The last line contains `'*/`. `'` causes the QBasic interpreter to interpret the following code as a comment, whereas in JavaScript, it does not have any effect as it is a part of a comment (which was started at the end of the first line). The following code (`*/`) causes JavaScript to end the comment which was started in the first line, but it is not executed in QBasic because QBasic thinks it's a part of a comment.

---

## Test Cases

**JavaScript (min-language):**

```
'';f=x=>{m=Math.max(...x);s=Math.min(...x);if(x[0]!=x[1])alert([m,m-s])}/*
INPUT c
LET m=c
LET s=c
INPUT n
IF n>c THEN m=n
IF n<c THEN s=n
IF n<>c THEN PRINT m,m+s
END
'*/

f([100,40]);
```

**QBasic (max-language):**

Go to this website. Copy paste the following code in their text-editor :

```
1 '';f=x=>{m=Math.max(...x);s=Math.min(...x);if(x[0]!=x[1])alert([m,m-s])}/*
2 INPUT c
3 LET m=c
4 LET s=c
5 INPUT n
6 IF n>c THEN m=n
7 IF n<c THEN s=n
8 IF n<>c THEN PRINT m,m+s
9 END
10 '*/

```

The reason why line numbers are required is that the website I mentioned only supports unstructured BASIC languages. And that website is the only decent online BASIC interpreter I could find. However, running the code present in the top of the post (the code without line numbers) should work fine in any good QBasic interpreter that supports structured BASIC and `'` as a comment-starter (few do not, most do, though)
> 3 votes

---
Tags: code-golf, math, arithmetic, polyglot
---


# Question
Title: What characters are more common in my MD2 hash?
**The challenge is simple**

Write a script that, when given a string input, will hash the string using the MD2 hashing algorithm, and then return either a positive integer or negative integer output based on which character set below is more common in the resulting hash as a hexadecimal string:

```
01234567 - (positive)
89abcdef - (negative)

```
* The input will always be a string, but may be of any length up to 65535
* The entire input, whitespace and all, must be hashed
* For the purposes of this challenge, the integer 0 is considered neither positive nor negative (see tie output)
* The more common set is the one who's characters are more common within the 32 character hexadecimal hash string
* Your output may contain trailing whitespace of any kind, as long as the only non-whitespace characters are a valid truthy or falsey output
* In the event of a tie, where the hexadecimal string contains exactly 16 characters from each set, the program should output a 0

**I/O Examples**

```
Input: "" (Empty String)
Hash: 8350e5a3e24c153df2275c9f80692773
Output: 1

Input: "The quick brown fox jumps over the lazy cog" (Without quotes)
Hash: 6b890c9292668cdbbfda00a4ebf31f05
Output: -1

Input: "m" (Without quotes)
Hash: f720d455eab8b92f03ddc7868a934417
Output: 0

```

**Winning Criterion**

This is , fewest bytes wins!

# Answer
# Octave, 35 bytes

```
@(s)diff(hist(hash('md2',s),+'78'))

```

\*Requires the latest version of Octave (at least 4.2).

Computes histcounts of the hash string with it's center of bins are 7 and 8 then computes the difference of counts.
> 1 votes

# Answer
## Mathematica, 43 bytes

```
Tr@Sign[15-2#~Hash~"MD2"~IntegerDigits~16]&

```

Outputs the number of digits in `01234567` minus the number of digits in `89abcdef`.
> 8 votes

# Answer
## JavaScript (ES6), 731 bytes

This monster is implementing the MD2 algorithm, so it's embarrassingly long. Based on js-md2 by Chen Yi-Cyuan.

```
let f =

m=>{L=x=s=b=0,n=m.length,M=[],X=[],C=[],S=[...atob`KS5DyaLYfAE9NlSh7PAGE2KnBfPAx3OMmJMr2bxMgsoem1c8/dTgFmdCbxiKF+USvk7E1tqe3kmg+/WOuy/ueqloeZEVsgc/lMIQiQsiXyGAf12aWpAyJzU+zOe/95cD/xkws0iltdHXXpIqrFaqxk+4ONKWpH22dvxr4px0BPFFnXBZZHGHIIZbz2XmLagCG2Alra6wufYcRmFpNEB+D1VHoyPdUa86w1z5zrrF6iYsUw1uhSiECdPfzfRBgU1Satw3yGzBq/ok4XsIDL2xSniIlYvjY+ht6cvV/jsAHTny77cOZljQ5KZ3cvjrdUsKMURQtI/tHxrbmY0znxGDFA`].map(c=>c[O='charCodeAt']());for(l=1;l-2;){for(j=19;j--;)M[j]=M[16+j]||0;for(i=s;i<16;x++)L=(x-n||(b+=i-s,s=i-16,l=2),C[i]^=S[(M[i++]=x<n?m[O](x):16-(b&15))^L]);for(i=0;i<l;i++){for(j=16;j--;)X[32+j]=(X[16+j]=(i?C:M)[j])^X[j];for(t=j=0;j<18;t=t+j++&255)for(k=0;k<48;)t=X[k++]^=S[t]}}for(i=16,n=-i;i--;)n+=!(X[i]&8)+!(X[i]&128);return n}

console.log(f(''))
console.log(f('The quick brown fox jumps over the lazy cog'))
console.log(f('m'))
```
> 8 votes

# Answer
# Python 2 + Crypto, ~~108~~ ~~99~~ ~~93~~ ~~91~~ ~~87~~ 78 bytes

Python doesn't have a native builtin for MD2.

```
from Crypto.Hash import*
lambda s:sum(x<'8'for x in MD2.new(s).hexdigest())-16

```

*Saved 12 bytes thanks to @ovs.*
*Saved 9 bytes thanks to @FelipeNardiBatista.*
> 5 votes

# Answer
# Java 8, 173 bytes

*-4 thanks to dzaima*

*-128 thanks to Oliver, this is basically his answer now.*

```
a->{String h="";for(byte b:java.security.MessageDigest.getInstance("MD2").digest(a.getBytes()))h+=h.format("%02x",b);return h.codePoints().filter(c->c>47&&c<56).count()-16;}

```

Positive for truthy. Negative for falsy. 0 for 0.
> 4 votes

# Answer
# PHP, 50 Bytes

prints 1 for truthy and -1 for false and 0 for a tie

```
<?=preg_match_all("#[0-7]#",hash(md2,$argn))<=>16;

```

# PHP, 58 Bytes

prints 1 for truthy and -1 for false and 0 for a tie

```
<?=16<=>strlen(preg_filter("#[0-7]#","",hash(md2,$argn)));

```
> 3 votes

# Answer
# Tcl + Trf package, 79

```
package require Trf
puts [expr [regexp -all \[0-7\] [hex -m e [md2 $argv]]]-16]

```

Try it online. (Thanks @Dennis for adding Tcl to TIO.)
> 1 votes

# Answer
# PHP, 56 bytes

```
while($i<32)${hash(md2,$argn)[$i++]>'7'}++;echo$$_<=>16;

```
> 1 votes

# Answer
# Java ~~137~~ ~~130~~ ~~124~~ 123 bytes

```
a->{int c=32;for(int b:java.security.MessageDigest.getInstance("MD2").digest(a.getBytes()))c-=(b>>6&2)+(b>>2&2);return c;}

```

Test it online!

Basically, for each byte, we're asked to check against its 4th and 8th least significant bits. I don't go through the hex representation at all. So it seemed only natural to start playing with bits.

Values `<0` are falsey, values `>0` are truthy, value `0` is neither truthy or falsey. The usual truthy and falsey can't be applied to Java this time (because it can't be `true` or `false` or `0` with the rule `if(<truthy>)`), so I took the liberty to declare as such.

## Saves

1. 137 -\> 130 bytes: golfed by using bit operations, removing 2 everytime I get a "falsy" bit.
2. 130 -\> 124 bytes: more bitwise operations
3. 124 -\> 123 bytes: replaced `byte` by `int` in the for loop declaration.
> 1 votes

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


title: Break my source file!

text:
# Question
Title: Break my source file!
# Challenge

Create a program that, when run, changes the contents of the source file. This means that you can delete/add/change characters in the source file, but you can't delete the (source) file itself (deletion is when the source file does not exist after the program is run).

In the case of pre-compiled languages such as C++, your program can change the source file only, such that when compiled, either fails or does not produce the same result.

Your program must not return any errors, such as access violations (e.g. opening a file that is already open).

* This is an advantage to pre-compiled languages, as the source file does not have to be in use to run it.

## Input

You may take an optional path to the source file, but nothing more.

## Output

You may output anything.

## Scoring

This is , shortest answer wins!

# Answer
> 10 votes
# Zsh, 3 bytes

```
>$0

```

Truncates the script to length **0**.

Unlike its Bash counterpart, this handles filenames that contain whitespace.

Try it online!

# Answer
> 7 votes
# C, ~~35~~ 25 bytes

```
f(){fopen(__FILE__,"w");}

```

Just empties the source file.

Online test suite on TIO

# Answer
> 5 votes
# Octave, 27 bytes

```
fwrite(fopen('f','w'),'')

```

**Explanation:**

`fopen('f','w')` opens the file `f` (itself) with writing privileges (the file has no file extension (it's not `f.m`)). `fwrite` writes an empty string `''` to that file, overwriting the content of it.

Run it from the GUI / CLI using: `run f`. PS!

Note: You should close the file again afterwards using `fclose(3)`, but this is not necessary for it to work.

# Answer
> 2 votes
# Python, ~~18~~ 17 bytes

```
open(input(),"w")

```

-1 thanks to @EriktheOutgolfer

Opens itself in write mode, deleting everything in the file.

# Answer
> 2 votes
# Jelly, 17 bytes

```
“µ÷ⱮÑċẊṚ⁾Ṁ)ɦGl»ŒV

```

Never fails, but produces different outputs.

Takes relative path through STDIN (unquoted).

Explanation:

```
“µ÷ⱮÑċẊṚ⁾Ṁ)ɦGl»ŒV Main link. Arguments: 0
“µ÷ⱮÑċẊṚ⁾Ṁ)ɦGl»   Literal "open(input(),'w')"
               ŒV Python eval and listify

```

Open a file in write mode in Python overwrites it.

# Answer
> 2 votes
# PHP, 18

```
fopen(__FILE__,w);

```

From the manual:

```
Open for writing only; place the file pointer at the beginning
of the file and truncate the file to zero length. If the file
does not exist, attempt to create it.

```

I guess that should also work in most other languages

# Answer
> 1 votes
# Ruby, 10 bytes

```
open $0,?w

```

Not very original, almost everybody is doing it the same way nowadays.

# Answer
> 1 votes
## C, 27 bytes

```
f(){system("cd>"__FILE__);}

```

Overwrites the contents of the file wtih the current directory.

# Answer
> 0 votes
# Batch, ~~7~~ 4 bytes

Thanks to Neil for saving 3 bytes

```
.>%0

```

`>` overwrites the contents of a file and `%0` returns the current batch file's path.
Result: Blank batch file.

# Answer
> 0 votes
# Node.js, 47 bytes

```
require('fs').writeFileSync(process.argv[1],'')

```

Erase the content of the source file

---
Tags: code-golf, source-layout
---


title: Shorten an absolute path

text:
# Question
Title: Shorten an absolute path
Sometimes a long absolute path, in e.g. a command-line parameter to a linux tool, can be shortened, using current working directory as reference:

```
$ pwd
/home/heh

$ cat /home/heh/mydir/myfile
my stuff

$ cat mydir/myfile
my stuff

```

In this challenge, you should make a function or a program that receives two parameters:

1. Absolute path, using the linux format (starts with `/`)
2. Current directory, using the same format

The output is the shorter of the following:

* Input 1 unchanged
* Relative path that refers to the same file/directory as the absolute path

Fine points:

* If your operating system is compatible with linux, you can use the system's current directory instead of receiving it as input
* You can assume the inputs contain only alphanumeric characters (and path separators)
* You can assume the input absolute path doesn't have a path separator `/` at the end
* You can assume the input current directory has a path separator `/` at the end
* You cannot assume that the absolute path refers to an existing file, or that any part of it is an accessible directory; however, the current directory can be assumed valid
* You can assume there are no symlinks anywhere near either path - because I don't want to require any special way of dealing with symlinks
* No need to support the case where either of the inputs is the root directory
* "The current directory" should be output as `.` (an empty string is not valid)

Test cases (input1, input2, output):

```
/home/user/mydir/myfile
/home/user
mydir/myfile

/var/users/admin/secret/passwd
/var/users/joe/hack
../../admin/secret/passwd

/home/user/myfile
/tmp/someplace
/home/user/myfile

/dir1/dir2
/dir1/dir2/dir3/dir4
../..

/dir1/dir2
/dir1/dir2
.

```

# Answer
# Julia 0.5, 32 bytes

```
!,~=relpath,endof
t->~t<~!t?t:!t

```

This uses the current working directory as base and cannot be tested on TIO at the moment.

### Example run

**Warning:** This will alter your file system.

```
$ sudo julia --quiet
julia> function test(target,base)
       mkpath(base)
       cd(base)
       shorten(target)
       end
test (generic function with 1 method)
julia> !,~=relpath,endof
(relpath,endof)

julia> shorten = t->~t<~!t?t:!t
(::#1) (generic function with 1 method)

julia> test("/home/user/mydir/myfile","/home/user")
"mydir/myfile"

julia> test("/var/users/admin/secret/passwd","/var/users/joe/hack")
"../../admin/secret/passwd"

julia> test("/home/user/myfile","/tmp/someplace")
"/home/user/myfile"

julia> test("/dir1/dir2","/dir1/dir2/dir3/dir4")
"../.."

julia> test("/dir1/dir2","/dir1/dir2")
"."

```

## Alternate version, 35 bytes (dyadic)

```
^,~=relpath,endof
t-b=~t<~t^b?t:t^b

```

This takes the base directory as input, so it can be tested without modifying the file system.

Try it online!
> 7 votes

# Answer
## JavaScript (ES6), ~~107~~ 106 bytes

Takes the absolute path `a` and the current path `c` in currying syntax `(a)(c)`.

```
a=>c=>(A=a.split`/`,s='',c.split`/`.map(d=>!s&A[0]==d?A.shift():s+='../'),s+=A.join`/`)[a.length]?a:s||'.'

```

### Test cases

```
let f =

a=>c=>(A=a.split`/`,s='',c.split`/`.map(d=>!s&A[0]==d?A.shift():s+='../'),s+=A.join`/`)[a.length]?a:s||'.'

console.log(f
  ('/home/user/mydir/myfile')
  ('/home/user')
);

console.log(f
  ('/var/users/admin/secret/passwd')
  ('/var/users/joe/hack')
);

console.log(f
  ('/home/user/myfile')
  ('/tmp/someplace')
);

console.log(f
  ('/dir1/dir2')
  ('/dir1/dir2/dir3/dir4')
);

console.log(f
  ('/dir1/dir2')
  ('/dir1/dir2')
);
```
> 9 votes

# Answer
# Retina, ~~85~~ ~~83~~ 82 bytes

*1 byte saved thanks to @MartinEnder*

```
^(..+)(.*;)\1
%$2
(%?)(.*);(.*)
$1$3;$2
\w+(?=.*;)
..
%;/

;
/
.*//
/
%/?|/$

^$
.

```

Try it online!
> 8 votes

# Answer
# ES6 (Node.js REPL), ~~56~~, ~~54~~, ~~46~~, 45 bytes

* Use empty string, instead of "." to denote the current directory (on input), -1 byte
* Borrowed the `[f.length]` trick from @Arnauld's answer, -6 bytes
* Use the current directory instead of an explicit directory parameter, -2 bytes
* Removed superfluous parentheses, -2 bytes

**Golfed**

```
f=>(r=path.relative("",f))[f.length]?f:r||"."

```

**Test**

```
> F=f=>(r=path.relative("",f))[f.length]?f:r||"."
[Function: F]

> F("/home/user/mydir/myfile")
'mydir/myfile'

> F("/var/users/admin/secret/passwd")
'../../admin/secret/passwd'

> F("/home/user/myfile")
'/home/user/myfile'

> F("/dir1/dir2")
'../..'

> F("/dir1/dir2")
'.'

```
> 5 votes

# Answer
# Python 2, ~~135~~ 144 bytes

```
i=0
a,c=input()
b,d=a.split('/')*(a!=c),c.split('/')
while b[:i+1]==d[:i+1]:i+=1
print'.'[i:]or min('/'.join(['..']*len(d[i:])+b[i:]),a,key=len)

```

Try it Online!

Kind of long, but I wanted to do a solution without built-in path functions.

**Edit:** 9 bytes added to account for test case provided by Nathan Merrill
> 4 votes

# Answer
# Zsh \+ realpath, 58 bytes

```
r=`realpath -m --relative-to=$*`
(($#2<$#r))&&r=$2
echo $r

```

Try it online!

### Bash version, 62 bytes

```
r=`realpath -m --relative-to=$*`
((${#2}<${#r}))&&r=$2
echo $r

```

Try it online!
> 3 votes

# Answer
## Python 3 – 53 bytes

Using `os.path`:

```
import os
lambda x:min(x,os.path.relpath(x),key=len)

```

Full program (61 bytes):

```
import os
x=input();print(min(x,os.path.relpath(x),key=len))

```
> 2 votes

# Answer
# PHP, 204 Bytes

```
[,$l,$p]=$argv;$z=($d=array_diff_assoc)($y=($w=explode)("/",$p),$x=$w("/",$l));$m=str_pad("",3*count($z)-1,"../");$j=join("/",$r=$d($x,$y));echo$l!=$p?strlen($u=$m&&$j?"$m/$j":$m.$j)<strlen($l)?$u:$l:".";

```

Testcases

Expanded

```
[,$l,$p]=$argv;
$z=($d=array_diff_assoc)($y=($w=explode)("/",$p),$x=$w("/",$l));
$m=str_pad("",3*count($z)-1,"../");
$j=join("/",$r=$d($x,$y));
echo$l!=$p
    ?strlen($u=$m&&$j?"$m/$j":$m.$j)<strlen($l)
      ?$u
      :$l
    :".";

```

if an Output `../../` instead `of ../..` is allowed it can be shorten to 175 Bytes

```
[,$l,$p]=$argv;$z=($d=array_diff_assoc)($y=($w=explode)("/",$p),$x=$w("/",$l));echo$l!=$p?strlen($m=str_pad("",3*count($z),"../").join("/",$r=$d($x,$y)))<strlen($l)?$m:$l:".";

```
> 1 votes

# Answer
# C# - 66 bytes

Using a .NET builtin and forcing to be a valid path:

```
(f,t)=>f==t?".":new Uri("/"+t).MakeRelativeUri(new Uri("/"+f))+"";

```

Where `f`,`t` and output are `string`.

Try it online!
> 0 votes

---
Tags: code-golf, string, file-system
---


title: Restricted powers of two

text:
# Question
Title: Restricted powers of two
# Challenge

Given a number `x`, output the first `x` powers of two, starting with 2¹ (2).

### Example

```
2   2 4
3   2 4 8
1   2
6   2 4 8 16 32 64

```

You may output numbers separated by non-numerical characters. You may not just output them mashed together like `248163264128`.

# Rules

* In your code, you may only use the number `2`. You may not use any other numbers, either as ASCII characters or numeric literals in any base.
    + You may not use character literals as integers to bypass this rule.
* You may not use your language's built-in exponentiation function, operator, or similar. You must implement the exponent yourself.
    + You may not use bit shifting operators.
    + You may not use operations that are equivalent to bit shifting.
* Standard loopholes are disallowed.
* This is , shortest answer wins. However, it will not be selected.

# Answer
# Haskell, 20 bytes

```
(`take`iterate(*2)2)

```

Try it online!

3 bytes longer than the unrestricted:

```
f n=map(2^)[1..n]

```
> 2 votes

# Answer
## Alice, 16 bytes

```
t/O<\*2Hw&
k\i.@

```

Try it online!

### Explanation

This uses the `w&...k` looping technique explained in this answer.

```
t    Decrement the implicit zero on top of the stack to give -1 to initialise
     the product for later.
/    Reflect to SE. Switch to Ordinal.
i    Read all input as a string.
     Bounce off bottom boundary, move NE.
<    Set the horizontal component of the IP direction to west, i.e. move NW.
     Bounce off top boundary, move SW.
i    Try reading more input. Just pushes an empty string.
     Bounce off bottom boundary, move NW.
/    Reflect to W. Switch to Cardinal.
t    Implicitly discard the empty string and convert the actual input to its
     numerical value N. Decrement it to get N-1.
     IP wraps around to the last column.
&w   Repeat the following bit N times.
  H    Take the absolute value of the top of the stack. This is only
       relevant for the first iteration, because we initialised the product
       to -1 instead of 1.
  2*   Double the current product.
  \    Reflect to SW. Switch to Ordinal.
  .    Duplicate the current product (also converts it to a string, but it
       will be converted back by the H).
       Bounce off bottom boundary, move NW.
  O    Output the current product as a string with a trailing linefeed.
       Bounce off top boundary, move SW.
  \    Reflect to W. Switch to Cardinal.
k    End of loop.
     IP wraps around to the last column.
@    Terminate the program.

```
> 1 votes

# Answer
# Cheddar, 26 bytes

```
n->2/2|>n=>n->[n]*n/(*)

```

Takes n as art generated range \[1, n\], maps (`=>`) It over \[n\]\*n (array of n n times over multiplication)

No TIO link because cheddar on TIO is outdated.
> 1 votes

# Answer
# Jelly, ~~5~~ 4 bytes

```
2ṁ×\

```

Try it online!

### How it works

```
2ṁ×\  Main link. Argument: n

2ṁ    Mold; reshape [2] as [1, ..., n], generating an array of n 2's.
  ×\  Take the cumulative product.

```
> 1 votes

# Answer
# Brain-Flak, 44 bytes

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

```

Try it online!

Explanation:

```
#Push negative(input * 2)
(([{}]){}

  #And push a 2 underneath it
  <(()())>
)

#While True:
{

    #Pop the top of the stack off
    ({}

       #And double the number underneath it
       <((({})){})>

    #Then push the former top of the stack + 2
    ()())

#Endwhile
}

#Pop two elements, implicitly display stack
{}{}

```
> 1 votes

# Answer
# Octave, 23 bytes

```
@(x)cumprod(~(2/2:x)+2)

```

Try it online!

Returns cumulative product of repeated 2s.
> 1 votes

# Answer
## JavaScript (ES6), 35 bytes

```
x=>[...Array(x)].map(_=>p+=p,p=x/x)

```

Using no digits at all.
> 1 votes

# Answer
# SOGL, 6 bytes

```
2.{t2*

```

Explanation:

```
2       push 2
 .{     repeat input times
   t     output
    2*   multiply by two

```
> 0 votes

# Answer
## Ruby, 29 bytes

```
->n{b=2;n.times{puts b;b*=2}}

```
> 0 votes

# Answer
# Python 2, 31 bytes

```
n=2
exec"print n;n*=2;"*input()

```

Try it online!

This might be the shortest way to do it, restrictions or no. Compare

```
lambda n:[2<<i for i in range(n)]
# 33 bytes, ignoring restrictions

```

Try it online
> 0 votes

# Answer
# CJam, 11 bytes

```
2ri{_p2*}*;

```

Try it online!
> 0 votes

# Answer
## Batch, 80 bytes

```
@set/px=
@set/ap=2/2
@for /l %%i in (%p%,%p%,%x%)do @set/ap+=p&call echo %%p%%

```

Takes input on STDIN, since `%1` would be illegal. Fully illegal version would only be 63 bytes:

```
@set/ap=1
@for /l %%i in (1,1,%1)do @set/ap+=p&call echo %%p%%

```
> 0 votes

---
Tags: code-golf, number, arithmetic, restricted-source
---


title: Are these lists equal?

text:
# Question
Title: Are these lists equal?
As you may very well know python has lists. As you might not know these lists can contain themselves.

```
a = []
a.append(a)

```

Python 2

Python 3

These are cool and there are lots of interesting things you can do with them, however you cannot compare them.

```
a = []
a.append(a)
b = []
b.append(b)
a == b

```

Python 2

Python 3

## Task

Your job is to write a function in Python (or any language that can handle python objects directly) that will take two lists that may contain themselves and compare them.

Two lists are equal if they are the same length and there does not exist sequence of numbers such that indexing both of the lists by that sequence results in two objects that are not equal under this definition of equal. All non-list objects contained in a list will be python integers for simplicity and should be compared with python's builtin equality for integers.

Your program *should not* rely on the recursion depth of python to determine if a list is infinitely deep. That is:

```
def isInfinite(a,b):
 try:
  a==b
  return False
 except RunTimeError:
  return True

```

Is not a valid way of determining if two lists are self referential.

## Testcases

Assumes you define a function `equal`

```
a = []
a.append(a)
b = []
b.append(b)
print(equal(a,b))

```

---

```
True

```

---

```
a = []
b = []
a.append(b)
b.append(a)
print(equal(a,b))

```

---

```
True

```

---

```
a = []
b = []
a.append(1)
a.append(b)
b.append(1)
b.append(a)
print(equal(a,b))

```

---

```
True

```

---

```
a = []
a.append(a)
b = [a]
print(equal(a,b))

```

---

```
True

```

---

```
a = []
b = []
c = []
a.append(b)
b.append(c)
c.append(a)
equal(a,b)

```

---

```
True

```

---

```
a=[1,[2]]
b=[1,[2,[1]]]
a[1].append(a)
b[1][1].append(b[1])

```

---

```
True

```

---

```
a = []
a.append(a)
b = [1]
b.append(a)
c = [1]
c.append([c])
print(equal(b,c))

```

---

```
False

```

---

```
a = []
b = []
a.append(1)
a.append(b)
b.append(a)
b.append(1)
print(equal(a,b))

```

---

```
False

```

---

```
a = []
b = []
a.append(a)
b.append(b)
b.append(b)
print f(a,b)

```

---

```
False

```

# Answer
# Python 2, 94 bytes

```
g=lambda c,*p:lambda a,b:c in p or all(map(g((id(a),id(b)),c,*p),a,b))if a>[]<b else a==b
g(0)

```

Try it online!

An improvement on isaacg's very clever solution of storing the `id` pairs of lists being processed and declaring them equal if the same comparison comes up on a lower level.

The recursive step `all(map(...,a,b))` says that `a` and `b` are equal if all corresponding pair of elements in them are equal. This works nicely to reject unequal-length because `map` pads the shortest list with `None`, unlike `zip` which truncates. Since none of the actual lists contain `None`, these padded lists will always be rejected.
> 9 votes

# Answer
# Python, ~~233~~ ~~218~~ ~~197~~ 217 bytes

```
d=id
def q(a,b,w):
 w[(d(a),d(b))]=0
 if d(a)==d(b):return 1
 if(a>[]and[]<b)-1:return a==b
 if len(a)!=len(b):return 0
 for x,y in zip(a,b):
  if((d(x),d(y))in w or q(x,y,w))-1:return 0
 return 1
lambda a,b:q(a,b,{})

```

The anonymous function on the last line performs the desired function.

This is still in the process of being golfed, I just wanted to show that this is possible.

Essentially, we put an entry in w if we're working on a given check. Two things are equal if they're the same object, if they're not lists, and they're equal, or if all their elements are either equal or being worked on.
> 5 votes

---
Tags: code-golf, decision-problem, python, recursion
---


# Question
Title: Finding the center point between two points on a plane
### Challenge:

To take two points on the plane and figure out the position of the point that's a) on the line that connects them, and b) equally distant from each of the original points.

### Example:

```
(0,0), (3,3) -> (1.5,1.5)

(-1,-1), (1,1) -> (0,0)

(-7,3), (2,-2) -> (-2.5,0.5)

(3, 1), (-5,9) -> (-1,5)

```

### Rules:

* The input and output can be a tuple, array, list, or any other type of sequence.
* There must be two inputs, each representing a point.
* The output has to support floating point numbers.

Shortest solution in bytes wins.

# Answer
# Jelly, ~~7~~ 2 bytes

-5 bytes (ha ha, yes I am an idiot) thanks to FryAmTheEggman!

```
+H

```

Takes two lists each of length d and returns one list of length d where d is the dimensions of the Cartesian space (question is posed for 2 dimensions, but should work for any d).

**Try it online!**

### How?

```
+H - Main link: a, b (lists of coordinates)
+  - add (vectorises across the dimensions)
 H - halve (vectorises across the result)

```
> 4 votes

# Answer
# Mathematica, 4 bytes

```
Mean

```

Works on lists of vectors: for example, `Mean[{{-7, 3}, {2, -2}}]` returns `{-5/2, 1/2}`. (If the input consists of floating-point numbers, so will the output.)
> 4 votes

# Answer
# Python 3, ~~39~~ 35 bytes

```
lambda*x:[sum(a)/2for a in zip(*x)]

```

Try it online!
> 2 votes

# Answer
## Haskell, ~~22~~ 19 bytes

```
zipWith$((/2).).(+)

```

Can be called with `(zipWith$((/2).).(+)) (p1::[a]) (p2::[a])` where `a` is any type deriving `Fractional`. Works in arbitrary dimensions.
> 1 votes

# Answer
# TI-BASIC, 8 bytes

```
.5(L₁+L₂

```

Takes input on List 1 and List 2. Works for all dimensions.
> 1 votes

# Answer
## Julia 0.6, 13 bytes

```
(x->x/2)∘(+)

```
> 1 votes

# Answer
# Common Lisp, ~~70~~ ~~54~~ 49 bytes

*Thanks to @Julian Wolf for helping to save a bunch of bytes!*

```
(defun f(a b)(mapcar(lambda(c d)(/(+ c d)2))a b))

```

Try it online!
> 0 votes

# Answer
# JavaScript , 30 bytes

valid for any number of dimensions

```
a=>b=>a.map((c,i)=>(c+b[i])/2)

```

Try it online!
> 0 votes

# Answer
# R, 22 bytes

As an unnamed function that takes 2 vectors as parameters. Simply returns the mean of input vectors the same as a lot of answers.

```
function(a,b)((a+b)/2)

```

Try it online!

And 16 bytes using the pryr library

```
pryr::f((a+b)/2)

```
> 0 votes

# Answer
## Python \+ NumPy, 18 bytes

```
lambda a,b:(a+b)/2

```

Works in two dimensions for points inputted as imaginary numbers, or (since OP specifies that inputs must be taken as sequences) in arbitrary dimensions for points inputted as NumPy arrays.

Try it online!
> 0 votes

# Answer
# Math.JS, 14 bytes

```
f(a,b)=(a+b)/2

```

Creates function `f` which takes 2 One Dimensional Matricies as input.

As expected, this just adds the two, then halfs the result.

Try it!
> 0 votes

# Answer
# Julia, 13 bytes

```
a->b->(a+b)/2

```

Call with currying syntax, i.e. `(a->b->(a+b)/2)([1,2])([3,4])`.
> 0 votes

# Answer
# Python + NumPy, 17 bytes

```
lambda a:sum(a)/2

```

A slightly less boring version of the other python answer. Takes args as 1 numpy array, containing both pairs.

Try it online!
> 0 votes

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


# Question
Title: Operator that combines sum, product and difference between two numbers
## Challenge:

There's a silly puzzle circulating on social networks that reads:

```
8 + 2 = 16106
5 + 4 = 2091
9 + 6 = ?

```

Implement a function or operator that, when given two positive integer numbers `x` and `y` such that `x > y > 0`, yields the correct answer as an **integer**, where the answer's digits are the digits of `x * y` followed by the digits of `x + y` followed by the digits of `x - y`. Very simple.

## Rules:

* Standard loopholes are disallowed.
* This is so shortest code in bytes wins.
* Input data validation is **not** required. This program may crash or return garbage when given invalid input.
* You're allowed to use numeric functions and operators (including integer and floating point, math library functions, and other functions that accept and return numbers).
* You're allowed to use a function that returns the number of digits of a number, if applicable.
* You're **not** allowed to use strings or any kind of concatenation anywhere in your code.
* The result may be returned or pushed to the stack, whichever applies in the language. The result must be an integer number, not a string.

## Sample code:

**Dyalog APL:**

The following code creates a dyadic operator named `X`.

> X←{(⍺-⍵)+((⍺+⍵)×10\*1+⌊10⍟⍺-⍵)+⍺×⍵×10\*(2+⌊10⍟⍺+⍵)+⌊10⍟⍺-⍵}

Explanation:

* In APL, you evaluate from right to left.
* `⍺ and ⍵` are the left and right operand, respectively
* `⌊10⍟⍺-⍵` reads: `floor of log10(⍺-⍵)`. First performs substraction then logarithm then floor. From right to left. log10 is done in order to count the digits of `⍺-⍵` (you must sum 1 afterwards).
* `⍺×⍵×10*(...)` reads: `10 to the (...)th power, multiplied by ⍵, multiplied by ⍺`
* Hence, `⍺×⍵×10*(2+⌊10⍟⍺+⍵)+⌊10⍟⍺-⍵` is the product, shifted to the left by the sum of the number of digits of the sum and the difference. Multiplying by a power of 10 will shift an integer to the left.
* `((⍺+⍵)×10*1+⌊10⍟⍺-⍵)` is the sum, shifted to the left by the number of digits of the difference.
* `(⍺-⍵)` is the difference. No shifting is necessary here.
* `X←{...}` is how you define an operator in APL.

Examples:

```
      8 X 2
16106
      5 X 4
2091
      9 X 6
54153

```

**GNU dc:**

The following code creates a macro named `a`:

```
[sysx10lxly-dseZdsclxly+dsd+Z1+^lxly**10lc^ld*+le+]sa

```

Explanation:

* `sx` and `sy` pop an element from the stack and save it on the registers `x` and `y`, respectively.
* `lx` and `ly` load an element from registers `x` and `y` respectively and push it to the stack.
* `d` duplicates the last element in the stack.
* `^` computes the power of two numbers.
* `Z` pops a number and returns its number of digits. This is done because `dc` has no logarithm function.
* `[...]sa` stores a macro in register `a`. `la` loads it. `x` executes the macro at the top of the stack.

Examples:

```
8 2 laxn
16106
5 4 laxn
2091
9 6 laxn
54153

```

# Answer
> 10 votes
# JavaScript (ES7), ~~63~~ ~~61~~ 59 bytes

Saved 4 bytes thanks to Neil.

```
(a,b)=>[a*b,a+b,a-b].reduce((p,c)=>p*10**-~Math.log10(c)+c)

```

```
<input id=a type=number oninput="c.innerText=((a,b)=>[a*b,a+b,a-b].reduce((p,c)=>p*10**-~Math.log10(c)+c))(+a.value,+b.value)">
<input id=b type=number oninput="c.innerText=((a,b)=>[a*b,a+b,a-b].reduce((p,c)=>p*10**-!Math.log10(c)+c))(+a.value,+b.value)">
<p id=c>
```

# Answer
> 8 votes
# C, ~~79~~ 75 bytes

*Thanks to @G B for saving 4 bytes!*

```
#define X for(c=1;(c*=10)<=a
c,d;f(a,b){X+b;);d=c*a*b+a+b;X-b;);a=d*c+a-b;}

```

Try it online!

# Answer
> 6 votes
# Bash, 66

* 2 bytes saved thanks to @chepner.

```
f()(s=$[$1+$2]
d=$[$1-$2]
echo $[($1*$2*10**${#s}+s)*10**${#d}+d])

```

Try it online.

# Answer
> 5 votes
# EXCEL, 61 Bytes

```
=A1-B1+(A1+B1)*10^LEN(A1-B1)+A1*B1*10^(LEN(A1-B1)+LEN(A1+B1))

```

Excel, 18 Bytes not valid

```
=A1*B1&A1+B1&A1-B1

```

# Answer
> 5 votes
# Stacked, 36 bytes

```
,@A$(*+-){!A...n!}"!{%y#'10\^x*y+}#\

```

Try it online!

Previously: `,@A$(-+*){!A...n!}"!:inits$#'"!$summap:pop@.10\^1\,\*sum`

I'm going to try to squeeze out a byte or two before writing an explanation. (`#'` = size of, and `"` is "do on each", no strings attached here.)

Noncompeting at 26 bytes: `$(*+-)#!!:{%y#'10\^x*y+}#\`.

# Answer
> 5 votes
# TI-Basic, ~~34~~ 33 bytes

```
Prompt A,B
A-B+(A+B)<sub>10</sub>^(1+int(log(A-B
Ans+AB<sub>10</sub>^(1+int(log(Ans

```

# Answer
> 4 votes
# GNU dc, 36

Defines a macro `m` that takes the top two members of the stack, applies the macro and leaves the result on the stack (as per the example in the question):

```
[sadsbla-dZAr^lalb+*+dZAr^lalb**+]sm

```

Try it online.

# Answer
> 3 votes
# Perl 6,  ~~81 61~~  58 bytes

```
->\x,\y{($/=($/=x- y)+(x+y)*({10**$++}...*>$/).tail)+x*y*({10**$++}...*>$/).tail}

```

Try it

```
->\x,\y{(x*y,x+y,x- y).reduce:{$^a*10**Int(1+log10($^b))+$b}}

```

Try it

```
->\x,\y{[[&({$^a*10**Int(1+$^b.log10)+$b})]] x*y,x+y,x- y}

```

Try it

# Answer
> 3 votes
# Jelly, 27 bytes

```
+,ạ,.1Fl⁵Ḟ‘€Ṛ+\⁵*
ạ,+,×Fæ.ç

```

Defines a dyadic link / function, callable with `ç`. Takes two integers as input and returns an integer. It has the added bonus of being able to take x`<`y or x`>`y by using absolute difference.

Try it online!

Explanation:

```
+,ạ,.1Fl⁵Ḟ‘€Ṛ+\⁵* -- Create link which computes what order of magnitude
                        to multiply the difference, sum, and product by
ạ,+,×Fæ.ç         -- Main link, applies this using dot product

```

Details:

```
+,ạ,.1Fl⁵Ḟ‘€Ṛ+\⁵* -- Create dyadic like which does the following:
       l⁵Ḟ‘       -- Create operation which computes number of digits
                       (log base 10 (⁵ is the literal 10), floored, incremented)
           €      -- Apply this to each element in
+,ạ,.1F           -- ... the list [sum,difference,.1]
            R     -- Reverse the list
             +\   -- Add up first n elements to get list.
               ⁵* -- Raise 10 (⁵ is literal 10) to the power of each element

ạ,+,×Fæ.ç         -- Main link, applies above link
ạ,+,×F            -- The list [difference, sum, product]
      æ.          -- Dot product (multiply corresponding elements) with
        ç         -- The above link.

```

# Answer
> 2 votes
# PHP, ~~79~~ 75 bytes

two versions:

```
[,$a,$b]=$argv;echo(10**strlen($s=$a+$b)*$a*$b+$s)*10**strlen($d=$a-$b)+$d;
[,$a,$b]=$argv;echo(10**strlen($a+$b)*$a*$b+$a+$b)*10**strlen($a-$b)+$a-$b;

```

takes input from command line arguments; run with `-r`.

I guess `strlen` qualifies as "function that returns the number of digits",
although it uses the number as a string. Let me know if not.

# Answer
> 2 votes
# C (gcc), 70 bytes

```
#define _ for(c=1;a+b>=(c*=10););d=c*d+a-(b=-b);
c,d;f(a,b){d=a*b;_ _}

```

Try it online!

based on Steadybox answer, putting everything in a macro to golf it a little more.

(Note: assigning the result to `d` instead of `a` works, unexpectedly. I had a look at the generated assembly code and it seems to be ok.)

# Answer
> 2 votes
# Haskell, 54 bytes

```
a%0=a
a%b=10*a%div b 10+mod b 10
a#b=(a*b)%(a+b)%(a-b)

```

The puzzle is implemented via an infix function `#`, e.g. `8#2 = 16106`. The other function, `%`, defines base-10 concatenation (assuming the RHS is greater than 0).

# Answer
> 2 votes
# Dyalog APL, 31 bytes

`{a⊥⍨10*1+⌊10⍟a←(⍺×⍵)(⍺+⍵)(⍺-⍵)}`

based on the sample APL code from the problem statement

# Answer
> 1 votes
# PHP, 87 Bytes

```
[,$a,$b]=$argv;echo($s=$a-$b)+($t=$a+$b)*10**($l=strlen($s))+$a*$b*10**($l+strlen($t));

```

and a not valid solution for 37 Bytes

```
[,$a,$b]=$argv;echo$a*$b,$a+$b,$a-$b;

```

# Answer
> 1 votes
# Ruby, 61 bytes

```
->a,b{[a*b,a+b,a-b].reduce{|x,y|z=y;x*=10while(z>z/=10);x+y}}

```

Which suspiciously looks a lot like this Javascript answer, but without using a logarithm.

# Answer
> 1 votes
# R (3.3.1), 104 bytes

```
function(x,y)Reduce(function(p,q)p*10^(floor(log10(q)+1))+q,lapply(c(`*`,`+`,`-`),function(z)z(x,y)),0)

```

returns an anonymous function.

This is my first golfing attempt, so any feedback is appreciated.

# Answer
> 1 votes
# Python, 92 91 Chars

```
def g(x,y):
    l=lambda x,i=0:l(x/10,i+1)if x else 10**i
    a=x-y
    a+=(x+y)*l(a)
    return x*y*l(a)+a

```

Thanks to Wizards suggestion;)

# Answer
> 0 votes
## REXX, 70 bytes

```
f:arg a b
c=a-b
c=(a+b)*10**length(c)+c
c=a*b*10**length(c)+c
return c

```

Of course, the native way would be much shorter:

```
f:arg a b
return a*b||a+b||a-b

```

# Answer
> 0 votes
## Python 2.7, ~~109~~ 96 bytes

```
import math
a=lambda n:10**int(math.log10(10*n))
b,c=input()
d=b-c+(b+c)*a(b-c)
print d+b*c*a(d)

```

Corrected after following rules of contest. Credits to mbomb007 for bringing down the code from 109 bytes to 96 bytes

# Answer
> 0 votes
## PowerShell, 88 Bytes

```
param($x,$y)$l=2;if(($a=$x+$y)-gt9){$l++};($x*$y)*[math]::Pow(10,$l)+$a*10+$x-$y

```

PowerShell does not have a to the power operator which does not help. Also can't count the length of an integer unless you count it as a string, which we can not do, so I check to see if it is `-gt` 9 to get know the length. Likely could be more terse but I have to get back to work.

# Answer
> 0 votes
# , 25 bytes

```
X=.10#.[:;10#.inv&.>*;+;-

```
1. `*;+;-` Box the results of each operation.
2. `10#.inv&.>` Convert each result into an array of base-10 digits. (`inv` is `^:_1`)
3. `[:;` Unbox and join the arrays.
4. `10#.` Convert array of base-10 digits into an integer.
5. `X=.` define the above as the operator `X`.

Results:

```
   8 X 2
16106
   5 X 4
2091
   9 X 6
54153

```

# Answer
> 0 votes
# Mathematica, 67 bytes

```
c=Ceiling;l=Log10;#-#2+(#+#2)10^(c@l[#-#2]/. 0->1)+10^c@l[2#]10#2#&

```

Takes `x-y`, then takes the log10 of `x-y`, rounds it up, calculates 10 to the power of that and then multiplies it by `x+y`. But we also need to consider `log10(x-y)` being 0, so we replace 0 with 1. Then we take the log10 of `2x`, rounded up, plus 1, and find 10 to the power of that. Multiply that by `xy`, and add that on.

# Answer
> 0 votes
# 05AB1E, ~~23~~ ~~22~~ 16 bytes

```
-Dg°¹²+*Dg°¹²**O

```

Try it online!

We could have saved a few bytes if we'd been allowed to use strings in the program (but not in calculations) by looping over a string containing the operations `"-+*"`, as the code performed for each operation is the same.
Of course, if we'd been allowed to use concatenation we'd saved a lot more.

# Answer
> 0 votes
## R, 64 bytes

```
x=scan();(b=(a=diff(-x))+10^nchar(a)*sum(x))+10^nchar(b)*prod(x)

```

Usage:

```
> x=scan();(b=(a=diff(-x))+10^nchar(a)*sum(x))+10^nchar(b)*prod(x)
1: 8 2
3:
Read 2 items
[1] 16106

```

---
Tags: code-golf, number, arithmetic
---


title: Transpile these ES6 arrow functions!

text:
# Question
Title: Transpile these ES6 arrow functions!
The ECMAScript 6 standard added many new features to the JavaScript language, including a new arrow function notation.

Your task is to write a basic ES6-to-ES5 transpiler. Given only an ES6 arrow function as input, output its ES5-compatible counterpart.

It's ! May the shortest program in bytes win!

---

## The Basics

An arrow function looks like this:

```
(a, b, c) => { return a + b - c }

```

And its equivalent ES5 function expression looks like this:

```
function(a, b, c) { return a + b - c }

```

In general, you can copy the body of the function (everything between the curly braces) verbatim.

---

## Implicit Return Statement

Instead of a body with curly braces, a single expression can be used; the result of this expression is then returned.

```
(a, b, c) => a + b - c

function(a, b, c) { return a + b - c }

```

Another example:

```
(a, b, c) => (a + 1, b - 2 * c / 3)

function(a, b, c) { return (a + 1, b - 2 * c / 3) }

```

Again, you may simply copy the expression verbatim - BUT take care that you do not output a line break between it and the `return` keyword to avoid automatic semicolon insertion!

---

## One Argument

Parentheses are optional if one argument is provided.

```
foo => { return foo + 'bar' }

function(foo) { return foo + 'bar' }

```

---

## Whitespace

Finally, you must be able to account for any number of whitespace characters (space, tab, newline) before or after parentheses, variables, commas, curly braces, and the arrow\*.

```
 ( o   ,  O
     , _    )=>{

    return                                     "Please don't write code like this."
}

```

Whether or not you choose to preserve whitespace in the output is up to you. Keep 'em, remove 'em, or add your own - just make sure it's valid code!

<sub>\*It's technically illegal for an arrow to come immediately after a line break, but I doubt this fact would help you. :)</sub>

---

## A quick way to validate your output:

Enter `var foo = <your output>; foo()` into your browser console. If it doesn't complain, you're probably on the right track.

---

## More rules for the wizards:

* Input is a syntactically valid ES6 arrow function.
* Assume the body of the function is ES5-compatible (and doesn't reference `this`, `super`, `arguments`, etc). This also means that the function will never contain another arrow function (but you may not assume that "=\>" will never occur within the body).
* Variable names will only consist of basic Latin letters, `$` and `_`.
* You need not transpile ES6 features that aren't listed above (default parameters, rest operator, destructuring, etc).
* The space after a `return` statement is optional if followed by `(`, `[`, or `{`.
* It isn't strictly necessary to match my test cases exactly - you can modify the code as much as you need if it'll help lower your byte count. Really, as long as you produce a syntactically valid, functionally equivalent ES5 function expression, you're golden!

# Answer
## JavaScript (ES6), ~~123~~ ~~110~~ ~~100~~ 97 bytes

*Saved 3 bytes thanks to @Neil*

```
s=>s.replace(/\(?(.*?)\)?\s*=>\s*([^]*)/,(_,a,b)=>`function(${a})${b[0]=='{'?b:`{return ${b}}`}`)

```

Assumes the input is a syntactically valid arrow function and nothing else. Correctly handles the case `a =>\na`, though not handling is not any shorter as far as I can tell.

Output when the code is run through itself:

```
function(s){return s.replace(/\(?(.*?)\)?\s*=>\s*([^]*)/,(_,a,b)=>`function(${a})${b[0]=='{'?b:`{return ${b}}`}`)}

```

---

I can save 9 bytes with a possibly invalid format:

```
s=>s.replace(/\(?(.*?)\)?\s*=>\s*({?)([^]*?)}?$/,(_,a,z,b)=>Function(a,z?b:'return '+b))

```

Output for itself:

```
function anonymous(s) {
return s.replace(/\(?([^=)]*)\)?\s*=>\s*({?)([^]*?)}?$/,(_,a,z,b)=>Function(a,z?b:'return '+b))
}

```

(Specifically, the `function anonymous` is what I'm worried about.)
> 5 votes

# Answer
# Retina, ~~86~~ ~~80~~ 79 bytes

```
^([^(]*?)=
($1)=
s(`\s*$

>\s*(.*[^}])$
>{return $1}
)`(.*?)=>(.*)
function$1$2

```

Try it Online!

*Saved a byte thanks to Neil*

*Saved 6 bytes with help from ETHproductions*

**Edit:** Fixed for possibility of newlines in function body.

75 byte solution assuming the input won't contain `§`: Try it Online!
> 2 votes

# Answer
# PHP, 112 bytes

```
preg_match("#\(??(.*)\)?=>(\{?)(.*$)#U",$argn,$m);echo"function($m[1])",trim($b=$m[3])[0]=="{"?$b:"{return $b}";

```

takes input from STDIN; run with `-R`
> 0 votes

---
Tags: code-golf
---


title: Golfing end-to-end encryption

text:
# Question
Title: Golfing end-to-end encryption
> ~~This challenge carries a bounty of 200 points for the first to answer and remain unbeaten for at least 3 days.~~ Claimed by user3080953.

There's a lot of talk lately about end-to-end encryption, and pressure on companies to remove it from their products. I'm not interested in the rights-and-wrongs of that, but I wondered: how short can code be that would get a company pressured into not using it?

The challenge here is to implement a Diffie Hellman key exchange between two networked systems, then allow the users to communicate back-and-forth using the generated symmetric key. For the purpose of this task, no other protections are required (e.g. no need to cycle the key, verify identities, protect against DoS, etc.) and you can assume an open internet (any ports you listen on are available to everyone). Use of builtins is allowed *and encouraged!*

You may choose one of two models:

* A server and a client: the client connects to the server, then server or client can send messages to the other. Third-parties in between the two must be unable to read the messages. An example flow could be:
    1. User A launches server
    2. User B launches client and directs it to user A's server (e.g. via IP/port), the program opens a connection
    3. User A's program acknowledges the connection (optionally asking the user for consent first)
    4. User B's program begins generation of a DH secret, and sends the required data (public key, prime, generator, anything else your implementation needs) to User A
    5. User A's program uses the sent data to complete generation of the shared secret and sends back the required data (public key) to User B. From this point, User A can enter messages (e.g. via stdin) which will be encrypted and sent to User B (e.g. to stdout).
    6. User B's program completes generation of the shared secret. From this point, User B can send messages to User A.
* Or: A server with two clients connected to it: each client talks to the server, which forwards their message to the other client. The server itself (and any third-parties in between) must be unable to read the messages. Other than the initial connection, the process is the same as that described in the first option.

### Detailed rules:

* You can provide a single program, or multiple programs (e.g. server & client). Your score is the total code size across all programs.
* Your program must be theoretically capable of communicating over a network (but for testing, localhost is fine). If your language of choice doesn't support networking, you can combine it with something that does (e.g. a shell script); in this case your score is the total code size across all languages used.
* The Diffie Hellman key generation can use hard-coded "p" and "g" values.
* The generated shared key must be at least 1024 bits.
* Once the key is shared, the choice of symmetric-key encryption is up to you, but you must not pick a method which is currently known to have a practical attack against it (e.g. a caesar shift is trivial to reverse without knowledge of the key). Example permitted algorithms:
    + AES (any key size)
    + RC4 (theoretically broken, but no practical attacks that I can find mention of, so it's allowable here)
* Users A and B must both be able to send messages to each other (two-way communication) interactively (e.g. reading lines from stdin, continually prompting, or events such as pressing a button). If it makes it easier, you may assume an alternating conversation (i.e. after a user sends a message, they must wait for a response before sending their next message)
* Language builtins **are** permitted (no need to write your own cryptographic or networking methods if they're already supported).
* The underlying communication format is up to you.
* The communication steps given above are an example, but you are not required to follow them (as long as the necessary information is shared, and no middle-men are able to calculate the shared key or messages)
* If the details needed to connect to your server are not known in advance (e.g. if it listens on a random port), these details must be printed. You can assume that the IP address of the machine is known.
* Error handling (e.g. invalid addresses, lost connections, etc.) is not required.
* The challenge is code golf, so the shortest code in bytes wins.

# Answer
> 3 votes
# Node.js (372 423+94=517 513 bytes)

## Golfed

Linebreaks added for "readability".

### chat.js (423 419 bytes)

No line breaks

```
[n,c,p]=["net","crypto","process"].map(require);r="rc4",a="create",h="DiffieHellman",z="pipe",w="write",o=128,g=p.argv;s=e=d=0,y=c[a+h](8*o),k=y.generateKeys();v=n.connect(9,g[2],_=>{g[3]&&(v[w](y.getPrime()),v[w](k));v.on("data",b=>{s||(g[3]||(y=c[a+h](b.slice(0,o)),k=y.generateKeys(),v[w](k),b=b.slice(o)),s=y.computeSecret(b),e=c[a+"Cipher"](r,s),p.stdin[z](e)[z](v),d=c[a+"Decipher"](r,s),v[z](d)[z](p.stdout))})})

```

Line breaks

```
[n,c,p]=["net","crypto","process"].map(require);
r="rc4",a="create",h="DiffieHellman",z="pipe",w="write",o=128,g=p.argv;
s=e=d=0,y=c[a+h](8*o),k=y.generateKeys();
v=n.connect(9,g[2],_=>{g[3]&&(v[w](y.getPrime()),v[w](k));
v.on("data",b=>{s||(g[3]||(y=c[a+h](b.slice(0,o)),k=y.generateKeys(),
v[w](k),b=b.slice(o)),s=y.computeSecret(b),e=c[a+"Cipher"](r,s),p.stdin[z](e)[z](v)
,d=c[a+"Decipher"](r,s),v[z](d)[z](p.stdout))})})

```

### echo\_server.js (94 bytes)

```
c=[],require("net").createServer(a=>{c.forEach(b=>{a.pipe(b),b.pipe(a)});c.push(a)}).listen(9);

```

## Ungolfed

Node has built-in networking and crypto capabilities. This uses TCP for networking (because it's simpler than Node's interface for HTTP, and it plays nicely with streams).

I use a stream cipher (RC4) instead of AES to avoid having to deal with block sizes. Wikipedia seems to think it can be vulnerable, so if anyone has any insights into which ciphers are preferred, that would be great.

Run the echo server `node echo_server.js` which will listen on port 9. Run two instances of this program with `node chat.js <server IP>` and `node chat.js <server IP> 1` (the last argument just sets which one sends a prime). Each instance connects to the echo server. The first message handles the key generation, and subsequent messages use the stream cipher.

The echo server just sends everything back to all the connected clients except the original.

### Client

```
var net = require('net');
var crypto = require('crypto');
var process = require('process');
let [serverIP, first] = process.argv.slice(2);

var keys = crypto.createDiffieHellman(1024); // DH key exchange
var prime = keys.getPrime();
var k = keys.generateKeys();
var secret;

var cipher; // symmetric cipher
var decipher;

// broadcast prime
server = net.connect(9, serverIP, () => {
    console.log('connect')
    if(first) {
        server.write(prime);
        console.log('prime length', prime.length)
        server.write(k);
    }

    server.on('data', x => {
        if(!secret) { // if we still need to get the ciphers
            if(!first) { // generate a key with the received prime
                keys = crypto.createDiffieHellman(x.slice(0,128)); // separate prime and key
                k = keys.generateKeys();
                server.write(k);
                x = x.slice(128)
            }

            // generate the secret
            console.log('length x', x.length);
            secret = keys.computeSecret(x);
            console.log('secret', secret, secret.length) // verify that secret key is the same
            cipher = crypto.createCipher('rc4', secret);
            process.stdin.pipe(cipher).pipe(server);
            decipher = crypto.createDecipher('rc4', secret);
            server.pipe(decipher).pipe(process.stdout);
        }
        else {
            console.log('sent text ', x.toString()) // verify that text is sent encrypted
        }
    });
})

```

### Echo server

```
var net = require('net');
clients = [];

net.createServer(socket => {
    clients.forEach(c=>{socket.pipe(c); c.pipe(socket)});
    clients.push(socket);
}).listen(9)

```

Thanks Dave for all the tips + feedback!

# Answer
> 0 votes
# Node.js, ~~638~~ 607 bytes

Now that it's been well and truly beaten (and in the same language), here's my test answer:

```
R=require,P=process,s=R('net'),y=R('crypto'),w=0,C='create',W='write',D='data',B='hex',G=_=>a.generateKeys(B),Y=(t,m,g,f)=>g((c=y[C+t+'ipher']('aes192',w,k='')).on('readable',_=>k+=(c.read()||'').toString(m)).on('end',_=>f(k)))+c.end(),F=C+'DiffieHellman',X=s=>s.on(D,x=>(x+'').split(B).map(p=>p&&(w?Y('Dec','utf8',c=>c[W](p,B),console.log):P.stdin.on(D,m=>Y('C',B,c=>c[W](m),r=>s[W](r+B)),([p,q,r]=p.split(D),r&&s[W](G(a=y[F](q,B,r,B))),w=a.computeSecret(p,B))))));(R=P.argv)[3]?X(s.Socket()).connect(R[3],R[2]):s[C+'Server'](s=>X(s,a=y[F](2<<9))[W](G()+D+a.getPrime(B)+D+a.getGenerator(B)+B)).listen(R[2])

```

Or with wrapping:

```
R=require,P=process,s=R('net'),y=R('crypto'),w=0,C='create',W='write',D='data',B
='hex',G=_=>a.generateKeys(B),Y=(t,m,g,f)=>g((c=y[C+t+'ipher']('aes192',w,k=''))
.on('readable',_=>k+=(c.read()||'').toString(m)).on('end',_=>f(k)))+c.end(),F=C+
'DiffieHellman',X=s=>s.on(D,x=>(x+'').split(B).map(p=>p&&(w?Y('Dec','utf8',c=>c[
W](p,B),console.log):P.stdin.on(D,m=>Y('C',B,c=>c[W](m),r=>s[W](r+B)),([p,q,r]=p
.split(D),r&&s[W](G(a=y[F](q,B,r,B))),w=a.computeSecret(p,B))))));(R=P.argv)[3]?
X(s.Socket()).connect(R[3],R[2]):s[C+'Server'](s=>X(s,a=y[F](2<<9))[W](G()+D+a.
getPrime(B)+D+a.getGenerator(B)+B)).listen(R[2])

```

### Usage

This is a server/client implementation; one instantiation will be the server, and the other the client. The server is launched with a specific port, then the client is pointed to the server's port. DH can take a few seconds to set-up if your machine is low on entropy, so the first messages may be delayed a little.

```
MACHINE 1                       MACHINE 2
$ node e2e.js <port>            :
:                               $ node e2e.js <address> <port>
$ hello                         :
:                               : hello
:                               $ hi
: hi                            :

```

### Breakdown

```
s=require('net'),
y=require('crypto'),
w=0,                                      // Shared secret starts unknown
Y=(t,m,g,f)=>g(                           // Helper for encryption & decryption
  (c=y['create'+t+'ipher']('aes192',w,k=''))
  .on('readable',_=>k+=(c.read()||'').toString(m))
  .on('end',_=>f(k)))+c.end();
X=s=>s.on('data',x=>(x+'').split('TOKEN2').map(p=>
  p&&(w                                   // Have we completed handshake?
    ?Y('Dec','utf8',c=>c.write(p,'hex'),console.log) // Decrypt + print messages
    :                                     // Haven't completed handshake:
     process.stdin.on('data',m=>          //  Prepare to encrypt + send input
       Y('C','hex',c=>c.write(m),r=>s.write(r+'TOKEN2')),(
       [p,q,r]=p.split('TOKEN1'),         //  Split up DH data sent to us
       r&&                                //  Given DH details? (client)
          s.write(
            (a=y.createDiffieHellman(     //   Compute key pair...
              q,'hex',r,'hex')            //   ...using the received params
            ).generateKeys('hex')),       //   And send the public key
       w=a.computeSecret(p,'hex')         //  Compute shared secret
       //,console.log(w.toString('hex'))  //  Print if you want to verify no MITM
))))),
(R=process.argv)[3]                       // Are we running as a client?
  ?X(s.Socket()).connect(R[3],R[2])       // Connect & start chat
  :s.createServer(s=>                     // Start server. On connection:
    X(s,                                  //  Start chat,
      a=y.createDiffieHellman(1024))      //  Calc DiffieHellman,
    .write(                               //  Send public key & public DH details
      a.generateKeys('hex')+'TOKEN1'+
      a.getPrime('hex')+'TOKEN1'+
      a.getGenerator('hex')+'TOKEN2')
  ).listen(R[2])                          // Listen on requested port

```

The only requirement for the tokens is that they contain at least one non-hex character, so in the minified code other string constants are used (`data` and `hex`).

---
Tags: code-golf, networking, encryption
---


title: Working on my Knight moves

text:
# Question
Title: Working on my Knight moves
Hexagonal chess describes a family of chess variants played on a board where the cells are hexagons instead of the traditional squares. There are many such variants; in this challenge we'll be focusing on Gliński's variant, which is the most common.

The board is composed of three colors (so that the same color doesn't share an edge), with the edges of the hexagons facing the players. The board has 11 files, marked by letters `a` through `l` (letter `j` is not used), and 11 ranks (which bend 60° at file `f`). Ranks `1` through `6` each contain 11 cells, rank `7` has 9 cells, rank `8` has 7, and so on. Rank `11` contains exactly one cell: **f11**. (If it helps, think of each rank as making a very wide "V" shape.)

Here is an example picture of the board, with the knight on the center cell. The cells marked with a dot are the legal moves of this particular knight. The knight moves in a similar fashion to "normal" chess, two-down-and-one-over. In hexagonal chess terms, it's an orthogonal move (across an edge), then a diagonal move in the same direction (the closest move to the same color). For example with the knight below, an orthogonal move "up" to the light brown is then accompanied by a diagonal move "up and right" or "up and left" to the nearest light brown.

<sub>*From the public domain via https://commons.wikimedia.org/wiki/File:Glinski\_Chess\_Knight.svg*</sub>

This knight is positioned at **f6** and the legal moves are thus

```
c4, c5, d3, d7, e3, e8, g3, g8, h3, h7, i4, i5

```

### Input

A single input giving the starting cell of our knight. This can be as a single string `"b6"`, as two strings, `"b", "6"`, etc., in any convenient format. The input letters can be uppercase or lowercase -- your choice.

### Output

A list of the valid moves that a knight on that location can make. This can be as an array of strings, a single string with an unambiguous and consistent delimiter, separate strings by newlines, etc., whatever is most convenient. The output does not necessarily need to be in sorted order, and can be in either uppercase or lowercase -- your choice.

### Rules

* Assume no other pieces are on the board or interfere with the moves. We're focusing on just the knight.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an online testing environment so other people can try out your code!
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

### Examples

```
b6
a3, c4, d5, d9, e7, e8

f6
c4, c5, d3, d7, e3, e8, g3, g8, h3, h7, i4, i5

f11
d8, e8, g8, h8

i1
f2, f3, g4, h4, l2, k3

```

# Answer
> 11 votes
## JavaScript (ES6), 184 bytes

Takes the file `F` as a character and the rank `R` as an integer in currying syntax `(F)(R)`. Returns an array of strings.

```
F=>R=>[...'100124566542'].map((X,i)=>(X-=3-(x=(s='abcdefghikl').search(F)))-7<(Y=('9641001469'[i]||10)-(A=Math.abs)(x-5)+17-2*R)&X+Y>3&X+16>Y&X+Y<27&&s[X]+(22-Y-A(X-5))/2).filter(n=>n)

```

### How?

**Step #1: convert file/rank to Cartesian coordinates**

We convert the hexagonal chess coordinates to Cartesian coordinates ***(x, y)*** with ***x*** in **\[0 .. 10\]** and ***y*** in **\[0 .. 20\]**:

```
      00 01 02 03 04 05 06 07 08 09 10
   +----------------------------------
00 |                f11                     F = file (letter)
01 |             e10   g10                  R = rank in [1 .. 11]
02 |          d09   f10   h09
03 |       c08   e09   g09   i08            F | a b c d e f g h i k l
04 |    b07   d08   f09   h08   k07         --+-----------------------
05 | a06   c07   e08   g08   i07   l06      x | 0 1 2 3 4 5 6 7 8 9 10
06 |    b06   d07   f08   h07   k06
07 | a05   c06   e07   g07   i06   l05      y = 22 - |x - 5| - 2R
08 |    b05   d06   f07   h06   k05
09 | a04   c05   e06   g06   i05   l04
10 |    b04   d05   f06   h05   k04
11 | a03   c04   e05   g05   i04   l03
12 |    b03   d04   f05   h04   k03
13 | a02   c03   e04   g04   i03   l02
14 |    b02   d03   f04   h03   k02
15 | a01   c02   e03   g03   i02   l01
16 |    b01   d02   f03   h02   k01
17 |       c01   e02   g02   i01
18 |          d01   f02   h01
19 |             e01   g01
20 |                f01

```

**Step #2: apply the move vectors**

Below is the list of the move vectors in the Cartesian system:

```
(-2, +4), (-1, -5), (+3, +1),
(-3, +1), (+1, -5), (+2, +4),
(-3, -1), (+2, -4), (+1, +5),
(-2, -4), (+3, -1), (-1, +5)

```

We apply each of them to the source coordinates ***(x, y)*** and get a list of target coordinates ***(X, Y)***.

**Step #3: test the target coordinates**

We now need to check which target coordinates are actually located inside the board. This is done by testing ***X + Y*** and ***X - Y***:

The coordinates are valid if all the following comparisons are true:

* ***X + Y \> 3***
* ***X + Y \< 27***
* ***X - Y \< 7***
* ***X - Y \> -17***

We should also verify that ***X*** is in **\[0 .. 10\]**. This is not done explicitly because `s[X]` is *undefined* if it's not, which eventually results in a falsy value that gets filtered out.

**Step #4: convert back to hexagonal chess coordinates**

Finally the valid target coordinates are converted back to hexagonal chess coordinates, using the inverse of the formulas described at step #1.

### Test cases

```
let f =

F=>R=>[...'100124566542'].map((X,i)=>(X-=3-(x=(s='abcdefghikl').search(F)))-7<(Y=('9641001469'[i]||10)-(A=Math.abs)(x-5)+17-2*R)&X+Y>3&X+16>Y&X+Y<27&&s[X]+(22-Y-A(X-5))/2).filter(n=>n)

console.log(JSON.stringify(f('b')(6)))
console.log(JSON.stringify(f('f')(6)))
console.log(JSON.stringify(f('f')(11)))
console.log(JSON.stringify(f('i')(1)))
```

# Answer
> 4 votes
## Batch. 403 bytes

```
@echo off
set j=a b c d e f g h i k l
set f=0
for %%f in (%j%)do set/af+=1&if %%f==%1 goto l
:l
set j=j%j: =%
set/a"r=6-f,r*=r>>31,r+=%2
for %%s in ("-3 -2" "-3 -1" "-2 1" "2 -1" "3 1" "3 2")do call:c %%~s
exit/b
:c
call:l %2 %1
:l
set/ag=f+%1,s=r+%2,t=g-s
if %g% geq 1 if %g% leq 11 if %s% geq 1 if %s% leq 11 if %t% geq -5 if %t% leq 5 set/a"t=6-g,s-=t*=t>>31"&call echo %%j:~%g%,1%%%%s%%

```

Adjusts the coordinate system, although in a different way to @Arnauld's answer. The `c` subroutine takes advantage of the symmetry by trying the mirror reflection of each move. (I also tried rotating but that took too many bytes.)

# Answer
> 3 votes
## JavaScript (ES6), 184 bytes

```
(s,t,j=' abcdefghikl',f=j.search(s),r=f<6?t:t+f-6)=>[...'120405..162645'].map((c,i)=>[(i>>1)-3+f,c-3+r]).filter(([f,r])=>f>0&f<12&r>0&r<12&f-r<6&r-f<6).map(([f,r])=>j[f]+(f<6?r:r+6-f))

```

I thought I'd port my Batch solution to ES6 to see how it compared... I didn't expect it to be *that* close...

# Answer
> 3 votes
# CJam, 77

```
1Z2W2Z]_Wf*+2/_Wf%+[r('a-_9>-_6-We>@~+]f.+{_~m5++B,-!},{~1$6-We>-\_8>+'a+\S}/

```

Try it online

**Overview:**

I'm using a coordinate system that looks like a..f and 1..6 on the left side, extended without bending, with letters replaced with numbers, and changed to be 0-based (b3→\[1 2\], g1→\[6 1\], k3→\[9 6\]). The relative moves in this system are \[1 3\], \[2 -1\], \[2 3\] and their reflections (negative and swapped, e.g. \[1 3\] → \[-1 -3\], \[3 1\], \[-3 -1\]). A resulting \[x y\] position is valid iff \[x y z\] ⊂ \[0 1 .. 10\] where z=x-y+5.

# Answer
> 1 votes
# Dyalog APL, 72 bytes

```
(6=|×/t,-/t←↑j[a⍳⊂⍞]-j←⊃,/i,¨¨↓∘i¨i-6)/a←⊃,/(11⍴⎕a~'J'),∘⍕¨¨⍳¨5+i⌊⌽i←⍳11

```

try

builds a list `a` of all valid cells: `'A1' 'A2' ... 'L6'`

`a` is used for both input and output

builds a list `j` of the corresponding coordinates to `a` in a system where the x axis is along `A6-L1` and y along `F1-F11`

an imaginary third coordinate is the difference of the first two

if the input cell is translated to coords `0 0 0`, a knight can move to those cells whose product of coords is 6 or -6

# Answer
> 0 votes
# Python 3.6, 149

```
H='abcdefghikl'
lambda f,r:[H[i]+str(j)for i,j in[(H.find(f)+p%4*s,int(r)+p//4)for p in[9,6,-1,-5,-11,-10]for s in(1,-1)]if 0<i<11if 0<j<12-abs(6-i)]

```

An anonymous function called with two strings for the file and rank; returns a list of strings.

## Ungolfed:

```
def h(f,r):
    H='abcdefghikl'

    A = []
    for p in[9,6,-1,-5,-11,-10]:
        for s in(1,-1):
            i = H.find(f) + p%4*s
            j = int(r) + p//4
            A.append(i, j)

    B = []
    for i,j in A:
        if 0 < i < 11 and 0 < j < 12 - abs(6 - i):
            B.append(H[i] + str(j))

    return B

```

---
Tags: code-golf, chess, hexagonal-grid
---


title: Count # of Cookie Chocolate Chips

text:
# Question
Title: Count # of Cookie Chocolate Chips
Note: this is my first post here.

# The Challenge

The challenge is to count the number of chocolate chips in a cookie. A cookie in this case is a circle with dots (the chips) in it. Given any square cartoon image of this cookie, you are to write a bot that counts and outputs the number of chocolate chips.

# Rules

* Has to take in an image type of png.
* It has to be able to take in any file size, as long as it is square.
* It has to be able to handle both color and B&W images.
* Output can be in any human-understandable form.
* The circle will be filled with color and will have an outline.
* Chips will all be the same size and color.
* There is only one cookie in the image
* Chocolate chips may be irregularly spaced, but are perfect circles.
* You can use a library.
* There is nothing in the image except the cookie and the chocolate chips. -All other cookies will look like the example images.

This is ; the shortest code gets accepted.

# Examples

Cookie 1 =\> `8` or `1000` (binary)
Cookie 2 =\> `8` or `1000` (binary)
Cookie 3 =\> `10` or `1010` (binary)
Cookie 4 =\> `7` or `0111` (binary)

# Answer
## Mathematica 134 Bytes

```
Max@ComponentMeasurements[ArrayComponents[ImageData@ColorQuantize[RemoveAlphaChannel[#,White],4,Dithering->False],2],"Holes"][[All,2]]&

```

Usage (applied to .png images)

```
%/@cookies

```

Output:

```
{8,8,10,7}

```

Here's the code to bring in the cookie examples:

```
cookieURLs={"https://i.stack.imgur.com/UCV1A.png","https://i.stack.imgur.com/5n7AY.png","https://i.stack.imgur.com/ZbZx6.png","https://i.stack.imgur.com/M8jTo.png"};
cookies=Import/@cookieURLs;

```

I'm sure this can be shortened, but I think it's fairly bullet-proof as is. The original images have many more colors than the eye can see.

Here are the original cookies:

Here are the cookies after cleanup to get them into a 4 component array:

```
ArrayPlot[ArrayComponents[ImageData@ColorQuantize[RemoveAlphaChannel[#,White],4,Dithering->False],2]]&/@cookies//Row

```

After that, all is needed is to use `ComponentMeasurements` to count holes. This will always report at least 1. You could have one really big chocolate chip filling the cookie border, so the 0 or 1 case will always be ambiguous.
> 3 votes

---
Tags: code-golf, image-processing, counting
---


title: Braille-ify a string

text:
# Question
Title: Braille-ify a string
> And no, This is not a dupe of Translate ASCII text to braille.

There are 28=256 Braille patterns in Unicode. (By 'Braille' I mean 8-cell ones)

W, wait. How many ASCII characters were there?

27 = 128?

Well then, Let's turn ASCII into Braille, 'cause there is absolutely no reason not to!

---

# The way from ASCII, to Braille

We can see each cells represent a bit, which each cell is 'punched' or not.

Now we can allocate each cells to represent the bits of the ASCII character as binary.

```
(1  )(16 )
(2  )(32 )
(4  )(64 )
(8  )( - )

```

* `( - )` is blank

Now we can convert ASCII to Braille. For example, `A`(65=01000001) equals to .

# Examples

```
Input -> Output
Braille! -> ⠢⠺⠱⡱⡴⡴⠵⠑
(Upscaled)
.. .o o. o. .. .. o. o.
o. oo .o .o .o .o .o .o
.o .o .o .o oo oo oo ..
.. .. .. o. o. o. .. ..

```

# Answer
> 14 votes
# CJam, ~~27~~ 26 bytes

```
80qf{i2b7Te[4/~\)\@+++2bc}

```

Try it online!

### Explanation

The Braille code points are neatly ordered so that the individual dots do count up in binary. However, the ordering of the bits in the code points is different. We want the following order:

```
04
15
26
37

```

Whereas the characters are laid out in Unicode in this order:

```
03
14
25
67

```

(Which kinda makes sense, because historically, Braille only used the first six dots.) Note that we don't need the `7` dot, since the input is guaranteed to be in the ASCII range. So given a list of bits `[6 5 4 3 2 1 0]` of an input character, we want to reorder them into `[3 6 5 4 2 1 0]`, to pull the bit representing the bottom-left dot to the most significant position.

```
80     e# Push 80... we'll need this later.
q      e# Read all input.
f{     e# Map this block onto each character, putting a copy of the 80
       e# below each character.
  i    e#   Convert the character to its code point.
  2b   e#   Get its binary representation.
  7Te[ e#   Pad it to 7 bits with zeros. We've now got some bit list
       e#   [6 5 4 3 2 1 0].
  4/   e#   Split into chunks of 4: [[6 5 4 3] [2 1 0]]
  ~    e#   Dump them onto the stack: [6 5 4 3] [2 1 0]
  \    e#   Swap them: [2 1 0] [6 5 4 3]
  )    e#   Pull off the last element: [2 1 0] [6 5 4] 3
  \    e#   Swap: [2 1 0] 3 [6 5 4]
  @    e#   Rotate: 3 [6 5 4] [2 1 0]
  ++   e#   Concatenate twice: [3 6 5 4 2 1 0]
       e#   That's the reordering done.
  +    e#   Prepend the 80. That puts it in the 2^7 position of the
       e#   binary digit list, which gives it a value of 10240, which
       e#   is where the Braille characters start.
  2b   e#   Convert the bits back to an integer.
  c    e#   Convert the code point to the corresponding integer.
}%

```

# Answer
> 11 votes
## JavaScript (ES6), 83 bytes

```
f=
s=>s.replace(/./g,c=>String.fromCharCode((c=c.charCodeAt())&7|c*8&64|c/2&56|10240))
```

```
<input oninput=o.textContent=f(this.value)><pre id=o>
```

# Answer
> 6 votes
# Python 3, ~~98~~ ~~71~~ 66 bytes

```
lambda s:''.join(chr(i*8&64|i//2&56|i&7|10240)for i in map(ord,s))

```

Try it online!

# Answer
> 5 votes
## CJam, 27 bytes

*1 byte stolen from Neil.*

```
q{i__8&8*@7&@2/56&++'⠀+}%

```

Try it online!

### Explanation

This uses the same basic idea as my other CJam answer but uses bitwise arithmetic instead of base conversion and list manipulation to reorder the bits.

```
q        e# Read all input.
{        e# Map this block over each character...
  i__    e#   Convert the character to its code point and make two copies.
  8&     e#   AND 8. Gives the 4th bit, which we need to move to the 7th place.
  8*     e#   Multiply by 8 to move it up three places.
  @7&    e#   Pull up another copy and take it AND 7. This extracts the three
         e#   least significant bits which shouldn't be moved at all.
  @2/    e#   Pull up the last copy and divide by 2 to shift all bits down
         e#   by one place.
  56&    e#   AND 56. Extracts the three most-significant bits.
  ++     e#   Add all three components back together.
  '⠀+    e#   Add to the empty Braille character which is the offset for all
         e#   the code points and which converts the value to a character.
}%

```

# Answer
> 3 votes
# PHP, 109 Bytes

```
foreach(str_split($argn)as$c)echo json_decode('"\u'.dechex(10240+(($d=ord($c))&7)+($d/2&56)+(($d&8)*8)).'"');

```

Online Version

# Answer
> 2 votes
## Mathematica 100 Bytes

```
FromCharacterCode[10240+#~Drop~{4}~Prepend~#[[4]]~FromDigits~2&/@ToCharacterCode@#~IntegerDigits~2]&

```

Ungolfed:

```
ToCharacterCode["Braille!0"]
PadLeft@IntegerDigits[%,2]
Prepend[Drop[#,{4}],#[[4]]]&/@%
FromDigits[#,2]&/@%
FromCharacterCode[%+10240]

```

+60 bytes of this tied up in long function names.

# Answer
> 1 votes
# Jelly, 21 bytes

```
O&€“¬®p‘æ.1,8,.+“'ṁ’Ọ

```

Try it online!

### How it works

```
O&€“¬®p‘æ.1,8,.+“'ṁ’Ọ  Main link. Argument: s (string)

O                      Ordinal; map all characters to their Unicode code points.
   “¬®p‘               Yield the code points of the enclosed characters in Jelly's
                       code page, i.e., [1, 8, 112].
 &€                    Take the bitwise AND of each code point to the left and the
                       three code points to the right.
          1,8,.        Yield [1, 8, 0.5].
        æ.             Take the dot product of the array to the right and each flat
                       array in the array to the left.
                “'ṁ’   Yield 10240 = 250 × 39 + 239, where 39 and 239 are the
                       indices of ' and ṁ in Jelly's code page.
               +       Add 10240 to all integers to the left.
                    Ọ  Unordinal; convert all code points to their respective
                       Unicode charcters.

```

# Answer
> 0 votes
# Retina, 59 bytes

```
T`�-- -'0-7@-GP-W\`-gp-w--(-/8-?H-OX-_h-ox-`⠀-⡿

```

Try it online! Hex dump:

```
0000  54 60 00 2a 07 10 2a 17  20 2a 17 30 2a 17 40 2a  T`�-- -'0-7@-
0010  47 50 2a 57 5c 60 2a 67  70 2a 77 08 2a 0f 18 2a  GP-W\`-gp-w--
0020  1f 28 2a 2f 38 2a 3f 48  2a 4f 58 2a 5f 68 2a 6f  (-/8-?H-OX-_h-o
0030  78 2a 7f 60 e2 a0 80 2a  e2 a1 bf                 x-`⠀-⡿
```

# Answer
> 0 votes
# Chip, ~~62~~ 59 bytes

```
h*
 Z~.
z.g+b
>xv<
||sf
Zx^<
Z< |
A/a/D
B/b
C/c
E/d
F/e
G/f

```

Try it online!

I suspect I can golf it more, just gotta figure out how...

Chip reads in each byte of input as a collection of bits, referred to by the first eight letters of the alphabet (uppercase is input, lower is output):

```
HGFEDCBA

```

We simply need to map those bits of the input to the following three bytes of output:

```
11100010 101000hd 10gfecba

```

The top half of the code is doing all the sequencing, and generates the first two bytes, the bottom half generates the third byte.

Since the specification only requires handling 7 bits for ASCII, we don't examine `H`. To include the eighth bit, change line `B/b` to `B/b/H`.

# Answer
> 0 votes
# C#, 63 bytes

```
s=>string.Concat(s.Select(c=>(char)(c*8&64|c/2&56|c&7|10240)));

```

Try it online!

Inspiration from @ovs and @Neil

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


title: Easy as ABC Solver

text:
# Question
Title: Easy as ABC Solver
Easy As ABC, also known as "End View", is a puzzle where you are given an empty grid with letters around it; you must partially fill in the grid so that exactly one of each letter is in every row and column; in addition, letters at the end of a row (or column) must be the first letter visible in that row (or column) from that direction. Your goal in this code golf will be to solve an Easy As ABC puzzle.

For example, here is an Easy As ABC puzzle from this year's MIT Mystery Hunt using the letters MIC:

The solution is:

(Sorry about the artifacts on the Cs; I tried to edit out the irrelevant information from the rest of the puzzle.)

# I/O

Input will be an array of strings or a string possibly with delimiters. It will start in the top left corner and go clockwise. For instance, the above puzzle could be input like this:

```
".CMM.M|....IM|.....I|C.ICI."

```

Output should be the solved grid, with or without the border. It can be as an array of chars, array of strings, or any other convenient format. The same "blank" character must be accepted as input and displayed as output, but that blank character may be anything. If they are single strings, both input and output must have the same separator (between sides for input and rows for output) or no separator at all.

For unsolvable puzzles, you must output something that is not mistakable for a solution. You may assume that no puzzle has more than one solution.

You must allow any number of letters and any size grid; *all* used letters will appear in the border of the grid.

This is : as usual, shortest code wins!

# Test Cases

```
"T.AA..|.T.TSS|..TST.|A...SS"
"R.RU..|B.B..B|.UR.UB|UR..B."
"N...NK|E.NK.K|..KK..|....EK"
"CA..DBD|.B..CC.|.D.DEB.|DB.A..A"
"...DDEBE|DC..EBBD|BA..ABF.|E..FECDE"

```

# Answer
> 1 votes
# PHP, 1111 Bytes

minus the Bytes removing newlines

The Online version works only with the Testcases with a length of 6

## short workaround

make all permutations

fill 2 arrays with the permutations $x $y

change between two functions so long till only 1 solution in the x array foreach line exists

function i:find intersections in the grid and drop permutations

function c:check the colums in each array of unique charcters and remove permutations in the other lines for array $x and $y

```
$p=[];p(array_pad(($s="str_split")(substr(count_chars($a=$argn,3),1,-1)),$l=(strlen($a)-3)/4," "));
$e=explode("|",$a);$e[3]=strrev($e[3]);$e[2]=strrev($e[2]);
$x=$y=array_fill(0,$l,$p);$g="preg_grep";$c="array_column";$o="join";
foreach($q=range(0,$l-1)as$i){
$e[0][$i]=="."?:$y[$i]=$g("#^\s*{$e[0][$i]}#",$y[$i]);
$e[2][$i]=="."?:$y[$i]=$g("#{$e[2][$i]}\s*$#",$y[$i]);
$e[3][$i]=="."?:$x[$i]=$g("#^\s*{$e[3][$i]}#",$x[$i]);
$e[1][$i]=="."?:$x[$i]=$g("#{$e[1][$i]}\s*$#",$x[$i]);}
for(;array_sum(($m="array_map")("count",$x))>$l;){
foreach($q as$i)foreach($q as$j){
$k=array_intersect($c($m($s,$x[$i]),$j),$c($m($s,$y[$j]),$i));
$y[$j]=$g("#^.{{$i}}(".$o("|",$k).")#",$y[$j]);
$x[$i]=$g("#^.{{$j}}(".$o("|",$k).")#",$x[$i]);
foreach(["x","y"]as$z){
$u=array_unique($c($m($s,${"$z"}[$i]),$j));
if(count($u)==1&&end($u)!=" "){$w=end($u);
foreach($q as$h){
if($i!=$h)${"$z"}[$h]=$g("#^.{{$j}}{$w}#",${"$z"}[$h],1);}}
}}}
echo$o("\n",$m($o,$x));
function p($c,$b=[]){global$p;
if(($c)){$n=[];while($c){
$e=array_pop($c);
p(($m="array_merge")($c,$n),$m($b,[$e]));
$n[]=$e;
}}else in_array($b=join($b),$p)?:$p[]=$b;}

```

---
Tags: code-golf, puzzle-solver
---


title: Solve a Stack State Diagram

text:
# Question
Title: Solve a Stack State Diagram
A stack state diagram shows how the values on one stack are changed into the other. For example, this is a stack state diagram:

```
3 0 2 1 0

```

This means that there is a stack initially containing 3 values (the `3` part). These values are indexed from 0 to 2, with 0 at the top: `2 1 0`. The next part `0 2 1 0` describes the final state of the stack: the value that was originally on top of the stack has been copied to the back as well.

These transformations happen on a stack that has support for several data types:

* The "value" type, which is what is originally on the stack. This could be a string, integer, etc. but its value does not need to be known.
* The "list" type, which is a list containing values of any data type.

To model this transformation, the following operations are permitted:

* `S`: Swap the two values on top of the stack: `2 1 0``2 0 1`
* `D`: Duplicate the value on top of the stack: `1 0``1 0 0`
* `R`: Remove the top value on the stack. `2 1 0``2 1`
* `L`: Turn the top value into a one-element list containing that value: `2 1 0``2 1 (0)`
* `C`: Concatenate the top two lists on the stack: `2 (1) (0)``2 (1 0)`
* `U`: Place all the values from a list onto the stack: `2 (1 0)``2 1 0`

These are equivalent to the Underload commands `~ : ! a * ^`, provided that no other commands are used.

`S`, `D`, `R`, and `L` can be used with any values on top of the stack, but `C` and `U` must have lists on top of the stack to function. A submission whose generated sequences attempt to preform invalid operations (like `D` on an empty stack or `U` on a non-list) is *wrong* and must be ~~punished~~ fixed.

To solve a stack state diagram, find a sequence of commands that will correctly transform the initial stack state into the new one. For example, one solution to `3: 0 2 1 0` is `LSLCSLCULSLCLSLDCSC USLCU`:

```
   2 1 0
L  2 1 (0)
S  2 (0) 1
L  2 (0) (1)
C  2 (0 1)
S  (0 1) 2
L  (0 1) (2)
C  (0 1 2)
U  0 1 2
L  0 1 (2)
S  0 (2) 1
L  0 (2) (1)
C  0 (2 1)
L  0 ((2 1))
S  ((2 1)) 0
L  ((2 1)) (0)
D  ((2 1)) (0) (0)
C  ((2 1)) (0 0)
S  (0 0) ((2 1))
C  (0 0 (2 1))
U  0 0 (2 1)
S  0 (2 1) 0
L  0 (2 1) (0)
C  0 (2 1 0)
U  0 2 1 0

```

Your task is to write a program that takes a stack state diagram and outputs a solution.

# Test Cases

```
2 1 0       ->

3 2 0       -> SR

9           -> RRRRRRRRR

2 0 1 0     -> LSLCDCUR

2 0 1 1     -> SD

6 2         -> RRSRSRSR

5 0 1 2 3 4 -> LSLCSLCSLCSLCU

4 2 0 1 3 2 -> LSLCSLSCSLCULSLSCSLSCLSLDCSCUSLCU

```

This is , so the shortest valid answer (in bytes) wins.

# Answer
# Python 3, 84 bytes

```
lambda n,*s:"DLL"+"L".join(i*"SLSC"+"LSLSCDURLCULCULSC"for i in s[::-1])+n*"SR"+"UR"

```

Usage:

```
# Example: 4 2 0 1 3 2 -> LSLCSLSCSLCULSLSCSLSCLSLDCSCUSLCU
>>> f = lambda ...
>>> f(4, 2, 0, 1, 3, 2)
'DLLSLSCSLSCLSLSCDURLCULCULSCLSLSCSLSCSLSCLSLSCDURLCULCULSCLSLSCLSLSCDURLCULCULSCLLSLSCDURLCULCULSCLSLSCSLSCLSLSCDURLCULCULSCSRSRSRSRUR'

```

**Explanation:** To start off we duplicate the zero and wrap it in a list:

```
DL -> 3 2 1 0 (0)

```

This is our base. Now I will explain a general algorithm that turns `... 1 0 (x)` into `... 1 0 (i x)` for arbitrary integer `i`. I will use as an example `i = 2`, and we have some arbitrary list `(x)`. We start by wrapping our current list `(x)` into another list:

```
L -> 3 2 1 0 ((x))

```

Now we repeat the following sequence `i` times:

```
SLSC -> 3 2 1 (0 (x))
SLSC -> 3 2 (1 0 (x))

```

Now we're ready to insert the 2 into list `(x)`. This goes as follows:

```
LSLSC -> 3 (2 (1 0 (x)))
DU -> 3 (2 (1 0 (x))) 2 (1 0 (x))
RLCU -> 3 2 (1 0 (x)) 2
LCU -> 3 2 1 0 (x) 2
LSC -> 3 2 1 0 (2 x)

```

Note that we keep pushing new integers on the left. So the very first `(0)` we started with stays on the right.

After we have inserted every integer we need into the list we remove the rest of the stack by swapping and removing *n* time (`SR`). Finally we unpack our list and delete the first `0` we inserted to start our list (`UR`).
> 9 votes

# Answer
## CJam, 54 bytes

Just a translation from orlp's Python solution into CJam. There's nothing new here.

```
"DLL"q~("SR"*\W%{"SLSC"*"LSLSCDURLCULCULSC"+}%'L*\"UR"

```

Explanation:

```
"DLL"                  e# Push string
q~                     e# Read input and evaluate
(                      e# Pop the first value
"SR"                   e# Push string
*                      e# Repeat string n times
\                      e# Swap (bring s to front)
W%                     e# Reverse
{                      e# For each:
  "SLSC"               e#   Push string
  *                    e#   Repeat i times
  "LSLSCDURLCULCULSC"+ e#   Append string to end
}%                     e# End
'L*                    e# Join with 'L'
\                      e# Swap (bring "SR"*n to front)
"UR"                   e# Push string
                       e# [Stack is implicitly output.]

```
> 0 votes

---
Tags: code-golf, code-generation, stack
---