title: Find the binarray!

text:
# Question
Title: Find the binarray!
We define a *binarray* as an array satisfying the following properties:

* it's non-empty
* the first value is a `1`
* the last value is a `1`
* all other values are either `0` or `1`

For instance, the array `[ 1, 1, 0, 1 ]` is a valid *binarray*.

## The task

Given a non-empty array **A** of non-negative integers and a positive integer **N**, your job is to find a *binarray* **B** of length **N** which allows to generate **A** by summing an unrestricted number of copies of **B**, shifted by an unrestricted number of positions.

### Example

```
A = [ 1, 1, 2, 4, 1, 2, 2, 1, 0, 1, 0, 1, 1, 0, 1 ]
N = 4

```

For this input, the *binarray* `B = [ 1, 1, 0, 1 ]` would be a valid answer because we can do:

```
  [ 1, 1, 0, 1 ]
+       [ 1, 1, 0, 1 ]
+       [ 1, 1, 0, 1 ]
+          [ 1, 1, 0, 1 ]
+                   [ 1, 1, 0, 1 ]
+                                  [ 1, 1, 0, 1 ]
  -----------------------------------------------
= [ 1, 1, 2, 4, 1, 2, 2, 1, 0, 1, 0, 1, 1, 0, 1 ]

```

### Rules

* Input can be taken in any reasonable format.
* Output can be either a native array (e.g. `[1, 1, 0, 1]`) or a binary string with or without a separator (e.g. `"1,1,0,1"` or `"1101"`)
* You're only required to print or return one valid *binarray*. Alternatively, you may choose to print or return *all of them* when several solutions exist.
* You are not required to support inputs that do not lead to any solution.
* The sum may include implicit zeros which do not overlap with any copy of **B**. The second zero in the above sum is such an implicit zero.
* Your can assume that the maximum size of **A** is 100 and the maximum size of **B** is 30.
* This is code-golf, so the shortest answer in bytes wins. Standard loopholes are forbidden.

## Test cases

```
Input : N = 1 / A = [ 1, 2, 3, 4, 5 ]
Output: [ 1 ]

Input : N = 2 / A = [ 1, 2, 100, 99 ]
Output: [ 1, 1 ]

Input : N = 3 / A = [ 1, 1, 1 ]
Output: [ 1, 1, 1 ]

Input : N = 3 / A = [ 1, 1, 3, 2, 2 ]
Output: [ 1, 1, 1 ]

Input : N = 3 / A = [ 1, 0, 2, 1, 1, 1, 0, 0, 1, 0, 1 ]
Output: [ 1, 0, 1 ]

Input : N = 4 / A = [ 1, 2, 2, 2, 1 ]
Output: [ 1, 1, 1, 1 ]

Input : N = 4 / A = [ 1, 1, 2, 4, 1, 2, 2, 1, 0, 1, 0, 1, 1, 0, 1 ]
Output: [ 1, 1, 0, 1 ]

Input : N = 4 / A = [ 1, 1, 0, 2, 1, 0, 1 ]
Output: [ 1, 0, 0, 1 ] or [ 1, 1, 0, 1 ]

Input : N = 5 / A = [ 1, 3, 6, 9, 8, 6, 3, 4 ]
Output: [ 1, 1, 1, 0, 1 ]

Input : N = 8 / A = [ 2, 1, 0, 2, 3, 3, 1, 2, 1 ]
Output: [ 1, 0, 0, 1, 1, 1, 0, 1 ]

Input : N = 10 / A = [ 1, 2, 1, 2, 2, 1, 3, 3, 3, 2, 3, 0, 2, 1, 1, 0, 1 ]
Output: [ 1, 1, 0, 1, 0, 1, 1, 1, 0, 1 ]

Input : N = 13 / A = [ 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1 ]
Output: [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]

Input : N = 5 / A = [ 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1 ]
Output: [ 1, 1, 1, 1, 1 ]

Input : N = 6 / A = [ 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1 ]
Output: [ 1, 0, 0, 0, 0, 1 ]

Input : N = 7 / A = [ 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1 ]
Output: [ 1, 1, 0, 0, 0, 1, 1 ]

Input : N = 9 / A = [ 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1 ]
Output: [ 1, 0, 1, 0, 1, 0, 1, 0, 1 ]

```

# Answer
> 8 votes
# PHP, ~~105 92 90~~ 86 bytes

Jörg´s solution fixed and golfed:

```
for($b=1+2**$argv[1];;)--$argc>1?$s+=$argv[$argc]*2**$i++:$s%($b-=2)||die(decbin($b));

```

takes `N` from first command line argument, values after that; run with `-r`or test it online.
prints binary number (format `10001`); prints invalid solution or runs dead if there is no valid solution.

**first version** (now 97 bytes) that prints nothing for invalid input: test it online

```
for($b=1+$m=2**$argv[1];$m/2<=$b;)--$argc>1?$s+=$argv[$argc]*2**$i++:$s%($b-=2)||die(decbin($b));

```

**breakdown**

```
for($b=1+$m=2**$argv[1];$m/2<=$b;)  # second loop: loop $b from 2^N-1 by -2 to 2^(N-1)
--$argc>1                           # first loop: decrease $argc ...
    ?$s+=$argv[$argc]*2**$i++           # while $argc>1: binary sum from last to 2nd argument
    :$s%($b-=2)||die(decbin($b));       # later: if $b divides $s, print in binary and exit

```

# Answer
> 8 votes
# PHP, 219 bytes

```
<?for(list($g,$z)=$_GET,$d=~-$l=2**$z;$d>=$l/2;max(array_diff_assoc($r,$g)?:[0])?:$o[]=$b,$d-=2)for($r=[],$b=decbin($d),$k=0;$k<count($g);$k++)for($u=$g[$k]-$r[$k],$i=0;$i<$z;$i++)$u<1?:$r[$k+$i]+=$u*$b[$i];print_r($o);

```

Try it online!

-4 Bytes using `[$g,$z]=$_GET` PHP 7.1 instead of `list($g,$z)=$_GET`

# Answer
> 3 votes
# Python, 166 bytes

```
def f(a,n):
 for i in range(1<<n-1,1<<n):
  b=bin(i)[2:];u,v=(int(('0{:0>%d}'%sum(a)*len(s)).format(*s))for s in[a,b])
  if u%v<1>int(str(u//v*10)[::~sum(a)]):yield b

```

Try it online!

### How it works

Consider A and B as the digits of base *k* numbers *u* and *v*. For example (we’ll use *k* = 1000 for illustration):

A = \[1, 2, 1, 3, 2, 1, 2\]
B = \[1, 0, 0, 1\]
*u* = 1 002 001 003 002 001 002
*v* = 1 000 000 001

As many of the other answerers noticed, if B is a valid answer, then *u* is divisible by *v*. In this case,

*u* = 1 002 001 002 ⋅ *v*

This quotient, translated back to the array \[1, 2, 1, 2\], tells us exactly how many copies of B we need shifted to each position.

```
  [1, 0, 0, 1]
+    [1, 0, 0, 1]
+    [1, 0, 0, 1]
+       [1, 0, 0, 1]
+          [1, 0, 0, 1]
+          [1, 0, 0, 1]
-----------------------
  [1, 2, 1, 3, 2, 1, 2]

```

(Why? Because that is exactly how long multiplication works in base *k*.)

What the other answerers failed to notice is that **the above condition is not sufficient**. For example:

A = \[1, 2, 1, 3, 2, 1, 2\]
B = \[1, 1, 1, 1\]
*u* = 1 002 001 003 002 001 002
*v* = 1 001 001 001
*u* = 1 000 999 002 ⋅ *v*

Mathematically speaking, we can still translate that quotient back to the array \[1, 1, −1, 2\], which works fine if we’re allowed to use negative copies of B:

```
  [1, 1, 1, 1]
+    [1, 1, 1, 1]
−       [1, 1, 1, 1]
+          [1, 1, 1, 1]
+          [1, 1, 1, 1]
-----------------------
  [1, 2, 1, 3, 2, 1, 2]

```

but of course the challenge does not permit negative copies. So we need an additional check.

Toward that end, we select a base *k* = 10<sup>*e*</sup> where *k* \> 10 ⋅ sum(A), and check that none of the base *k* digits overflow into the next base *k* digit when we multiply the quotient by ten. That is, every *e*th base ten digit, starting at the end, in the base ten representation of the quotient times ten, must be 0. This guarantees that the quotient translates back to an array with nonnegative elements.

# Answer
> 2 votes
# PHP, 213 Bytes

Same way a little bit golfed

```
<?for($b=2**~-$l=$_GET[1];$b<2**$l;array_filter($t[$b++])?:$d[]=$o)for($g=count($t[$b]=$_GET[$i=0]);min($t[$b])>-1&$i<=$g-$l;$i++)for($e=$t[$b][$i],$k=0,$o=decbin($b);$k<$l;)$t[$b][$k+$i]-=$o[$k++]*$e;print_r($d);

```

Try it online!

## PHP, 344 Bytes first working

After my first answer I have decide to make a longer try that give back all valid solutions.

```
<?foreach(range(2**($l=$_GET[1])-1,2**($l-1))as$b){$t[$b]=($g=$_GET[0]);for($i=0;$t[$b]&&$i<=count($g)-$l;$i++){$e=reset($y=array_slice($t[$b],$i,$l));foreach(str_split(decbin($b))as$k=>$v)$t[$b][$k+$i]=$y[$k]-$e*$v;if(min($t[$b])<0)unset($t[$b]);}}foreach($t as$k=>$v)if(max($v)>0)unset($t[$k]);echo join(",",array_map(decbin,array_keys($t)));

```

Online Version

## Breakdown

```
foreach(
    range(2**($l=$_GET[1])-1
    ,2**($l-1)
    ) # make decimal range of a binarray with given length
    as$b){
$t[$b]=($g=$_GET[0]); # make a copy for each possible solution pattern
    for($i=0;$t[$b]&&$i<=count($g)-$l;$i++){ # Loop till solution is valid or reach last digit
        $e=reset($y=array_slice($t[$b],$i,$l)); # take first value of a sequence with the length
        foreach(str_split(decbin($b))as$k=>$v)
            $t[$b][$k+$i]=$y[$k]-$e*$v; # replace values in copy
        if(min($t[$b])<0)unset($t[$b]); # kill solution if a minimum <0 exists
    }
}
foreach($t as$k=>$v)if(max($v)>0)unset($t[$k]); # drop all solutions where the sum is not zero

echo join(",",array_map(decbin,array_keys($t))); #Output all solutions

```

# Answer
> 1 votes
## Python, 205 bytes

```
def f(a,l):
 b=lambda s:b(s[:-1])*sum(a)*8+int(s[-1])if s else 0
 c=lambda n:n and(n/sum(a)/4%2 or c(n/sum(a)/8))
 for i in range(2**~-l,2**l):
  j=bin(i)[2:]
  if b(a)%b(j)<1 and not c(b(a)/b(j)):return j

```

Returns a binary string without separator. As @AndersKaseorg points out, there are inputs for which @fəˈnɛtɪk's solution doesn't work because the division represents a negative coefficient which is disallowed. To work around this, I use a very large base and test that there is no borrow in the division.

# Answer
> 1 votes
# Pari/GP, ~~77~~ ~~74~~ ~~96~~ 80 bytes

```
n->a->[v|d<-divisors(b=Pol(a)),(v=Vec(d))%2==v&&vecmin(Vec(b/d))>=0&&d%x&&#d==n]

```

Returns all solutions.

First converts the array `a` to a polynomial `b`. Then chooses from the divisors `b` the polynomials `d` such that the coefficients of `d` are all `1` and `0`, and the coefficients of `b / d` are all nonnegative, and `d(0) = 1`, and `deg(d) = n + 1`. Finally, converts them back to arrays.

Try it online!

# Answer
> 1 votes
# Pyth, 32 bytes

```
f!|%FKiRJysQ,QT>#sQj/FKJ+L1^U2tE

```

Try it online

### How it works

```
                           ^U2tE   Cartesian power [0, 1]^(N - 1)
                        +L1        prepend 1 to every list
f                                  filter for lists T such that:
          sQ                         sum(A)
         y                           double
        J                            assign to J
      iR    ,QT                      convert [A, T] from base J
     K                               assign to K
   %F                                fold modulo
  |                                  logical OR with
                    /FK                fold integer division over K
                   j   J               convert to base J
               >#sQ                    filter for digits greater than sum(A)
 !                                   logical NOT

```

The strategy is similar to my Python answer, except that since Pyth has builtins for base conversion, we can use a more efficient base *k* = 2 ⋅ sum(A), and check directly that every digit of the quotient is at most sum(A).

---
Tags: code-golf, array, polynomials
---


title: THE Magic Hexagon

text:
# Question
Title: THE Magic Hexagon
There are many magic squares, but there is just *one* non-trivial magic hexagon, as Dr. James Grime explained, which is the following:

```
  18 17  3
 11  1  7 19
9  6  5  2 16
 14  8  4 12
  15 13 10

```

As it is done in Hexagony this is easiest written as just one line, by just reading it row by row:

```
18 17 3 11 1 7 19 9 6 5 2 16 14 8 4 12 15 13 10

```

Of course there are twelve such list representations of this magic hexagon in total, if you count rotations and reflections. For instance a clockwise 1/6 rotation of the above hexagon would result in

```
9 11 18 14 6 1 17 15 8 5 7 3 13 4 2 19 10 12 16

```

@Okx asked to list the remaining variants. The remaining lists are:

```
15 14 9 13 8 6 11 10 4 5 1 18 12 2 7 17 16 19 3
3 17 18 19 7 1 11 16 2 5 6 9 12 4 8 14 10 13 15
18 11 9 17 1 6 14 3 7 5 8 15 19 2 4 13 16 12 10
9 14 15 11 6 8 13 18 1 5 4 10 17 7 2 12 3 19 16

```

plus all the mentioned lists reversed.

### Challenge

Write a program that outputs the magic hexagon as a list. You can choose *any* of the 12 reflections/rotations of the hexagon.

Please add a few words on how your solution works.

# Answer
> 9 votes
# Octave, 24 bytes

```
'IKRNFAQOHEGCMDBSJLP'-64

```

Try it online!

# Answer
> 5 votes
# Jelly, 11 bytes

```
“JɼQⱮȦ>Ȯ’Œ?

```

A niladic link returning the list of the given orientation reflected left-right.

**Try it online!**

### How?

Just the kind of thing for which I made `Œ?`

```
“JɼQⱮȦ>Ȯ’Œ? - Niladic link: no arguments
“JɼQⱮȦ>Ȯ’   - base 250 number, 18473955480703453
         Œ? - shortest permutation of some set of natural numbers one through to some N
            -   inclusive which would lie at that index in a list of all permutations of
            -   those same natural numbers when sorted lexicographically.
            -
            -   - for example 7Œ?:
            -   - since 7 is greater than 3! and less than 4!+1, it references four items
            -   - the sorted order of permutations of 4 items is:
            -   - [[1,2,3,4],[1,2,4,3],[1,3,2,4],[1,3,4,2],[1,4,2,3],[1,4,3,2],[2,1,3,4], ...]
            -   - so 7Œ? yields [2,1,3,4]

```

# Answer
> 4 votes
# 05AB1E, 14 bytes

Both solutions generate the list `[3,17,18,19,7,1,11,16,2,5,6,9,12,4,8,14,10,13,15]`

```
19Lœ•δn2м×„Á•è

```

Generates a list of all (sorted) permutations of the range `[1...19]` and indexes into that list with a base 255 compressed base 10 number.

Or 15 bytes runnable online

```
•áRвºñ*$vn+•20в

```

Decompresses a base 255 string to a base 10 number and converts to a list of base 20 digits.

Try it online!

# Answer
> 4 votes
# Pyth, 15 bytes

```
.PC"A¡öò\x06\x11Ý"S19

```

(Control characters replaced with `\x06` and `\x11` for your viewing convenience.)

Try it online

### How it works

```
   "A¡öò\x06\x11Ý"      magic string
  C                     convert to number n using codepoints as base-256 digits
.P                S19   nth lexicographic permutation of [1, …, 19]

```

# Answer
> 3 votes
# Jelly, 21 bytes

```
18473955480703453œ?19

```

I really want to compress that big number, but I'm not sure how.

Try it online!

# Answer
> 3 votes
# SOGL, 15 bytes

```
³←@uΙΒQH√y׀“L«─

```

Explanation:

```
...“     push the number 4121998669867569415662783
    L«   push 20
      ─  convert 4121998669867569415662783 from base 10 to a base 20 number aka base 10 array

```

# Answer
> 2 votes
# APL, 24 bytes

```
⎕A⍳'RQCKAGSIFEBPNHDLOMJ'

```

Try it online!

**How?**

```
⎕A                        ⍝ 'ABC...
   ⍳                       ⍝ indices of
    'RQCKAGSIFEBPNHDLOMJ'  ⍝ ← this vector

```

# Answer
> 1 votes
# JavaScript (ES6), 49 bytes

```
[...'ih3b17j9652ge84cfda'].map(n=>parseInt(n,26))

```

```
console.log(
[...'ih3b17j9652ge84cfda'].map(n=>parseInt(n,26))
)
```

# Answer
> 0 votes
## Mathematica, 37 bytes

```
36^^md1o3apsqxqkfhq6~IntegerDigits~20

```

Explanation (that may be already obvious as Mathematica is not a codegolf language, but according to the OP requirement):

```
36  : Number base
^^  : Input a number in arbitrary base. See BaseForm documentation
md1o3apsqxqkfhq6 : the number in base 36
~IntegerDigits~20 : convert to base 20 as list of digits

```

Output:

```
{18,17,3,11,1,7,19,9,6,5,2,16,14,8,4,12,15,13,10}

```

# Answer
> 0 votes
# Japt, 27 bytes

Inspired by rahnema1's solution.

```
`ikrnfaqogcmdbsjlp`¬®c -96

```

Try it online

---
Tags: code-golf, kolmogorov-complexity, permutations, hexagonal-grid
---


# Question
Title: Count the number of "e"s in a string without using the letter "e"
Your code may not contain the letter "e", but must count the number of "e"s in the inputted string and output that as a number. Bonus points if you use a language that is not a codegolf language and a language that actually uses the letter e (unlike brainfuck) --- not a required criteria.

# Answer
> 4 votes
# Japt, ~~7~~ ~~6~~ 4 bytes

Nope, definitely didn't use `e`!

```
è'Ev

```

Try it online

---

## Explanation

```
    :Implicit input of string U
è   :Count.
'E  :"E".
v   :Convert to lowercase.
    :Implicit output of result.

```

# Answer
> 3 votes
# MATL, 5 bytes

```
101=s

```

Try it online!

# Answer
> 2 votes
# Mathematica, 42 bytes

```
#~StringCount~StringDrop[ToString[2<1],4]&

```

input

> \["dfhjkeehjke"\]

output

> 3

# Answer
> 2 votes
# Jelly, 5 bytes

```
Oċ“d’

```

A monadic link returning the count.

**Try it online!**

### How?

```
Oċ“d’ - Link: list of characters
O     - cast to ordinals
  “d’ - base 250 number 101
 ċ    - count occurrences

```

Alternatives:
`O’ċȷ2` \- decrement () and count occurrences of 100 (`ȷ2`);
`ƓO’ċ³` \- evaluate a line from STDIN (`Ɠ`), decrement () and count occurrences of 100 (`³`)

# Answer
> 1 votes
# APL, 9 bytes

*2 bytes saved thanks to @Adam*

```
≢⍞∩22⊃⎕AV

```

**How?**

```
    22⊃⎕AV  ⍝ 'e'
 ⍞∩         ⍝ intersect with input
≢            ⍝ count

```

# Answer
> 1 votes
# CJam, 8 bytes

```
q'd)f=:+

```

Case sensitive.

Try it online!

### Explanation

```
q             Read input string
    f=        For each character in that string, see if it equals
 'd           character "d"
   )          increased by 1 (that is, character "e")
      :+      Sum the results. Implicitly display

```

# Answer
> 1 votes
# brainf\***, 215 bytes

case sensitive

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

```

155 of the bytes are from printing the number, from here.

Try it online!

# Answer
> 0 votes
# Python 3, ~~30~~ ~~26~~ 24 bytes

Extremely basic:

```
lambda s:s.count('\x65')

```

4 bytes off thanks to @Challenger's suggestion (adapted to this solution).

~~51~~ ~~46~~ 44 bytes, but I like it better:

```
lambda s:''.join('1'for i in s if i=='\x65')

```

Output is in unary. I found it first in the hopes that the other way was impossible; for once I'm annoyed that Python lets me do things the easy way.

5 bytes off thanks to @Challenger.

2 bytes off of each thanks to @xnor.

Attribution for the simple method: https://stackoverflow.com/questions/1155617/count-occurrence-of-a-character-in-a-string

Attribution for the unary one: https://stackoverflow.com/questions/1450897/python-removing-characters-except-digits-from-string

# Answer
> 0 votes
# Aceto, ~~21~~ 19 bytes

```
Ic!_
o=ML
d'I`
,dOp

```

We read a character and duplicate it, then push a "d" and increment its value to have an e. We then store the equality with `M`. *Now* we invert the input to get True when we're done, and conditionally jump to the print command at the end. Otherwise, we load our other truth value (whether it was an e), conditionally increment, and jump back to the `O`rigin.

# Answer
> 0 votes
## CJam, 10 bytes

It's annoying that the operation to count the number of instances, `e=`, contains an `e`.

```
q"&dd<":)~

```

This creates a string `&dd<` , increments every code point to get `'ee=`, and then executes it.

# Answer
> 0 votes
# PHP, 27 Bytes

```
<?=count_chars($argn)[101];

```

Try it online!

# Answer
> 0 votes
# Scala, 20 bytes

```
_.count(_=='\u0065')

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 4 bytes

```
Ƶ0ç¢

```

Try it online!

```
Ƶ0   # Push 101
  ç  # Convert to a character
   ¢ # Count the occurrences of that character

```

# Answer
> 0 votes
# Retina, 11 bytes

```
T`d-f`_f_
f

```

Try it online! `e` is indirectly referred to in the translation by creating a range from `d` to `f`. The `d`s and `f`s are deleted and the `e`s are translated to `f`s (we can't use `d` because that would expand to `0-9`). It then suffices to count the `f`s.

---
Tags: code-golf, string, restricted-source
---


title: Tips for golfing in V

text:
# Question
Title: Tips for golfing in V
What general tips do you have for golfing in V? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to V (e.g. "remove comments" is not an answer).

Since V is heavily based on vim, most of the tips for golfing vim would apply too. But there are some features in V that don't really apply to vim.

Please post one tip per answer.

# Answer
Take advantage of implicit endings!

In V, every single command will be implicitly finished if you don't actually finish out the command. For example, if the program ends in insert mode, the `<esc>` will be filled in automatically. Usually, this doesn't make any difference. However, if you have a count before the `i`, you have to actually hit `<esc>` at the end for the text to be inserted multiple times. So you can do `2i2i` for a quine, whereas in vim you would need `2i2i<esc>`, which is no longer a quine.

This also applies to ex commands, and psuedo ex-commands such as compressed regexes. So where vim needs

```
:foo<cr>

```

V can do

```
:foo

```

if it's at the end of the program.

But here is where it gets really cool: The implicit ending applies several layers deep. For example, consider this command:

```
òçfoo/óa

```

This translates to:

```
ò           " Recursively:
 çfoo/      "   On every line matching 'foo'
      óa    "     Remove the first 'a'

```

Without implicit endings, the `ó` needs a `<cr>`, the `ç` needs a `<cr>`, and the `ò` needs another `ò`. But none of these are needed with implicit endings! The interpreter will fill in the needed `ò`, the recursive command will fill in the `<cr>` that `ç` needs, and the `ç` command will fill in the `<cr>` that `ó` needs. This saves us 3 bytes.
> 4 votes

# Answer
Carefully choose how you take input.

V can take input two different ways: *input* and *args*. It can even take both at the same time! Choosing how you take input can sometimes save you many bytes. Here is how the two input formats work:

* The *input* is the text that is loaded into the buffer. Generally, this is more convenient for string inputs.
* The *args* are stuffed into the first *n* registers, depending on how many args are given. For example, if 5 args are given, these will be loaded into registers a-e. Since you can run these registers with `@<reg>`, these are generally more convenient for numeric input.

Lets make a hypothetical example. Our hypothetical challenge is:

> Given a string *s*, and an integer *n*, output *s* *n* times, separated by a newline.

In vim, you can only take input into the buffer. So you'd need to take the input on two lines, for example

```
n
s

```

And run

```
DJY@-pdd

```

The `D` to delete n into register '-', the `J` to remove the extra newline, and then `@-p` to paste s *n* times, and dd to take care of the extra copy. In V, you can take *s* as input, and *n* as an arg. Then you could shorten this too:

```
@apdd

```

of course, there's still a few ways to shorten this even more. For example, `Ä` makes *n* copies, rather than pasting *n* times. And `À`, or `<M-@>` will cycle through all of these args, so the first time it's called it is equivalent to `@a`. So you can simply do:

```
ÀÄ

```

The `À` will command will also loop back once you go through all of the args. So if you have 3 arguments, running `À` repeatedly will run

```
@a
@b
@c
@a
@b
@c
@a
...

```
> 3 votes

---
Tags: code-golf, tips, vim
---


title: Create your own Red and Black

text:
# Question
Title: Create your own Red and Black
In the musical rendition of Les Miserables, a song appears called "Red and Black." Here is part of that song:

> Red - the blood of angry men!
>
> Black - the dark of ages past!
>
> Red - a world about to dawn!
>
> Black - the night that ends at last!

Source.

Your task is to turn input into a resounding "Red and Black" anthem.

# Input

Text delimited by newlines, or a similar suitable text input. For example,

```
The blood of angry men!
The dark of ages past!
A world about to dawn!
The night that ends at last!

```

Empty input is undefined (out of scope).

# Output

If the length (number of lines, or length of input array, or similar) of the input is odd, either output nothing or output falsey. Your submission may not output errors or attempt to output the correct output.

Otherwise, turn the input into a Red/Black lyric. Turn any uppercase letters at the start of a line to lowercase. Add `Red` plus a delimiter to the front of odd lines, and `Black` plus a (visible) delimiter to the front of even lines. The delimiter must also be surrounded in spaces, so the output looks uncrowded (and ungolfed ;) ).

You now have your output.

# Test Cases

Output delimiter is `-`.

```
In:
The blood of angry men!
The dark of ages past!
A world about to dawn!
The night that ends at last!

Out:
Red - the blood of angry men!
Black - the dark of ages past!
Red - a world about to dawn!
Black - the night that ends at last!

In:
test test
1
[][][]
BBB

Out:
Red - test test
Black - 1
Red - [][][]
Black - bBB

In:
I feel my soul on fire!
The color of desire!
The color of despair!
Out:
falsey OR nothing

In:
Red - I feel my soul on fire!
Black - My world if she's not there!

Out:
Red - red - I feel my soul on fire!
Black - black - My world if she's not there!

```

# Answer
# 05AB1E, 26 bytes

### Code:

```
|©v”†¾ƒÏ”#Nè… - yćlìJ®gÈ×,

```

Uses the **05AB1E** encoding. Try it online!

### Explanation:

```
|                               # Take the input as an array of inputs
 ©                              # Keep a copy of this in the register
  v                             # Map over the array
   ”†¾ƒÏ”#                      #   Push the array ["Red", "Black"]
          Nè                    #   Get the Nth element (where N is the iteration index)
            … -                 #   Push the string " - "
                yć              #   Push the current element and extract the first element
                  lì            #   Convert to lowercase and prepend back to it's
                                    original place
                    J           #   Join the entire stack into a single string
                     ®g         #   Get the length of the input
                       È        #   Check if it is even (results in 1 or 0)
                        ×       #   String multiply the result by the string
                         ,      #   Pop and print with a newline

```
> 4 votes

# Answer
# , ~~31~~, 30 bytes

```
êuòIRed -
IBlack -
òñFRdH

```

Try it online!

Hexdump:

```
00000000: 16ea 75f2 4952 6564 202d 201b 0a49 426c  ..u.IRed - ..IBl
00000010: 6163 6b20 2d20 1b0a f2f1 4652 6448       ack - ....FRdH

```

This is trivial in V, but the edge case of odd inputs makes it tricky because V doesn't really have conditionals. Thankfully, we can handle this at the relatively small cost of `+6` bytes.
> 5 votes

# Answer
# Haskell, ~~104~~ ~~120~~ ~~113~~ ~~112~~ ~~111~~ 110 bytes

```
import Data.Char
f x|odd$length$x=mempty|1<2=Just$zipWith(\(h:t)x->x++toLower h:t)x$cycle["Red - ","Black - "]

```

Try it online!

## Ungolfed with explanation

```
import Data.Char

f :: [String] -> Maybe [String]
f x
  | even $ length $ x = Just $ zipWith (\(h : t) x -> x ++ toLower h : t) x $ cycle ["Red - ","Black - "]
  | otherwise         = Nothing

```

`f` is a function that takes a list of strings (a.k.a. a list of lists of `Char`s), and returns `Maybe` the same. Haskell's functions are quite "pure", and so we need to make it clear that this function may not return anything. (A function of type `Maybe a` returns either `Nothing` or `Just a`).

The `|` operator is a guard - a kind of conditional. The first branch is followed if `even $ length $ x` (which is another way of writing `even (length x)`) is `True`. Otherwise, the second one (`1<2` in the golfed example, which is of course always true) is followed and we return `Nothing`.

`zipWith` takes a two-argument function and applies it to each element of two lists. The function we're using here is `\(h : t) x -> x ++ toLower h : t`. `h : t` implicitly splits the first character off our first argument, which is the kind of nice thing you can do in Haskell. The first list is the input (which we already know contains an even number of lines), and the second is just infinitely alternating "Red - " and "Black - " (infinite lists are another nice thing that's possible, this time because Haskell is lazy - it only cares about as much of something as you use).
> 5 votes

# Answer
# Japt, ~~36~~ ~~35~~ 34 bytes

Outputs `0` for `false`. Includes an unprintable after the second `R`.

```
èR u ©¡[`R Black`¸gY '-XhXg v]¸}R

```

Try it online
> 3 votes

# Answer
# Jelly, 29 bytes

```
0
“ZœĠk»ḲṁJżj€“ - ”Y
ỴŒl1¦€LĿ

```

A full program.
Uses the "falsey" output option for inputs with an odd number of lines.

**Try it online!**

### How?

```
0 - Link 1, return a falsey value: no arguments
0 - well, yeah, zero - that's falsey.

“ZœĠk»ḲṁJżj€“ - ”Y - Link 2, format the lines: list of lists of characters, the lines
“ZœĠk»             - "Red Black"
      Ḳ            - split at spaces -> ["Red","Black"]
        J          - range(length(lines)) -> [1,2,3,...,nLines]
       ṁ           - mould -> ["Red","Black","Red","Black",...,"Red","Black"]
         ż         - zip with lines -> [["Red",l1],["Black",l2],...]
            “ - ”  - " - " (really I cant find any save :/)
          j€       - join for each -> ["Red - l1","Black - l2",...]
                 Y - join with newlines

ỴŒl1¦€LĿ - Main link: string
Ỵ        - split at newlines
   1¦€   - apply to index 1:
 Œl      -   convert to lower case
       Ŀ - call link at index:
      L  -   length - Note: this is modular, so:
         -                  link 2 is called for even, and
         -                  link 1 is called for odd.

```
> 3 votes

# Answer
# C, ~~112~~ ~~107~~ ~~105~~ ~~103~~ 99 bytes

-4 thanks to ASCII-only
-2 thanks to Mego

```
i;main(a,s)char**s;{for(;a%2&++i<a;)printf("%s - %c%s\n",i%2?"Red":"Black",tolower(*s[i]),s[i]+1);}

```

Takes an "array" as input. Example:

```
bash$ ./a.out "The blood of angry men!" "The dark of ages past!" "A world about to dawn!"
bash$ ./a.out "The blood of angry men!" "The dark of ages past!" "A world about to dawn!" "The night that ends at last!"
Red - the blood of angry men!
Black - the dark of ages past!
Red - a world about to dawn!
Black - the night that ends at last!

```

### How it works

* `i` creates a variable `i` outside of all functions, which means it's automatically initialized to 0.
* `main(a,s)char**s;{` declares the main function, which takes two arguments - an `int a` (# of command line arguments), and a `char ** s` (array of command line arguments).
* `for(;a%2&++i<a;)` is a loop that checks if `a` is even (`a%2`) and if it's less than the number of command line arguments passed (`i<a`).
* `printf("%s - %c%s\n",i%2"Red":"Black",tolower(*s[i]),s[i]+1` prints:
    + "Red" if `i` is odd, "Black" if `i` is even (`i%2?"Red":"Black"`)
    + The first letter of the current command-line argument in lowercase (`tolower(*s[i])`)
    + The string, without the first letter (`s[i]+1`)

Try it online!
> 3 votes

# Answer
# Röda, 97 bytes

```
f a{seq 0,#a-1|[_,a[_1]/""]|[["Red","Black"][_%2],` - `,lowerCase(_[0]),_2[1:]&"",`
`]if[#a%2<1]}

```

Try it online!
> 2 votes

# Answer
# Jelly, 30 bytes

```
LḂṆẋ@Ỵµ“ZœĠk»ḲṁL;€“ - ”żŒl1¦€Y

```

Try it online!
> 1 votes

# Answer
# Retina, 58 bytes

```
Tm`L`l`^.
m`^
Red -
(Red - .*¶)Red
$1Black
^(.*¶.*¶)*.*$

```

Try it online!
> 1 votes

# Answer
# Python 2, 215-\>184-\>165 bytes

Saved 31 bytes according to Stephen S' comment

Challenger5 got it down to 165 bytes

```
l=[]
b=["Red","Black"]
d=" - "
while 1:
 a=raw_input()
 if a:l.append(a)
 else:break
q=len(l)
if q%2<1:
 for i in range(q):n=l[i];print b[i%2]+d+n[0].lower()+n[1:]

```

Try it online!
> 1 votes

# Answer
## CJam, 41 bytes

```
qN/{(el\+}%2/"Red -
Black - "N/f.\:~2/N*

```
> 1 votes

# Answer
# Javascript, 118 bytes

```
v=s=>(s=s.split`\n`).length%2==0?s.map((l,i)=>(i%2==0?'Red':'Black')+' - '+l[0].toLowerCase()+l.substr`1`).join`\n`:!1

```

Test

```
//code
v=s=>(s=s.split`\n`).length%2==0?s.map((l,i)=>(i%2==0?'Red':'Black')+' - '+l[0].toLowerCase()+l.substr`1`).join`\n`:!1

//tests
t0 = "The blood of angry men!\nThe dark of ages past!\nA world about to dawn!\nThe night that ends at last!";
t1 = "test test\n1\n[][][]\nBBB";
t2 = "I feel my soul on fire!\nThe color of desire!\nThe color of despair!";
t3 = "Red - I feel my soul on fire!\nBlack - My world if she's not there!";

console.log( v(t0) );
console.log( v(t1) );
console.log( v(t2) );
console.log( v(t3) );
```
> 1 votes

# Answer
# JavaScript (ES6), 93 bytes

Takes the song as an array of lines.

```
S=>S.length%2?0:S.map((L,i)=>(i%2?'Black':'Red')+' - '+L[0].toLowerCase()+L.slice(1)).join`
`

```

```
f=
S=>S.length%2?0:S.map((L,i)=>(i%2?'Black':'Red')+' - '+L[0].toLowerCase()+L.slice(1)).join`
`

console.log(f([
  'The blood of angry men!',
  'The dark of ages past!',
  'A world about to dawn!',
  'The night that ends at last!'
]))

console.log(f([
  'The blood of angry men!',
  'The dark of ages past!',
  'A world about to dawn!'
]))
```
> 1 votes

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


# Question
Title: "Write" a simple calculator without writing a single line of code
It's very easy:

Create a program without writing a single line of code. The code may only consist of existing Stack Overflow questions and answers.

The program should create two random numbers and output the numbers

* added to,
* subtracted from,
* multiplied with and
* divided by

each other.

**Rules**

You must include links to the questions/answers you used in your answer. You may not modify the code you find, with the following exceptions:

1. You may rename variables, functions, and methods. (This doesn't mean you can change a method invocation, by changing, say scanner.nextInt() to scanner.nextLine() and claiming that you're changing a method name. The change must be in the definition or reference to the same entity.). The solution should still work if variables, functions or methods would be renamed again.
2. You may adjust indentation appropriately.
3. You can assume that the proper modules are loaded for the code snippets to work. (e.g., import statements for Java and Python, using statements for C# and C++, and their equivalents in all languages) If the code snippet includes the imports for you, you can move them to the top of the code.
4. If the language requires the code to be in some kind of method body to execute (e.g., `public static void main(String[] args)` for Java, `static int Main(string[] args)` for C#, and so on), you can wrap your code in the appropriate method. But the contents of that main method must remain unmodified.
5. You must supply an explicit list of any variable/method/function/class renamings performed.
6. You can't take snippets of snippets (meaning if you take a code block from a post, you take the whole thing) Provide a brief description of what the code does for people who aren't intimate with the language you're using. You must use snippets posted before this challenge was started.

**Popularity contest, so the most upvotes wins!**

**Deadline**

I will accept the the submission that has the most votes around the end of August, 6.

# Answer
# J, 7 questions/answers, none about J

```
echo a%b[echo a*b[echo a-b[echo a+b[b=:?2147483647 [a=:?2147483647

```

It's a pretty damn cheap way to do it, I'm not gonna lie. Here are the SO answers I used:

I renamed variable `foo` as `a` and `b` in the code.
> 18 votes

# Answer
# Python 2, ~~7~~ 6 references

Creating this solution wasn't as easy as it looked. Searching Stack Overflow for specific code is difficult, since symbols are not included in the search.

I had found a way to do this with 2000-bit random numbers, using a different answer in place of Ref #1, ~~but I couldn't test it on the online environments I use since it involves `getrandbits`, which calls `os.urandom`, giving me a `NotImplementedError`, so I went this way instead.~~ This could actually be used now, with TIO.

**Try it online**

```
#assumed to be loaded
import random

n1 = []
n1.append(random.randint(1, 100))

n2 = []
n2.append(random.randint(1, 100))

r1 = map(sum, zip(n1, n2))
r2 = map(lambda t: t[0] - t[1] ,zip(n1, n2))

ab = [n1[i]*n2[i] for i in range(len(n1))]

r1, last = r1[0], r1[-1]
r2, last = r2[0], r2[-1]
ab, last = ab[0], ab[-1]
n2, last = n2[0], n2[-1]

print r1
print r2
print ab
ab = float(ab) / n2
ab = float(ab) / n2
print ab

```

### References

`import random` is assumed to be loaded, since the question says that's allowed.

1. `lst = []` and `lst.append(random.randint(1, 100))` \- Here
2. `map(sum, zip(r1, r2))`, `map(lambda t: t[0] - t[1] ,zip(r1, r2))`, `r1`, and `r2` \- Here
3. `result = float(a) / b` \- Here
4. `ab = [a[i]*b[i] for i in range(len(a))]` \- Here
5. `first, last = some_list[0], some_list[-1]` \- Here
6. `print x` \- Here

### Renamed

1. `lst` renamed to `n1` and `n2` (Ref #1: I used the entire code twice)
2. `r1` and `r2` renamed to `n1` and `n2` (Ref #2: I used the separate variables later though, to assign the maps and to divide in the last print, since the answer included them. )
3. `result` and `a` renamed to `ab`, and `b` renamed to `n2` (Ref #3)
4. `a` and `b` renamed to `n1` and `n2` (Ref #4)
5. `first` and `some_list` both renamed to `r1`, `r2`, `ab`, or `n2`, depending on which line. (Ref #5: I used this four times. Note that only the first assignment is used, so I don't rename `last`)
6. `x` is renamed to `r1`, `r2`, or `ab`, depending on which line. (Ref #6)
> 7 votes

# Answer
# Decimal, 2 references

```
82D82D00D30001D30041D301212010D301200D30001D30042D301212010D301200D30001D30043D301212010D301200D30001D30044D30122

```

Commands used:

* `0` SET (default stack index)
* `1` PUSH
    + `2` CHAR
* `2` POP
* `3` I/O
    + `00` duplicate stack
    + `01` from stack to STDOUT
* `4` MATH
    + `1` ADD
    + `2` SUBTRACT
    + `3` MULTIPLY
    + `4` DIVIDE
* `8` BUILTIN
    + `2` push random integer to stack

Explained version:

```
82D       ; push random INT    - stack contains {r1}
82D       ; push random INT    - stack contains {r1, r2}

00D300    ; duplicate stack[0] - stack contains {r1, r2, r1}
01D300    ; duplicate stack[1] - stack contains {r1, r2, r1, r2}
41D       ; math +             - stack contains {r1, r2, r1+r2}
301       ; print from stack to output
2         ; pop                - stack contains {r1, r2}

12010D3012; print newline

00D300    ; duplicate stack[0] - stack contains {r1, r2, r1}
01D300    ; duplicate stack[1] - stack contains {r1, r2, r1, r2}
42D       ; math -             - stack contains {r1, r2, r1-r2}
301       ; print from stack to output
2         ; pop                - stack contains {r1, r2}

12010D3012; print newline

00D300    ; duplicate stack[0] - stack contains {r1, r2, r1}
01D300    ; duplicate stack[1] - stack contains {r1, r2, r1, r2}
43D       ; math *             - stack contains {r1, r2, r1*r2}
301       ; print from stack to output
2         ;                    - stack contains {r1, r2}

12010D3012; print newline

00D300    ; duplicate stack[0] - stack contains {r1, r2, r1}
01D300    ; duplicate stack[1] - stack contains {r1, r2, r1, r2}
44D       ; math /             - stack contains {r1, r2, r1/r2}
301       ; print from stack to output

```

Sources:

Try it online! You'll need to disable the output cache if it's not automatically disabled.
> 1 votes

---
Tags: popularity-contest, arithmetic, duct-tape-coding
---


title: Dankify this string

text:
# Question
Title: Dankify this string
**Challenge**

An ascii string is made 'dank' when exactly one space is inserted between any two consecutive letters and all capital letters are replaced with lowercase ones. In this challenge I would like you to write a program that takes a string (not necessarily 'dank') as input and outputs a 'dank' version of that string.

**Specification**

Your program should take as input an ascii string of arbitrary length and output another ascii string.

A string is classed as *dank* when it contains only spaces and lowercase letters such that there is exactly one space between any two consecutive letters. To make a string *dank* you'll have to strip all non-alphabetical characters, replace capital letters with their lowercase counterparts, then insert spaces between all the characters.

**Example**

```
"aesthetic" > "a e s t h e t i c"
"How are you?" > "h o w a r e y o u"
"drop // top" > "d r o p t o p"

```

**Winning criterion**

Code golf so the shortest code in bytes wins.

g o o d l u c k

# Answer
# 05AB1E, ~~6~~ 5 bytes

-1 byte thanks to Erik

```
láSðý

```

Explanation:

```
l        Convert to lowercase
 á       Remove all non-alphabetic characters
  S      Get characters as array
   ðý    Join by spaces

```

Try it online!
> 2 votes

# Answer
# Japt, ~~16~~ 5 + 1 (`-S` flag) = 6 bytes

*Thanks to obakaron for saving 10 bytes*

```
;v fE

```

Try it online!
> 1 votes

# Answer
# Python 3.5, ~~46~~ ~~49~~ 47 bytes

```
print(*[i for i in input().lower()if'`'<i<'{'])

```

Try it online!
> 1 votes

# Answer
# Jelly, 6 bytes

```
ŒlfØaK

```

A monadic link taking and returning lists of characters (or a program that prints the result).

**Try it online!**

### How?

```
ŒlfØaK - Main link: list of characters, s
Œl     - convert to lowercase (vectorises)
   Øa  - yield lowercase alphabet: "abcdefghijklmnopqrstuvwxyz"
  f    - filter keep
     K - join with spaces
       - if running as a program implicit print

```
> 1 votes

# Answer
# Decimal, 92 bytes

```
91D31030012090D415D56112032D41D625230012122D416D5291D5230012097D417D5291D52301212032D301291D

```

Whew, that was fun. Thanks for the challenge - it helped me develop Decimal into a fully working language. (While writing this, I realized a few flaws. Just bugs and such.)

Ungolfed:

```
91D
 310 300    ; input to stack, duplicate
 12090D     ; push CHAR 'Z' to stack
 415D       ; compare <, pop values used, push result

 5          ; if truthy
  61        ;  put result into memory
  12032D    ;  push CHAR 32 to stack
  41D       ;  math +, pop values used, push result
  62        ;  pop memory to stack
 5          ; endif

 2          ; pop

 300        ; duplicate DSI
 12122D     ; push CHAR 'z' to stack
 416D       ; compare >, pop values used, push result
 5          ; if truthy
  291D      ; pop, restart
 5          ; endif

 2          ; pop

 300        ; duplicate DSI
 12097D     ; push CHAR 'a' to stack
 417D       ; compare <, pop values uesd, push result
 5          ; if truthy
  291D      ; pop, restart
 5          ; endif

 2          ; pop

 3012       ; print, pop
 12032D3012 ; push CHAR ' ', print, pop
91D

```

Try it online!
> 1 votes

# Answer
# Perl 6, 18 bytes

```
{m:g/<:L>/.Str.lc}

```

`m:g/<:L>/` produces a list of all of the letters in the input string; `.Str` converts the list into a string with a space between each element; and `.lc` converts the string to lower case.
> 0 votes

# Answer
# Pyth, 6 bytes

```
jd@Gr0

```

Try it here!
> 0 votes

# Answer
# Python 2, ~~55~~ ~~50~~ ~~53~~ 50 bytes

*-3 bytes thanks to ETHproductions.*

```
lambda s:' '.join(i for i in s.lower()if'`'<i<'{')

```

Try it online!
> 0 votes

# Answer
# C, 65 bytes

```
c;f(){for(;~c;c=getchar())!isalpha(c)?:printf("%c ",tolower(c));}

```

How it works:

* `c` declares an integer `c`, and sets it to 0 by default.
* `for(;~c;` declares a loop that will only continue if performing a bitwise NOT on `c` is true. NOT will return false only if `c` is EOF (meaning there is no more input).
* `c=getchar()` reads a character from input into `c`.
* `!isalpha(c)?:` checks if `c` is in the alphabet. If so...
* `printf("%c ",tolower(c));` prints the character in lowercase, then a space.

Try it online!
> 0 votes

# Answer
# shortC, 40 bytes

```
c;AO;~c;c=G)!isalpha(c)?:R"%c ",tolower(c

```

Conversions in this program:

* `A` -\> `int main(int argc, char **argv){`
* `O` -\> `for(`
* `G` -\> `getchar()`
* `R` -\> `printf(`
* Auto-inserted closing `));}`

Try it online!
> 0 votes

# Answer
# PHP, 68 Bytes

```
<?=chunk_split(preg_replace("#[^a-z]#","",strtolower($argn)),1," ");

```

Try it online!

## PHP, 70 Bytes

```
<?=join(" ",str_split(preg_replace("#[^a-z]#","",strtolower($argn))));

```

Try it online!

or

```
<?=preg_replace(["#[^a-z]#","#.(?=.)#"],["","$0 "],strtolower($argn));

```

Try it online!
> 0 votes

# Answer
# Retina, 14 bytes

```
T`Llp`ll_
\B

```

Try it online! This is so simple I don't even need a header to run multiple testcases. All uppercase letters are lowercased, lowercase letters are also lowercased for consistency, and everything else is deleted. Then spaces are inserted between every pair of letters.
> 0 votes

# Answer
## JavaScript (ES6), 53 bytes

```
s=>[...s.toLowerCase().replace(/[^a-z]/g,'')].join` `

```

Sometimes the straightforward way is the shortest...

Here are a few successively more fun versions using array comprehensions (only works in Firefox 30+):

```
s=>[for(x of s.toLowerCase())if('`'<x&x<'{')x].join` `
s=>[for(x of s)if(parseInt(x,36)>9)x.toLowerCase()].join` `
s=>[for(x of s)if((x=parseInt(x,36))>9)x.toString(36)].join` `

```

If we can assume the input contains at least one letter, this will work for 42:

```
s=>s.toLowerCase().match(/[a-z]/g).join` `

```
> 0 votes

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


title: Add and multiply perplexing numbers

text:
# Question
Title: Add and multiply perplexing numbers
The split-complex numbers, also known as "perplex numbers" are similar to the complex numbers. Instead of `i^2 = -1`, however, we have **`j^2 = 1; j != +/-1`**. Each number takes the form of `z = x + j*y`.

In one attempt to limit the complexity of this challenge, I will use the symbol `-` to represent negation, as there will not be any subtraction.

Here are some examples for your viewing pleasure:

```
6 * 9 = 54            // real numbers still act normally
5 + -7 = -2
j*1 + j*1 = j*2           // two `j`s added together make a j*2
7 * j*1 = j*7           // multiplication is commutative & associative
j*1 + 2 = 2+j*1           // like oil and water, "combine" to form a split-complex number
j*1 + j*-3 = j*-2          // seems okay so far
j*j*1 = j*-1*j*-1 = 1     // kinda sketchy, but such is its inherent nature
j*j*-1 = j*-1*j*1 = -1
(2+j*3)+(4+j*7) = 6+j*10  // combine like terms
7 * (2+j*3) = 14+j*21 // distributive property
j * (2+j*3) = (j*2) + (j*j*3) = 3+j*2   // since j^2 = 1, multiplying my j "swaps" the coefficients
(2+j*3)*(4+j*7) = (2*4)+(2*j*7)+(j*3*4)+(j*3*j*7) = 8+j*14+j*12+21 = 29+j*26 // a complete multiplication

```

## Challenge

The goal of this challenge is to evaluate an expression with split-complex numbers.

This is **code-golf,** the fewest bytes wins.

**Input**

Input will be a single line containing only the symbols `+*()-`, the digits `0123456789`, and the letter `j`, with an optional newline. This string represents an expression, using infix notation and operator precedence (multiplication before addition, with parenthesis grouping).

* The symbol `-` will always represent negation, never subtraction. **If you so desire, you can replace `-` with either `_` or `~`** for ease of I/O.
* Parenthesis can be nested up to three times to denote grouping: `(1+(1+(1)))`
* The letter `j` will never be directly prefixed with negation, and will always be followed by `*`.
* Parentheses will not be preceded by negation `-(7)`, but instead like `-1*(j*5+2)`
* There will never be implicit operations. All multiplication will be expressed as `(7)*7` instead of `(7)7`, and as `j*5` instead of `j5`.
* No leading zeros.

**Output**

Output will be in the form of `X+j*Y`, where X and Y can be any integer. If an integer is negative, it should be prefixed with the negation sign.

## Additional Restrictions

Although I am not aware of any language with native support, built-ins that deal with split-complex numbers are forbidden. Regular complex numbers are fair game.

## Test Cases

Similar to the above examples, but tidied up. Input on one line and output the line beneath.

```
(2+j*3)+(4+j*7)
6+j*10

(2+j*3)*(4+j*7)
29+j*26

(-5+j*1+j*2+2)*(4+j*7)
9+j*-9

(1+j*-1)*(1+j*1)
0+j*0 // this is why division does not exist.

j*((j*-1)+2)
-1+j*2

(2+(5+-1*(j*1))+2)
9+j*-1

```

# Answer
## Python 2, 62 bytes

```
def f(s):b,a=[eval(s)/2.for j in-1,1];print'%d+j*%d'%(a+b,a-b)

```

We simply evaluate the expression `s` with `j=1` and `j=-1`, and output half their sum and half their difference as the coefficients of `1` and `j`.

This works because both `j=1` and `j=-1` satisfy the defining equation defining equation `j*j==1`. So, the original and simplified expressions must be equal for both these values. The simplified expression is linear, so this gives two linear equations in two unknowns:

```
x + 1*y  = s(1)  = 2*a
x - 1*y  = s(-1) = 2*b

```

which is solved by `x=a+b, y=a-b`.
> 14 votes

# Answer
# Python 2, 258

```
class c(complex):__mul__=lambda s,o:c(s.real*o.real+s.imag*o.imag,s.real*o.imag+s.imag*o.real);__add__=lambda s,o:c(sum(map(complex,[s,o])))
import re
r=eval(re.sub("j","c(0,1)",re.sub(r"(-?\d+)",r"c(\1)",raw_input())))
print`int(r.real)`+"+j*"+`int(r.imag)`

```

This is probably not the best approach, but it was the first time that OOP looked like a passable idea in Python for code golf, so why not?

Creates a class `c` that inherits from complex but has a different `mul` operation. The `add` operation is also changed so that it returns an object of type `c` and not `complex`, this behaviour is necessary to prevent the case of `(a + b) * (c + d)` doing complex multiplication instead of this special kind.

The input string is then converted into a string that can be evaluated naturally by python. It does this by changing every number into `c(number)` and then every `j` into `c(0,1)`.

Try it online or run a Test Suite
> 2 votes

# Answer
## GAP, 38 bytes

```
j:=X(Integers,"j");f:=t->t mod(j^2-1);

```

First `j` is defined to be an indeterminate, so we can create polynomials in `j`. To get the corresponding perplexing number, we reduce (i.e. take the remainder of polynomial division) by `j^2-1`. This gives a linear (or constant) term, and we can rely on GAP's ability to output polynomials.

Examples:

```
gap> f((2+j*3)+(4+j*7));
10*j+6
gap> f((1+j*-1)*(1+j*1));
0

```

Caveat: 1. This does not take a string as input, but a real term in GAP's language. To fix, I could use `EvalString`. 2. The output is nice and clear, but not exactly as specified: Order is changed, and unnecessary zeroes are suppressed. I think and hope this is still in the spirit of the challenge, otherwise I guess I'd be better off using @xnor's matrix approach.
> 1 votes

# Answer
# Axiom, ~~20~~ 42 bytes

```
f(x,n)==x^(n rem 2);m:=rule('j^n==f('j,n))

```

the preceding solution have a problem if `n<0` in `j^n` but this it seems more solid, and advise well where there is something wrong, even if the perfection would be return example j^1.2 or j^sqrt(-1) the same expression not evaluate

```
(9) -> f(x,n)==x^(n rem 2);m:=rule('j^n==f('j,n))
         n
   (9)  j  == 'f(j,n)
                    Type: RewriteRule(Integer,Integer,Expression Integer)
(10) -> [m((2+j*3)+(4+j*7)), m((2+j*3)*(4+j*7)), m((-5+j*1+j*2+2)*(4+j*7))]
   (10)  [10j + 6,26j + 29,- 9j + 9]
                                            Type: List Expression Integer
(11) -> [m((1+j*-1)*(1+j*1)), m(j*((j*-1)+2)), m(2+(5+-1*(j*1))+2)]
   (11)  [0,2j - 1,- j + 9]
                                            Type: List Expression Integer
(12) -> [m(j*j*j*j),m(j*j*j),m(j^200)]
   (12)  [1,j,1]
                                            Type: List Expression Integer
(13) -> [m(j^0),m(j^-1),m(j^-2), m(j^-3)]
            1   1
   (13)  [1,-,1,-]
            j   j
                                            Type: List Expression Integer
(14) -> m(j^(3.4))
   There are no library operations named m
      Use HyperDoc Browse or issue

```

if i not follow some law of the question: say me that and i add "not competitive". I mean it as one axiom for simplify formula
> 1 votes

# Answer
## Batch, 52 bytes

```
@set/aj=1,a=%1,j=-1,a-=b=(a-(%1))/2
@echo %a%+j*%b%

```

After seeing @xnor's excellent answer nomination I felt compelled to port it.
> 0 votes

---
Tags: code-golf, arithmetic, complex-numbers
---


# Question
Title: How high can you count in different languages?
Based on How high can you count? let us give an advantage to the polyglot people.

## Challenge:

Your task is to write as many programs / functions / snippets as you can, where each one outputs / prints / returns an integer. The first program must output the integer `1`, the second one `2` and so on.

**You can not reuse any characters between the programs. So, if the first program is simply: `1`, then you may not use the character `1` again in any of the other programs.** Note: It's allowed to use the same character many times in one program.

**You can only use a programming language once.** So every number must be in a different programming language.

### Scoring:

The winner will be the submission that counts the highest. In case there's a tie, the winner will be the submission that used the fewest number of bytes in total.

### Rules:

* You can only use a language for one integer - after that you cannot reuse the language
* **Snippets are allowed!**
* To keep it fair, all characters must be encoded using a single byte in same encoding in the languages you choose.
* The output must be in decimal. You may not output it with scientific notation or some other alternative format. Outputting floats is OK, as long as all digits *that are shown* behind the decimal point are `0`. So, `4.000` is accepted. Inaccuracies due to FPA is accepted, as long as it's not shown in the output.
* `ans =`, leading and trailing spaces and newlines etc. are allowed.
* You may disregard STDERR, as long as the correct output is returned to STDOUT
* You may choose to output the integer to STDERR, but only if STDOUT is empty.

Note: Explanations are encouraged!

# Answer
> 8 votes
# GS2, 3var, Alphuck, brainf\***, Numberwang, evil, ;#+, Charcoal, Retina, wsf, Jelly, Beeswax, CJam, Fourier, Fireball, M, Pushy, MATL, Brain-Flak, Convex, COW, Mouse-79, Mouse-98, Mouse-2002, Pyke, Neim, JavaScript, Braingolf, Japt, SOGL, score 31

All are encoded as hex bytes in either ASCII or the language's native encoding

```
GS2 - 1: 01 01
3var - 2: 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64 64
Alphuck - 3: 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65 65
brainf*** - 4: 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b
Numberwang - 5: 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39
Evil - 6: 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61
;#+ - 7: 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b 3b
Charcoal - 8: b8
wsf - 9: 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
Jelly - 10: 85
Beeswax - 11: 50 50 50 50 50 50 50 50 50 50 50
CJam - 12: 43
Retina - 13: 0a 2e 2e 2e 2e 2e 2e 2e 2e 2e 2e 2e 2e 2e 0d 0a 2e
Fourier - 14: 5e 5e 5e 5e 5e 5e 5e 5e 5e 5e 5e 5e 5e 5e
Fireball - 15: 46
M - 16: 96
Pushy - 17: 54 74 74 74 74 74 74 74 74 74 74 74 74 74 74 74 74 74 74 74 74 74 74 74 74 74 74 74 7e
MATL - 18: 32 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51
Brain-Flak - 19: 28 28 29 28 29 28 29 28 29 28 29 28 29 28 29 28 29 28 29 28 29 28 29 28 29 28 29 28 29 28 29 28 29 28 29 28 29 28 29 29
Convex - 20: 4b
COW - 21: 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f 4d 6f 4f
Mouse-79 - 22: 57
Mouse-98 - 23: 58
Pylons - 24: 34 21
Mouse-2002 - 25: 5a
Pyke - 26: 4e 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68 68
Neim - 27: f9
JavaScript - 28: 30 78 31 63
Braingolf - 29: 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c 6c
Japt - 30: c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4 c4
SOGL - 31: 41 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49

```

More to come :)

also if i was allowed to use any language as many times as i want i would be able to get ~200

---
Tags: number, code-challenge, restricted-source, rosetta-stone
---


title: Battle of the letters

text:
# Question
Title: Battle of the letters
Your task is simple: tell me who wins the battle of the letters.

# The troops

There are three different "troops" in this battle, summarized by this table.

```
name | health | damage
   A       25       25
   B      100        5
   C       10       50

```

You may use any three unique characters to represent the the troops, but must specify if they are not these letters.

# The battle

Suppose we have a sample battle:

```
ABC # army 1
CBA # army 2

```

Each army repeatedly fires at the leftmost unit, until it is dead; then they move to the troop to the right and repeat. So army 2 attacks `A` in army 1 until `A` is dead, then move to `B`, then `C`. Army 1 attacks `C` first, then `B`, then `A`. Assume the armies attack at the same time, and thus troops will always fire if they were alive before the round and can kill each other at the same time. They fire in order from left to right.

The battle would play out as so:

```
ABC
CBA

BC # A (25 hp) killed by C (-50 hp), B (100 hp) attacked by B (-5 hp) and A (-25 hp), has 70 hp
BA # C (10 hp) killed by A (-25 hp), B (100 hp) attacked by B (-5 hp) and C (-50 hp), has 45 hp

BC # B (70 hp) attacked by B (-5 hp) and A (-25 hp), has 40 hp
A  # B (45 hp) killed by B (-5 hp) and C (-50 hp)

BC # B (40 hp) attacked by A (-25 hp), has 15 health
   # A (25 hp) killed by B (-5 hp) and C (-50 hp), army 2 dead

```

Therefore, army 1 wins the battle!

# Input

Two strings, the first representing army 1 and the second army 2. They are not necessarily the same size (because who said it would be a fair fight?)

# Output

Any three unique, constant values to represent army 1 winning, army 2 winning, or the unlikely event of a tie. Yes, it is possible for the last troops to kill each other, ending in a tie.

# Battles

```
ABC
CBA
Army 1

CCCCC
CCCCC
Tie

CABCAB
ABBABBA
Army 2

```

Standard loopholes apply. You must submit a full program.

This is , shortest solution wins.

# Answer
> 3 votes
# Pyth ~~145~~ 97 bytes

```
=Y.d[,\A,25 25,\B,*TT5,\C,T*5T)Km=G@YdzJm=H@YdwW&KJMX0hG_smedH gKJ gJKI<hhK0=tK)I<hhJ0=tJ;?K1?J2Z

```

A little less naive than before.

Try it online!

# Explanations:

Let's cut the program in several parts.

```
=Y.d[,\A,25 25,\B,*TT5,\C,T*5T)

     ,\A,25 25                     Create this list: ['A', [25, 25]]
              ,\B,*TT5             Create this list: ['B', [100, 5]]
                      ,\C,T*5T     Create this list: ['C', [10, 50]]
  .d[                         )    From the three lists, create a dictionary whose keys are the letters, and values are the inner lists
=Y                                 Assign to the variable Y

```

The dictionary `Y` is: `{'A': [25, 25], 'C': [10, 50], 'B': [100, 5]}`. Then:

```
Km=G@YdzJm=H@YdwMX0hG_smedH

 m=G@Ydz                           For all letters in first input string, make a copy of Y[letter]. Make a list of all those values...
K                                  ...and assign the list to the variable K
         m=H@Ydw                   For all letters in second input string, make a copy of Y[letter]. Make a list of all those values...
        J                          ...and assign the list to the variable J
                MX0hG_smedH        Create a function g which takes two lists of couples, and subtract the sum of the second elements of the couples of the second list from the first element of the first couple of the first list

```

At this point, `K` is a list of couples that represents the first army. Each couple of this list is a letter of the army, and is `(health, damage)` for that letter. `J` is exactly the same, but for the second army. `g` is a function which takes two armies, and deals the damage made by the second army to the first one. Now:

```
W&KJ gKJ gJKI<hhK0=tK)I<hhJ0=tJ;

W&KJ                               While K not empty and J not empty
     gKJ                           Call g(K,J). That computes the damages to first army
         gJK                       Call g(J,K). That computes the damages to second army
            I<hhK0=tK)             If the first army's first letter is dead, remove it
                      I<hhJ0=tJ    If the second army's first letter is dead, remove it
                               ;   End of while loop

```

When the while loop is over, `K` and `J` have their final value. If they are both empty, it's a tie; otherwise the non-empty army win. That is handled by the last piece of code:

```
?K1?J2Z

?K1                                If K non-empty, display 1. Else...
   ?J2                             ...if J non-empty, display 2. Else...
      Z                            ...display zero

```

That's it!

# Answer
> 2 votes
# Haskell, 199 193 179 176 171 bytes

```
a!b=(t<$>a)?(t<$>b)
t v=[(5,5),(20,1),(2,10)]!!(fromEnum v-65)
m=sum.map snd
f=filter((>0).fst)
[]?[]=0
[]?_=2
_?[]=1
a@((c,d):e)?b@((h,i):j)=f((c-m b,d):e)?f((h-m a,i):j)

```

Try it online!

Small trick: divided all the army stats by 5.

# Answer
> 0 votes
# C#, 446 Bytes

```
using System.Linq;(c,d)=>{int z=c.Length,v=d.Length,j=0,k=0,l=0,m=0,q=0;int[]e=(c+d).Select(x=>x!='A'?x=='B'?100:10:25).ToArray(),f=e.Skip(z).ToArray();e=e.Take(z).ToArray();int[]g=(c+d).Select(x=>x!='A'?x=='B'?5:100:25).ToArray(),h=g.Skip(z).ToArray();g=g.Take(z).ToArray();try{for(;;){for(q=l;q<z;q++){if(e[j]<=0)j++;e[j]-=h[q];}for(q=k;q<v;q++){if(f[m]<=0)m++;f[m]-=g[q];}if(e[k]<=0)k++;if(f[l]<=0)l++;}}catch{}return k-z>=l-v?k-z>l-v?0:2:1;};

```

Formatted version:

```
         (c, d) => {
                int z = c.Length, v = d.Length, j = 0, k = 0, l = 0, m = 0, q = 0;

                int[] e = (c + d).Select(x => x != 'A' ? x == 'B' ? 100 : 10 : 25).ToArray(), f = e.Skip(z).ToArray();
                e = e.Take(z).ToArray();

                int[] g = (c + d).Select(x => x != 'A' ? x == 'B' ? 5 : 100 : 25).ToArray(), h = g.Skip(z).ToArray();
                g = g.Take(z).ToArray();

                try {
                    for (;;) {
                        for (q = l; q < z; q++) {
                            if (e[j] <= 0) j++; e[j] -= h[q];
                        }
                        for (q = k; q < v; q++) {
                            if (f[m] <= 0) m++; f[m] -= g[q];
                        }
                        if (e[k] <= 0) k++; if (f[l] <= 0) l++;
                    }
                }
                catch {
                }

                return k - z >= l - v ? k - z > l - v ? 0 : 2 : 1;
            };

```

Outputs 1 if army1 wins , 2 for army2 and 0 for tie

# Answer
> 0 votes
# Javascript (ES6) - ~~316~~ 269 Bytes

I'm sure this can be golfed like hell, but this is what I've come up with :) I managed to shave off 47 bytes though!

Outputs 0 for tie, 1 for Team 1 and 2 for Team 2.

```
l=(d,f)=>{for(t=[d,f].map(g=>g.split``.map(k=>[[25,100,10],[25,5,50]].map(m=>m[k.charCodeAt()-65])));(w=t.map(g=>g.some(k=>0<k[0])))[0]&&w[1];)t.forEach((g,k,m)=>m[k].sort(o=>0>o[0])[0][0]-=m[+!k].filter(o=>0<o[0]).reduce((o,p)=>o+p[1],0));return w[0]||w[1]?w[0]?1:2:0}

```

**Readable**:

```
function ltt(a,b){
    t=[a,b].map(x=>x.split``.map(c=>[[25,100,10],[25,5,50]].map(e=>e[c.charCodeAt()-65])))
    while((w=t.map(_=>_.some(x=>x[0]>0)))[0]&&w[1]){
        t.forEach((y,i,n)=>n[i].sort(j=>j[0]<0)[0][0]-=n[+!i].filter(x=>x[0]>0).reduce((h,v)=>h+v[1],0))
    }
    return(!w[0]&&!w[1])?0:(w[0])?1:2
}

```

**Demo**:

```
l=(d,f)=>{for(t=[d,f].map(g=>g.split``.map(k=>[[25,100,10],[25,5,50]].map(m=>m[k.charCodeAt()-65])));(w=t.map(g=>g.some(k=>0<k[0])))[0]&&w[1];)t.forEach((g,k,m)=>m[k].sort(o=>0>o[0])[0][0]-=m[+!k].filter(o=>0<o[0]).reduce((o,p)=>o+p[1],0));return w[0]||w[1]?w[0]?1:2:0}

var prnt=(g,h)=>{
  n=l(g,h);
  return(n==0)?"Tie!":`Team ${n} wins!`
}

console.log("ABCB - ABC: " + prnt("ABCB","ABC"));
console.log("BAAA - BBC: " + prnt("BAAA","BBC"));
console.log("AAAA - BBC: " + prnt("AAAA","BBC"));
console.log("ABC - BBC: " + prnt("ABC","BBC"));
console.log("ABC - CBA: " + prnt("ABC","CBA"));
```

---
Tags: code-golf
---


title: Roll to see all sides!

text:
# Question
Title: Roll to see all sides!
Let's say you have a 20-sided die. You start rolling that die and have to roll it a few dozen times before you finally roll all 20 values. You wonder, how many rolls do I need before I get a 50% chance of seeing all 20 values? And how many rolls of an `n`-sided die do I need to roll before I roll all `n` sides?

After some research, you find out that a formula exists for calculating the **chance** of rolling all `n` values after `r` rolls.

```
P(r, n) = n! * S(r, n) / n**r

```

where `S(a, b)` denotes Stirling numbers of the second kind, the number of ways to partition a set of n objects (each roll) into k non-empty subsets (each side).

You also find the OEIS sequence, which we'll call `R(n)`, that corresponds to the smallest `r` where `P(r, n)` is at least 50%. The challenge is to calculate the `n`th term of this sequence as fast as possible.

**The challenge**

* Given an `n`, find the **smallest** `r` where `P(r, n)` is greater than or equal to `0.5` or 50%.
* Your code should theoretically handle any non-negative integer `n` as input, but we will only be testing your code in the range of `1 <= n <= 1000000`.
* For scoring, we will be take the total time required to run `R(n)` on inputs `1` through `10000`.
* We will check if your solutions are correct by running our version of `R(n)` on your output to see if `P(your_output, n) >= 0.5` and `P(your_output - 1, n) < 0.5`, i.e. that your output is actually the smallest `r` for a given `n`.
* You may use any definition for `S(a, b)` in your solution. Wikipedia has several definitions that may be helpful here.
* You may use built-ins in your solutions, including those that calculate `S(a, b)`, or even those that calculate `P(r, n)` directly.
* You can hardcode up to 1000 values of `R(n)` and a million Stirling numbers, though neither of these are hard limits, and can be changed if you can make a convincing argument for raising or lowering them.
* You don't need to check every possible `r` between `n` and the `r` we're looking for, but you do need to find the smallest `r` and not just any `r` where `P(r, n) >= 0.5`.
* Your program must use a language that is freely runnable on Windows 10.

The specifications of the computer that will test your solutions are `i7 4790k, 8 GB RAM`. Thanks to @DJMcMayhem for providing his computer for the testing. Feel free to add your own *unofficial* timing for reference, but the official timing will be provided later once DJ can test it.

**Test cases**

```
n       R(n)
1       1
2       2
3       5
4       7
5       10
6       13
20      67       # our 20-sided die
52      225      # how many cards from a huge uniformly random pile until we get a full deck
100     497
366     2294     # number of people for to get 366 distinct birthdays
1000    7274
2000    15934
5000    44418
10000   95768
100000  1187943
1000000 14182022

```

Let me know if you have any questions or suggestions. Good luck and good optimizing!

# Answer
# Python + NumPy, 3.95 Seconds

```
from __future__ import division
import numpy as np

def rolls(n):
    if n == 1:
        return 1
    r = n * (np.log(n) - np.log(np.log(2)))
    x = np.log1p(np.arange(n) / -n)
    cx = x.cumsum()
    y = cx[:-1] + cx[-2::-1] - cx[-1]
    while True:
        r0 = np.round(r)
        z = np.exp(y + r0 * x[1:])
        z[::2] *= -1
        r = r0 - (z.sum() + 0.5) / z.dot(x[1:])
        if abs(r - r0) < 0.75:
            return np.ceil(r).astype(int)

for n in [1, 2, 3, 4, 5, 6, 20, 52, 100, 366, 1000, 2000, 5000, 10000, 100000, 1000000]:
    print('R({}) = {}'.format(n, rolls(n)))

import timeit
print('Benchmark: {:.2f}s'.format(timeit.timeit(lambda: sum(map(rolls, range(1, 10001))), number=1)))

```

Try it online!

### How it works

This uses the closed-form series for *P*(*r*, *n*), and its derivative with respect to *r*, rearranged for numerical stability and vectorization, to do a Newton’s method search for *r* such that *P*(*r*, *n*) = 0.5, rounding *r* to an integer before each step, until the step moves *r* by less than 3/4. With a good initial guess, this usually takes just one or two iterations.

*x**i* = log(1 − *i*/*n*) = log((*n**i*)/*n*)
*cx**i* = log(*n*!/((*n**i* − 1)! ⋅ *n**i* \+ 1)
*y**i* = *cx**i* \+ *cx**n**i* − 2*cx**n* − 1 = log binom(*n*, *i* \+ 1)
*z**i* = (-1)*i* \+ 1 ⋅ binom(*n*, *i* \+ 1) ⋅ ((*n**i* − 1)/*n*)*r*
1 + ∑*z**i* = n! ⋅ *S*(*r*, *n*)/*n**r* = *P*(*r*, *n*)
*z**i**x**i* \+ 1 = (-1)*i* \+ 1 ⋅ binom(*n*, *i* \+ 1) ⋅ ((*n**i* − 1)/*n*)*r* log((*n**i* − 1)/*n*)
*z**i**x**i* \+ 1 = d/d*r* *P*(*r*, *n*)
> 7 votes

---
Tags: sequence, combinatorics, fastest-code
---


title: Make your keyboard into a keyboard

text:
# Question
Title: Make your keyboard into a keyboard
# Task

You should write a program that when a button is pressed, it outputs a different sound for each key.

The keys that you will use are:

```
1!2"34$5%6^78*9(0qQwWeErtTyYuiIoOpPasSdDfgGhHjJklLzZxcCvVbBnm

```

The notes begin at `C` and each key above adds one semitone.

Lets make it slightly easier for you though. You can choose between 2 similar tasks,

> 1) Output a different note when a key is pressed that continues until another key is pressed. This program runs indefinitely
>
> 2) Take a string as input that only contains the characters above that will output each note for exactly 1 second (0.05 second variation allowed)

# Input

1. A key being pressed
2. A single string containing only the symbols above

# Output

1. A single musical note that sounds until another key is pressed
2. A series of notes, each one 1 second long

# Notes

```
Letter | Note
-------+-------
   1   |  C
   !   |  C#
   2   |  D
   "   |  D#
   3   |  E
   4   |  F
   $   |  F#
   5   |  G
   %   |  G#
   6   |  A
   ^   |  A#
   7   |  B
   8   |  C
   *   |  C#
   9   |  D
   (   |  D#
   0   |  E
   q   |  F
   Q   |  F#
   w   |  G
   W   |  G#
   e   |  A
   E   |  A#
   r   |  B
   t   |  C    <-- middle C
   T   |  C#
   y   |  D
   Y   |  D#
   u   |  E
   i   |  F
   I   |  F#
   o   |  G
   O   |  G#
   p   |  A
   P   |  A#
   a   |  B
   s   |  C
   S   |  C#
   d   |  D
   D   |  D#
   f   |  E
   g   |  F
   G   |  F#
   h   |  G
   H   |  G#
   j   |  A
   J   |  A#
   k   |  B
   l   |  C
   L   |  C#
   z   |  D
   Z   |  D#
   x   |  E
   c   |  F
   C   |  F#
   v   |  G
   V   |  G#
   b   |  A
   B   |  A#
   n   |  B
   m   |  C

```

# Rules

* You may choose between the tasks but please say which one in your answer
* You are given a ±0.05 second variation in task 2
* Each symbol along increments the tone by 1 semitone.
* The individual notes are shown above
* This is a so shortest code wins

This was originally taken from here with caird coinheringaahing's consent

# Answer
# Python 3, ~~154~~ 140 bytes

```
from winsound import*
for i in input():Beep(int(65.406*2**('1!2"34$5%6^78*9(0qQwWeErtTyYuiIoOpPasSdDfgGhHjJklLzZxcCvVbBnm'.find(i)/12)),999)

```

I chose the second task type.

The loop passes through each character and looks for the index of this element in the string. This index is the number of semitone up from Low C ('1'). Calculation of the desired frequency is made by this formula.

P.S. This library works only in Windows.

*-13 bytes thanks to ovs.*

*-1 byte thanks to Jonathan Allan.*
> 6 votes

# Answer
# JavaScript (ES6), 247 or 230 bytes

Decided to try out both options.

Saved a few bytes thanks to @darrylyeo for suggesting the `with` statement.
Thanks to @Кирилл Малышев for pointing out an issue with `.search()`.

## Option 1 - Keyboard Input, ~~252~~ ~~246~~ 247 bytes

```
_=>{c=new AudioContext;q=1;with(c.createOscillator())connect(c.destination),I.oninput=_=>(~(i='1!2"34$5%6^78*9(0qQwWeErtTyYuiIoOpPasSdDfgGhHjJklLzZxcCvVbBnm'.indexOf(I.value,I.value=""))&&(frequency.value=65.4*2**(i/12),q&&start(q=0)))}

```

```
<input id=I

```

Relies on the input element receiving the actual letter typed, instead of character codes. Focus must be on the input box.

## Option 2 - String Input, ~~234~~ ~~229~~ 230 bytes

```
s=>{c=new AudioContext;with(c.createOscillator())connect(c.destination),[...s].map((c,i)=>frequency.setValueAtTime(65.4*2**('1!2"34$5%6^78*9(0qQwWeErtTyYuiIoOpPasSdDfgGhHjJklLzZxcCvVbBnm'.indexOf(c)/12),i)),start(),stop(s.length)}

```

Simply takes the string as the function parameter.

## Combined Snippet

I suggest turning down your volume being running this, it can be loud. In order to stop playback, the snippet required adding `o=` inside each `with(c.createOscillator())`.

```
f= // keyboard input
_=>{c=new AudioContext;q=1;with(o=c.createOscillator())connect(c.destination),I.oninput=_=>(~(i='1!2"34$5%6^78*9(0qQwWeErtTyYuiIoOpPasSdDfgGhHjJklLzZxcCvVbBnm'.indexOf(I.value,I.value=""))&&(frequency.value=65.4*2**(i/12),q&&start(q=0)))}

g= // string input
s=>{c=new AudioContext;with(o=c.createOscillator())connect(c.destination),[...s].map((c,i)=>frequency.setValueAtTime(65.4*2**('1!2"34$5%6^78*9(0qQwWeErtTyYuiIoOpPasSdDfgGhHjJklLzZxcCvVbBnm'.indexOf(c)/12),i)),start(),stop(s.length)}

swap=_=>{keyboard=!keyboard;A.innerHTML=keyboard?"Keyboard":"String";S.style.display=keyboard?"none":"inline";window.c&&c.close();window.o&&o.stop();keyboard?f():I.oninput=null;I.value="";}
keyboard=0;
swap();
```

```
<span id="A"></span> Input:<br>
<input id="I">
<button id="S" onclick="g(I.value)">Run</button><br>
<button onclick="swap()">Swap</button>
```
> 3 votes

# Answer
# AHK, 130 bytes

```
s=1!2"34$5`%6^78*9(0qQwWeErtTyYuiIoOpPasSdDfgGhHjJklLzZxcCvVbBnm
Loop,Parse,1
SoundBeep,55*2**((InStr(s,A_LoopField,1)-10)/12),999

```

I chose Option 2.

Explanation:

Storing the search string as the variable `s` was shorter than escaping that mess directly in the `SoundBeep` function. I had to escape the percent sign since that's an escape character for variable names but the rest of the string is OK as is.

By default, the variable `1` is the first input parameter. Feeding that into a parsing loop without specifying a delimiter will result in each character in the input string being analyzed individually.

`SoundBeep` takes in a frequency in Hz and a duration in milliseconds and plays that note for that long.

The fun part was figuring out the right frequencies. Referencing the piano key frequency table from Wikipedia and the formula on the same page, I found the shortest encoding was to use A1 as the reference note because it's frequency is the nice round 55 Hz. Since we want to start at C1, we have to adjust from A1 (the 13th note) to C1 (the 4th note). That, plus the fact that `InStr` is one-indexed, is why we subtract 10 from the result of the `InStr` function.
> 1 votes

---
Tags: code-golf, audio
---


title: I <3 conditionals

text:
# Question
Title: I <3 conditionals
You end up having a lot of very long, boring-looking conditionals in your code:

```
if flag == 1:

while have != needed:

if type == 7:

```

These can be transformed into their much more lovable `<3` conditionals counterparts:

```
if abs(flag - 1) + 2 <3:

while 3 - abs(have - needed) <3:

if 2 + abs(type - 7) <3:

```

### Task

Your task is to take a conditional and make it in terms of `<3`. The only spacing that matters is that there is none between `<` and `3`.

Conditionals will be two expressions seperated by either `==`, `!=`, `>`, `<`, `>=` or `<=`.
Expressions will only contain addition, subtraction, unary negation (`-something`), where there is one `+` or `-` before each variables or numbers (except the first which has nothing or `-` before it).
Numbers will be `[0-9]+`, and variables will be `[a-z]+`. If the answer needs to use `|x|` (The absolute value of `x`), use the `abs()` function. You may assume that all variables are integers, and all number constants in the input are \< 1000.

The output does *not* need to be in it's simplest form. It does need to be a conditional like above, meaning that it is two expressions only, seperated by one conditional sign, but it can also use the `abs` function, enclosing a valid expression, and then it acts like a variable, in terms of validity.

If the input does not have an output for any value of a variable, output a condition that is always false, but still in terms of `<3`.

Part of the challenge is figuring out how to do it, but here are the steps for the `have != needed` above:

```
have != needed
have - needed != 0
abs(have - needed) > 0
-abs(have - needed) < 0
3 - abs(have - needed) <3

```

### Scoring

This is code-golf, so the shortest valid code, in bytes, wins.

### Test cases

(Note, these outputs aren't the only outputs, but I tried to simplify them.)

```
flag == 1
abs(flag - 1) + 2 <3

have != needed
3 - abs(have - needed) <3

type == 7
2 + abs(type - 7) <3

x > y
3 - x + y <3

x + 5 < -y
x + 8 + y <3

x + 6 <= y
x + 8 - y <3

-x >= y + 3
x + y + 5 <3

x < x
3 <3
# Unsimplified; both would be valid outputs.
x - x + 3 <3

```

# Answer
# Retina, 95 bytes

```
<=
<1+
>=
>-1+
(.*)(.=)(.*)
$2abs($1-($3))
==
2+
!=
3-
(.*)>(.*)
$2<$1
(.*)<(.*)
$1-($2)+3
$
<3

```

Try it online!

A rather naïve solution, but I haven't been able to find any improvements.

This is just a series of replacements:

```
<=
<1+
>=
>-1+

```

Get rid of "or equal to" comparisons by replacing `x <= y` with `x < 1 + y`, and `x >= y` with `x > -1 + y`.

```
(.*)(.=)(.*)
$2abs($1-($3))

```

Replace `x == y` with `==abs(x - y)`, and `x != y` with `!=abs(x - y)`.

```
==
2+
!=
3-

```

Replace `==` with `2+` and `!=` with `3-`, so that the overall replacements become `x == y``2 + abs(x - y)` and `x != y``3 - abs(x - y)`.

```
(.*)>(.*)
$2<$1

```

Normalize the direction of the remaining inequalities, replacing `x > y` with `y < x`.

```
(.*)<(.*)
$1-($2)+3

```

Replace `x < y` with `x - y + 3`.

```
$
<3

```

Append a heart to the end of the string.
> 3 votes

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


title: Golfception arrives

text:
# Question
Title: Golfception arrives
Lets play golf while we golf.

# Problem:

* Distance to the hole initially is 700m
* Each hit to the ball will make it advance to the hole 250-350m, this should be random.
* Each hit has a 5% probabilities of going into water, this will make the quantity of hits increase by 1 as a penalty.
* When ball is under 250m it will advance 70% to 90% (random again) of missing distance with a probability of 80%, Advance 90% to 99% with 14% Probability, 1% of doing 10%(and finishing) and 5% of going to water and increasing the number of hits by 1 as a penalty.
* When ball is under 10m it has 95% of going into hole (finishing) and 5% of advancing 75% of the missing path. No probability of going water.

Clarifications:

-Imagine ball is 270m from hole, if we hit for 300m, the distance to the hole is now 30, this means, distance will be absolute value.

-Numbers will always be integer due to deal the probability of hitting for example 300m when ball is 300m away from the hole.

-Round down number of m of the hit, imagine you are at 1m , if you fall on 5% of not going into the hole, it will advance 0.

## Input:

Nothing

## Output:

Distance to the hole in each hit /n

Total number of hits

Example output (don't print comments)

> 433m //Hit for 267m (700-267=433)
>
> 130m //Hit for 303m (433-303=130)
>
> 130m //Ball on water +1 penalty hit
>
> 35m //Hit for 95m (130-95=35)
>
> 7m //Hit for 28m (35-28=7
>
> 0m //Ball on hole
>
> Total hits 7 //6 hits +1 penalty

This is codegolf!

# Answer
# JavaScript, ~~204~~ 198 bytes

```
P=console.log
r=x=>Math.random()*x
for(d=700,h=0;d;)x=r(100),D=d>=250?r(20)<1?h++*0:250+r(100):d*(d<10?x<5?.75:1:x<5?h++*0:x<6?1:.9+r(x<20?.09:-.2)),d=Math.abs(d-D|0),h++,P(d+'m')
P('Total hits '+h)
```

Less golfed:

```
r=x=>Math.random()*x
for(d=700,h=0;d;){
    x=r(100),
    D=
        d>=250
            ? r(20)<1
                ? h++*0
                : 250+r(100)
        : d * (d<10
            ? x<5
                ? .75
                : 1
        : x<5
            ? h++*0
        : x<6
            ? 1
        : .9 + r(
            x<20
                ? .09
                : -.2
            )
        ),
    d=Math.abs(d-D|0),
    h++,
    console.log(d+'m')
}

console.log('Total hits '+h)

```
> 1 votes

# Answer
# Python 3.6, 250 bytes

Saved 4 bytes thanks to isaacg, and 1 thanks to KoishoreRoy!

```
d=700                    # Current distance
from random import*
r=randrange              # Function that gets a random value in the range [0, input)
i=0                      # Number of strokes
while d:
 i+=1;x=r(20)<1          # x is False 95% of the time
                         # My justification for reusing this random value
                         # is that it's used once and only once, separate by if/elif
 if d<10:d-=[d,d*.75][x] # We're within putting range; goes in if x is true; otherwise makes 75% progress
 elif x:i+=1             # Goes in the water, add a stroke
 elif d<250:
  s=r(95);d-=[d,d*[.7+r(21)/100,.9*r(10)/100][s<15]][s>0]
                         # Only 95 because we already checked to see if it would go in the water
                         # 99% of the time (s>0), it doesn't go in
                         # 14% of the time (s<15), it makes 90-99% progress
                         # Otherwise, it makes 70-90% progress
 else:d-=250+r(101)      # Lose 250-350 yards
 d=int(abs(d));print(f'{d}m')
print(f'Total hits {i}')

```

Try it online! (Uses Python 3.5 printing syntax at a cost of 6 bytes since TIO does not yet support Python 3.6.)
> 3 votes

# Answer
# Perl 6, 212 bytes

```
my&p=(^*).pick;say 'Total hits ',(700,->\d{my \n=d>249??abs d-(p(20)??250+p
100!!0)!!d>9??d-(|((d*(70+p 21)div 100) xx 80),|((d*(90+p 10)div 100) xx
14),d,|(0 xx 5))[p 100]!!p(20)??d div 4!!0;"{n}m".say;n}...0)-1

```

`&p` is a helper function that picks a random number from `0` to one less than its argument. The expression after `'Total hits '` is a lazily-constructed list that generates each element based on the previous element. The elements are printed as they are generated, which isn't very functional, but it is shorter than storing them in an intermediate array.
> 2 votes

---
Tags: code-golf, probability-theory
---


title: Print The Input Backward

text:
# Question
Title: Print The Input Backward
Just take an input in any way and then print it backward (trailing newlines allowed). For example:

```
Hello World -> dlroW olleH
Hi -> iH

```

Yes, it is case sensitive. Shortest code wins

# Answer
> 0 votes
# Mathematica, 13 bytes

```
StringReverse

```

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


# Question
Title: Do two numbers contain unique factorials?
Break two numbers up into their factorials; if they share any, return a falsey value. Otherwise, return a truthy value. (inspired by this recent question)

In other words, write each input number as the sum of factorials (of positive integers) in the greediest possible way; return a truthy value if no factorial appears in both representations, a falsey value otherwise.

# Example

Given 20 and 49:

```
20 = 3! + 3! + 3! + 2!
49 = 4! + 4! + 1!

```

No factorial appears in both representations, so return a truthy value.

Given 32 and 132:

```
132 = 5! + 3! + 3!
 32 = 4! + 3! + 2!

```

3! appears in both representations, so return a falsey value.

# I/O

Input and output can be through any standard means.

Input will always be two nonnegative integers; no upper bound on these integers other than what your language requires.

Output should be a truthy or falsey value. These values don't necessarily have to be consistent for different inputs, as long as every output is correctly truthy/falsey.

# Test Cases

If one input is `0`, the answer will always be truthy. Other truthy test cases:

```
{6, 3}, {4, 61}, {73, 2}, {12, 1}, {240, 2}, {5, 264}, {2, 91}, {673, 18},
 {3, 12}, {72, 10}, {121, 26}, {127, 746}

```

If both inputs are odd integers, or if both inputs are the same positive integer, then the output will always be falsey. Other falsey test cases:

```
{8, 5}, {7, 5}, {27, 47}, {53, 11}, {13, 123}, {75, 77}, {163, 160}, {148, 53},
 {225, 178}, {285, 169}, {39, 51}, {207, 334}, {153, 21}, {390, 128}, {506, 584},
 {626, 370}, {819, 354}

```

This is , so fewest bytes wins!

# Answer
> 9 votes
# Jelly, 7 bytes

```
Æ!ṠḄ&/¬

```

Try it online!

### How it works

```
Æ!ṠḄ&/¬  Main link. Argument: (x, y) (pair of integers)

Æ!       Convert x and y to factorial base.
  Ṡ      Apply the sign function to each digit.
   Ḅ     Unbinary; convert each resulting Boolean array from base 2 to integer.
    &/   Reduce the resulting pair of integers by bitwise AND.
      ¬  Take the logical NOT of the result.

```

# Answer
> 3 votes
# Python 3, ~~93~~ 91 bytes

```
lambda a,b:k(a)&k(b)=={0}
k=lambda t,n=1,a=1:{t}&{0}or a*n>t and{a-1}|k(t-n)or k(t,n*a,a+1)

```

Try it online!

# Answer
> 3 votes
# Python 2, 47 bytes

```
h=lambda a,b,d=2:a<1or a%d*(b%d)<h(a/d,b/d,d+1)

```

Try it online!

# Answer
> 2 votes
## JavaScript (ES6), 71 bytes

```
(a,b,g=(n,e=1,f=1)=>n>=f&&g(n,++e,f*e)+((n/f|0)%e&&1<<e))=>!(g(a)&g(b))

```

JavaScript's integers are limited to 53 bits of precision, which is just about enough for 18!; this means that I can use a mask of 18 bits to track which factorials are needed.

# Answer
> 2 votes
# PHP, 109 Bytes

```
for(;$a?:$a=$argv[++$i];$a-=$r[$i][]=$f,$i<2?:$t+=in_array($f,$r[1]))for($c=$f=1;($a/$f*=$c)>=++$c;);echo!$t;

```

Try it online!

# Answer
> 0 votes
# Mathematica, 73 bytes

```
F[x_]:=First@IntegerPartitions[x,99,Range[99]!];!IntersectingQ[F@#,F@#2]&

```

input form

> \[x1,x2\]

# Answer
> 0 votes
# C, ~~122~~ 119 bytes

```
G(q,i){return gamma(q+1)>i?gamma(q):G(q+1,i);}
Q(a,b,u,v){while(a&&b){a-=u=G(1,a);b-=v=G(1,b);if(a==b)exit();}exit(0);}

```

`Q` is the main function. It should be invoked with exactly two positive integer values. This exits with an exit code of `0` for truthy and `1` for falsy.

Although this does not seem to work on TIO, it works on my system with the Homebrew provided `gcc 7.1.0`.

I have not golfed in `C` in quite a while, so golfing tips are very much appreciated!

---
Tags: code-golf, arithmetic, decision-problem, integer, factorial
---


title: Exploring the xorspace

text:
# Question
Title: Exploring the xorspace
The *xorspace* of a set of integers is the set of all integers that can be obtained by combining the starting integers with the usual bitwise xor operator (`^`). For example, the xorspace of `(8, 4)` is `(0, 4, 8, 12)`: 0 is 4^4, 12 is 4^8, and no other numbers can be reached. Note that the starting numbers are always included, by this definition (for example, 4 is 4^4^4).

Your goal is to write the shortest program that takes a list of non-negative integers as input, and outputs the number of elements in their xorspace.

* Standard loopholes are forbidden.
* Input and output can be in any of the usual formats. Input is guaranteed to be valid, non-empty, and without duplicates.
* **Your code should be able to process all test cases in less than a day**.

### Test cases

```
Input: 0
Output: 1

Input: 6
Output: 2

Input: 8 4
Ouput: 4

Input: 0 256
Output: 2

Input: 256 259 3
Output: 4

Input: 60 62 94 101 115
Output: 32

Input: 60 62 94 101 115 40 91
Output: 32

Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
Output: 64

Input: 1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384
Output: 32768

```

# Answer
> 2 votes
# Pyth, 8 bytes

```
lu{+xM*Q

```

Test suite

Explanation:

To generate the xorspace, we find the fixpoint of taking the xor of every pair of numbers, adding in every number, and deduplicating. Then, we take the length of the result. This runs in 20 seconds (offline only) on the final test case.

```
lu{+xM*Q
lu{+xM*QGGQ    Implicit variable introduction
 u        Q    Find the fixed point of the following, starting with the input,
               where the current value is G.
      *QG      Form the Cartesian product of Q (input) and G (current)
    xM         Take the xor of every pair
   +           Add the current values
  {            Deduplicate
l              Output the length of the result.

```

---

# Packed Pyth, 7 bytes

Hexdump:

```
0000000: d9d7 dabf 1355 51                        .....UQ

```

The same as the above, with a 7-bit ASCII encoding.

Put the above in a file with `xxd -r`, and run it as follows:

```
py packed-pyth.py xorspace.ppyth '[256, 259, 3]'

```

# Answer
> 10 votes
# MATL, 11 bytes

```
t"G!Z~Ghu]n

```

Try it online!

The last test case doesn't run in the online interpreter because of memory limitations, but runs offline in less than 2 seconds on a modern computer.

### Explanation

For input of size `n`, this does the following:

1. Initiallize result to input.
2. Repeat `n` times:
    1. Apply bitwise XOR to all pair of entries from current result and input.
    2. Attach input values to the result.
    3. Deduplicate.
3. The output is the number of elements of the final result.

Commented code.

```
t      % Implicit input: row vector. Duplicate
"      % For each (i.e. do as many times as the input size)
  G!   %   Push input as a column vector
  Z~   %   Bitwise XOR with broadcast, i.e. for all pairs of entries of the
       %   two arguments. The first argument is the accumulated result
       %   from the previous iteration, the second is the input vector
  G    %   Push input again
  h    %   Postpend
  u    %   Unique values. Gives a row vector
]      % End
n      % Number of entries. Implicitly display

```

### Example

The intermediate results (steps 2.1 and 2.3) for input `[256 259 3]` are:

First iteration: `[256 259 3]` with `[256 259 3]`: computing all pairs of bitwise-XOR gives the matrix

```
  0   3 259
  3   0 256
259 256   0

```

Attaching `[256 259 3]` and deduplicating

```
0 3 259 256

```

Second iteration: current result `[0 3 259 256]` with `[256 259 3]`. After deduplicating this again gives

```
0 3 259 256

```

Third iteration: again

```
0 3 259 256

```

So the output is `4` (number of entries of result).

# Answer
> 8 votes
# Haskell, 64 bytes

`f` takes a list of integers and returns an integer.

```
import Data.Bits
f l|m<-maximum l,m>0=2*f(min<*>xor m<$>l)|0<1=1

```

Try it online!

This doesn't handle an empty list, for that you can but `$0:` instead of the space after `maximum`.

# How it works

* If the maximum `m` of the list is zero, returns 1.
* Otherwise, xors every element with the maximum.
    + If the result is smaller than the element, the element is replaced by it.
    + This necessarily zeroes the most significant bit set anywhere in the list.
    + Then recurses on the resulting list, doubling the result of the recursion.
* This process essentially performs Gaussian elimination (although throwing away the final rows by setting them to 0) modulo 2, on the matrix whose rows are the bit representations of the list of numbers. The set of bit representations of the "xorspace" is the vector space modulo 2 spanned by the rows of this matrix, and whose number of elements is 2 to the power of the matrix's row rank.
* This algorithm is polynomial time, so should definitely be better than O(2^n).

# Answer
> 4 votes
# Mathematica, 52 bytes

```
2^MatrixRank[PadLeft@IntegerDigits[#,2],Modulus->2]&

```

# Answer
> 3 votes
# 05AB1E, 8 bytes

```
vDy^ìÙ}g

```

Try it online!

All test-cases finish in under 1 minute on TIO.

# Answer
> 3 votes
# Python 2, 55 bytes

```
r={0}
for n in input():r|={x^n for x in r}
print len(r)

```

Try it online!

Beats out functions:

```
f=lambda l,r={0}:l and f(l[1:],r|{x^l[0]for x in r})or len(r)
f=lambda l:len(reduce(lambda r,n:r|{x^n for x in r},l,{0}))

```

---

Ørjan Johansen's beautiful row elimination method is one byte shorter.

**Python 2, 54 bytes**

```
f=lambda l:1-any(l)or 2*f([min(x,x^max(l))for x in l])

```

Try it online!

# Answer
> 2 votes
# Jelly, ~~9~~ 8 bytes

```
0œ|⁺^¥/L

```

Finishes all test cases in under **8** seconds on TIO, with negligible memory requirements.

Try it online!

### How it works

```
0œ|⁺^¥/L  Main link. Argument: A (array)

0œ|       Perform multiset union with 0, prepending 0 if A doesn't contain it.
      /   Reduce A by the link to the left.
     ¥      Combine the previous two links into a dyadic chain.
            Left argument: V (array). Right argument: n (integer)
    ^           Bitwise XOR each element in V with n.
   ⁺            This quick refers to the previous link, making it a shorthand for
                the link 'œ|'. Thus, it performs multiset union on V and the array
                of bitwise XORs.
       L  Compute the length of the result.

```

# Answer
> 1 votes
# Python, 113 bytes

```
def f(x):
 u,s=[0],{0}
 while u:
	a=u.pop()
	for b in x:
	 c=a^b
	 if c not in s:u+=[c]
	 s.add(c)
 return len(s)

```

---
Tags: code-golf, bitwise
---