title: On the Subject of Passwords

text:
# Question
Title: On the Subject of Passwords
In Keep Talking and Nobody Explodes, players are tasked with defusing bombs based on information from their "experts" (other people with a manual). Each bomb is made up of modules, one of which can be passwords, where the expert is given this list of possible passwords, all five letters long:

```
about   after   again   below   could
every   first   found   great   house
large   learn   never   other   place
plant   point   right   small   sound
spell   still   study   their   there
these   thing   think   three   water
where   which   world   would   write

```

And the player is given a list of 6 possible letters for each place in the password. **Given the possible letter combinations, output the correct password.** Input can be in any reasonable format (2D array, string separated by newline, etc.) **You may discount the code which you use to compress/generate the list/string/array/whatever of passwords.** (Thanks @DenkerAffe)

NOTE: Passwords are case insensitive. You may assume that input will only solve for one password.

## Examples / Test Cases

Input here will be represented as a array of strings.

```
["FGARTW","LKSIRE","UHRKPA","TGYSTG","LUOTEU"] => first
["ULOIPE","GEYARF","SHRGWE","JEHSDG","EJHDSP"] => large
["SHWYEU","YEUTLS","IHEWRA","HWULER","EUELJD"] => still

```

# Answer
## Pyth, 13 bytes

```
:#%*"[%s]"5Q0c"ABOUTAFTERAGAINBELOWCOULDEVERYFIRSTFOUNDGREATHOUSELARGELEARNNEVEROTHERPLACEPLANTPOINTRIGHTSMALLSOUNDSPELLSTILLSTUDYTHEIRTHERETHESETHINGTHINKTHREEWATERWHEREWHICHWORLDWOULDWRITE"5

```

Test suite.

```
 #             filter possible words on
:           0  regex match, with pattern
  %        Q   format input as
    "[%s]"     surround each group of letters with brackets (regex char class)
   *      5    repeat format string 5 times for 5 groups of letters

```
> 6 votes

# Answer
## Bash, 22 bytes

```
grep `printf [%s] $@`< <(echo ABOUTAFTERAGAINBELOWCOULDEVERYFIRSTFOUNDGREATHOUSELARGELEARNNEVEROTHERPLACEPLANTPOINTRIGHTSMALLSOUNDSPELLSTILLSTUDYTHEIRTHERETHESETHINGTHINKTHREEWATERWHEREWHICHWORLDWOULDWRITE | sed 's/...../&\n/g')

```

Run like so:

```
llama@llama:~$ bash passwords.sh FGARTW LKSIRE UHRKPA TGYSTG LUOTEU
FIRST

```

```
      printf [%s] $@    surround all command line args with brackets
grep `              `   output all input lines that match this as a regex
                     <  use the following file as input to grep

```
> 6 votes

# Answer
# Ruby, ~~48~~ ~~42~~ 39 bytes

Now that it's done, it's very similar to the Pyth solution, ~~but without `%s` formatting~~ to the point where it's basically a direct port now.

If you only output the result with `puts`, you don't need the `[0]` at the end since `puts` will deal with that for you.

```
->w,l{w.grep(/#{'[%s]'*l.size%l}/i)[0]}

```

With test cases:

```
f=->w,l{w.grep(/#{'[%s]'*l.size%l}/i)[0]}

w = %w{about after again below could
every first found great house
large learn never other place
plant point right small sound
spell still study their there
these thing think three water
where which world would write}

puts f.call(w, ["FGARTW","LKSIRE","UHRKPA","TGYSTG","LUOTEU"]) # first
puts f.call(w, ["ULOIPE","GEYARF","SHRGWE","JEHSDG","EJHDSP"]) # large
puts f.call(w, ["SHWYEU","YEUTLS","IHEWRA","HWULER","EUELJD"]) # still

```
> 2 votes

# Answer
## JavaScript (ES6), 62 bytes

```
(l,p)=>p.find(w=>l.every((s,i)=>eval(`/[${s}]/i`).test(w[i])))

```

53 bytes on Firefox 48 or earlier:

```
(l,p)=>p.find(w=>l.every((s,i)=>~s.search(w[i],"i")))

```

Would have been 49 bytes if not for that case insensitivity requirement:

```
(l,p)=>p.find(w=>l.every((s,i)=>~s.search(w[i])))

```

```
f=
  (l,p)=>p.find(w=>l.every((s,i)=>eval(`/[${s}]/i`).test(w[i])))
;
p=["about","after","again","below","could","every","first","found","great","house","large","learn","never","other","place","plant","point","right","small","sound","spell","still","study","their","there","these","thing","think","three","water","where","which","world","would","write"];
o1.value=f(["FGARTW","LKSIRE","UHRKPA","TGYSTG","LUOTEU"],p)
o2.value=f(["ULOIPE","GEYARF","SHRGWE","JEHSDG","EJHDSP"],p)
o3.value=f(["SHWYEU","YEUTLS","IHEWRA","HWULER","EUELJD"],p)
```

```
<input id=o1><input id=o2><input id=o3>
```
> 2 votes

# Answer
# Brachylog, 25 bytes

```
:@laL,["about":"after":"again":"below":"could":"every":"first":"found":"great":"house":"large":"learn":"never":"other":"place":"plant":"point":"right":"small":"sound":"spell":"still":"study":"their":"there":"these":"thing":"think":"three":"water":"where":"which":"world":"would":"write"]:Jm.'(:ImC,L:Im'mC)

```

The uncounted bytes are the array of words, including the square brackets.

### Explanation

```
:@laL                          Unifies L with the input where each string is lowercased
     ,[...]:Jm.                Unifies the Output with one of the words
               '(            ) True if what's in the parentheses is false,
                               else backtrack and try another word
                 :ImC          Unify C with the I'th character of the output
                     ,L:Im'mC  True if C is not part of the I'th string of L

```
> 2 votes

# Answer
# JavaScript (ES6), 71 bytes

```
w=>l=>w.filter(s=>eval("for(b=1,i=5;i--;)b&=!!~l[i].indexOf(s[i])")[0])

```

Usage:

```
f=w=>l=>w.filter(s=>eval("for(b=1,i=5;i--;)b&=!!~l[i].indexOf(s[i])")[0])
f(array_of_words)(array_of_letters)

```
> 1 votes

# Answer
## Python, ~~64~~ ~~60~~ 57 bytes

Code to create word list `w` as string, words are space-separated (bytes are discounted from solution code length):

```
w="about after again below could every first found great house large learn never other place plant point right small sound spell still study their there these thing think three water where which world would write"

```

**Current solution (57 bytes):** *saved 3 bytes thanks to @RootTwo*

```
import re;f=lambda a:re.findall("(?i)\\b"+"[%s]"*5%a,w)[0]

```

This function takes a `tuple` (no `list`!) of exactly 5 strings which represent the possible letters for each password character as input.

See this code running on ideone.com

---

**Second version (60 bytes):**

```
import re;f=lambda a:re.findall("\\b"+"[%s]"*5%a+"(?i)",w)[0]

```

This function takes a `tuple` (no `list`!) of exactly 5 strings which represent the possible letters for each password character as input.

See this code running on ideone.com

**First version (64 bytes):**

```
import re;f=lambda a:re.findall("\\b["+"][".join(a)+"](?i)",w)[0]

```

This function takes any iterable (e.g. `list` or `tuple`) of exactly 5 strings which represent the possible letters for each password character as input.

See this code running on ideone.com
> 1 votes

# Answer
## Hoon, 125 bytes

```
|=
r/(list tape)
=+
^=
a
|-
?~
r
(easy ~)
;~
plug
(mask i.r)
(knee *tape |.(^$(r t.r)))
==
(skip pass |*(* =(~ (rust +< a))))

```

Ungolfed:

```
|=  r/(list tape)
=+  ^=  a
|-
  ?~  r
    (easy ~)
  ;~  plug
    (mask i.r)
    (knee *tape |.(^$(r t.r)))
  ==
(skip pass |*(* =(~ (rust +< a))))

```

Hoon doesn't have regex, only a parser combinator system. This makes it pretty complicated to get everything working: `(mask "abc")` roughly translates to regex's `[abc]`, and is the core of the parser that we are building.

`;~(plug a b)` is a monadic bind of two parsers under `++plug`, which has to parse the first and then second or else it fails.

`++knee` is used to build a recursive parser; we give it a type (`*tape`) of the result, and a callback to call to generate the actual parser. In this case, the callback is "call the entire closure again, but with the tail of the list instead". The `?~` rune tests is the list is empty, and gives `(easy ~)` (don't parse anything and return ~) or adds on another `mask` and recurse again.

Having built the parser, we can get to using it. `++skip` removes all elements of the list for which the function returns yes for. `++rust` tries to parse the element with our rule, returning a `unit` which is either `[~ u=result]` or `~` (our version of Haskell's Maybe). If it's `~` (None, and the rule either failed to parse or didn't parse the entire contents), then the function returns true and the element is removed.

What's left over is a list, containing only the word where each letter is one of the options in the list given. I'm assuming that the list of passwords is already in the context under the name `pass`.

```
> =pass %.  :*  "ABOUT"  "AFTER"   "AGAIN"   "BELOW"   "COULD"
   "EVERY"   "FIRST"   "FOUND"   "GREAT"   "HOUSE"
   "LARGE"   "LEARN"   "NEVER"   "OTHER"   "PLACE"
   "PLANT"   "POINT"   "RIGHT"   "SMALL"   "SOUND"
   "SPELL"   "STILL"   "STUDY"   "THEIR"   "THERE"
   "THESE"   "THING"   "THINK"   "THREE"   "WATER"
   "WHERE"   "WHICH"   "WORLD"   "WOULD"   "WRITE"
   ~  ==  limo
> %.  ~["SHWYEU" "YEUTLS" "IHEWRA" "HWULER" "EUELJD"]
  |=
  r/(list tape)
  =+
  ^=
  a
  |-
  ?~
  r
  (easy ~)
  ;~
  plug
  (mask i.r)
  (knee *tape |.(^$(r t.r)))
  ==
  (skip pass |*(* =(~ (rust +< a))))
[i="STILL" t=<<>>]

```
> 0 votes

# Answer
# Python 3, 81 bytes

```
from itertools import*
lambda x:[i for i in map(''.join,product(*x))if i in l][0]

```

An anonymous function that takes input of a list of strings `x` and returns the password.

The list of possible passwords `l` is defined as:

```
l=['ABOUT', 'AFTER', 'AGAIN', 'BELOW', 'COULD',
   'EVERY', 'FIRST', 'FOUND', 'GREAT', 'HOUSE',
   'LARGE', 'LEARN', 'NEVER', 'OTHER', 'PLACE',
   'PLANT', 'POINT', 'RIGHT', 'SMALL', 'SOUND',
   'SPELL', 'STILL', 'STUDY', 'THEIR', 'THERE',
   'THESE', 'THING', 'THINK', 'THREE', 'WATER',
   'WHERE', 'WHICH', 'WORLD', 'WOULD', 'WRITE']

```

This is a simple brute force; I was interested to see how short I could get this without regexes.

**How it works**

```
from itertools import*  Import everything from the Python module for iterable generation
lambda x                Anonymous function with input list of strings x
product(*x)             Yield an iterable containing all possible passwords character by
                        character
map(''.join,...)        Yield an iterable containing all possible passwords as strings by
                        concatenation
...for i in...          For all possible passwords i...
i...if i in l           ...yield i if i is in the password list
:[...][0]               Yield the first element of the single-element list containing the
                        correct password and return

```

Try it on Ideone
> 0 votes

---
Tags: code-golf
---


# Question
Title: JSON tips: filter objects from array of objects where object name is alpha
What could be the shortest code for filtering the following array in Javascript without any library?

My code is:

```
filtered_obj = _.where(obj, { name: "Alpha" });

```

This uses a JS library called `underscore`.

Test case:

```
objs = [{'id':1,'name':'Alpha'},{'id':2,'name':'Beta'},
{'id':3,'name':'Gamma'},{'id':4,'name':'Eta'},
{'id':5,'name':'Alpha'},{'id':6,'name':'Zeta'},
{'id':7,'name':'Beta'},{'id':8,'name':'Theta'},
{'id':9,'name':'Alpha'},{'id':10,'name':'Alpha'}];

filtered_obj =[{'id':1,'name':'Alpha'},{'id':5,'name':'Alpha'},
{'id':9,'name':'Alpha'},{'id':10,'name':'Alpha'}]

```

# Answer
> 1 votes
# 45 bytes

```
filtered_obj=objs.filter(n=>n.name=='Alpha');

```

This uses the `filter` function for arrays.

Ideone it!

---
Tags: code-golf, array, tips, javascript, json
---


# Question
Title: Distinct subsets that sum to a given number
Write a function that gets as an input a sorted array of positive numbers `A`, and an additional number `n`. The Task is to print out all **distinct** subsets of `A`, that sum to `n`.

Example:

```
Input:
A = [1,2,2,4,4]
n = 9

Output:
[1,2,2,4]
[1,4,4]

```

Bonus: -50% if your code doesn't store duplicate subset (the same subset but in different order) intern. The function will not store more than one duplicate subset in memory at a time.

Shortest code in bytes wins.

# Answer
# Pyth, 6

```
@yE./Q

```

Try it online

We get all of the subsets of the given list with `yE`, and then `./Q` gets all of the integer partitions (lists of integers that add up to it) of the other input. `@` Finds the intersection of the two sets.
> 8 votes

# Answer
# Julia, ~~89~~ ~~82~~ 72 bytes

```
f(x,n)=partitions(n)∩foldl(vcat,[collect(combinations(x,i))for i=1:n])

```

This is a function that accepts an array and an integer and returns an array of arrays. It uses the same approach as FryAmTheEggman's clever Pyth answer and doesn't qualify for the bonus.

We get all combinations of the elements of *x* of size *i* for *i* in 1 to *n*, and take the intersection of this with the integer partitions of *n*. The resulting array is the set of combinations which are also partitions of *n*, i.e. those that sum to *n*.
> 3 votes

# Answer
# Pyth, 9 - 50% = 4.5 bytes

```
f!.-TQ./E

```

Try it online: Demonstration

Got a little bit inspired by Fry.

### Explanation:

```
f!.-TQ./E   implicit: Q = input list
      ./E   read a number from input and compute a list of partitions
f           filter for partitions T, which satisfy:
  .-TQ         remove the numbers in Q one by one from T
 !             check if the resulting list is empty
               (and therefore the partition is a subset of Q)

```
> 2 votes

# Answer
# JavaScript (ES6) 115

Using an hash table to store results, no duplicate is ever stored. But I doubt that this is what OP means for the bonus, so I will not claim it.

```
(A,n)=>[...Array(1<<A.length)].map((x,m)=>(x=A.filter((v,i)=>1<<i&m&&(t-=v,1),t=n),t||++s[x]),s={})&&Object.keys(s)

```

**Less golfed**

```
(A,n) =>
[...Array(1<<A.length)].map( // enumerate all the subsets (2^A.len)
  (x, // used as a local variable
   m  // current index, used as a bit mask
  ) => ( // build the current subset in x using bit mask
         // meanwhile, check if the elemnt sum is == n
    t = n,
    x = A.filter( (v,i) => 1<<i&m && (t-=v,1) ),
    t || ++s[x] // if the sum is n, add X to hash table (this avoid dups)
  ),
  s={}  // hash table init to empty
) && Object.keys(s) // return keys

```

**Test**

```
f=(A,n)=>[...Array(1<<A.length)].map((x,m)=>(x=A.filter((v,i)=>1<<i&m&&(t-=v,1),t=n),t||++s[x]),s={})&&Object.keys(s)

function go() {
  var a = A.value.match(/\d+/g)
  var n = +N.value
  O.textContent = f(a,n).join('\n')
}

go()
```

```
Array A <input id=A value='1 2 2 4 4'><br>
Value n <input id=N value=9><br>
<button onclick='go()'>Go</button>
<pre id=O></pre>
```
> 2 votes

# Answer
# Perl 6, 50 bytes - 50% = 25

`{@^a.combinations.unique(as=>~*).grep: *.sum==$^n}`

Ungolfed

```
sub d (@a,$n) {
    @a.combinations.unique(as => ~*).grep: *.sum == $n
}

```

Perl 6 has a built in `combinations` operator (as well as one for `permutations`!). Both of these return a lazy list.

`unique` by itself would not return unique combinations, because technically they are not unique (they are *equivalent*) so we tell `unique` to compare them as strings (`~$var` coerces `$var` to a string, and `*` means `Whatever`)

Then we `grep` for `Whatever.sum` is equal to n; Result of last evaluated expression is returned by default

Lastly, if I don't define a signature, I can use `$^var` to refer to a passed variable. Alphabetical (Positional) order matters with these, as `$^a` is passed in before `$^b`;
> 2 votes

# Answer
## Haskell, ~~54 * 1.0~~ 76 bytes * 0.5 = 38

```
import Data.List
f n=foldl(\r e->r++[e|notElem e r,sum e==n])[].subsequences

```

Usage example: `f 9 [1,2,2,4,4]` -\> `[[1,2,2,4],[1,4,4]]`.

Brute force: check every subsequences, keep it if it has the right sum and has not been seen before. `subsequences` build the list of subsequences lazily, i.e. one after the other, so at most one new element is kept in memory together with all unique elements so far.

For reference the previous version with the built-in function to remove duplicates, which requires to build the whole list of subsequences in memory. 54 bytes, no bonus.

```
import Data.List
x#n=nub[y|y<-subsequences x,sum y==n]

```
> 1 votes

# Answer
# MATL, 26 * 0.5 = 13

```
x{}FTinZ^!"0$G@)s=?2MVJX(u

```

Works with current version (14.0.0) of the language/compiler.

*EDIT (June 10, 2016): The link below replaces `J` by `JQ` to adapt to recent changes in the language*

**Try it online!**

### Explanation

All possible subsets are tested to see if the sum is correct. For each subset, if the sum condition is satisfied the subset is stored in a (cell) array. Immediately after that, duplicates are removed (the only possible duplicate at this point is the newly added array, and in that case it is removed). So this gets the bonus.

```
x        % take number input implicitly. Delete (gets copied into clipboard G)
{}       % push empty cell array. Will be grown with the found subsets
FT       % push array [false, true]
in       % take array input. Push its length
Z^!      % Cartesian power. 2D array in which each column indicates (via
         % logical indexing) which elements of the input array form a
         % subset. This covers all possible subsets.
"        % for each column
  0$G    %   push the two inputs: number, then array
  @)     %   apply logical index to extract the current subset
  s      %   compute its sum
  =      %   are they equal?
  ?      %   if so
    2M   %     push the subset again
    V    %     convert numbers to string. Needed to test for uniqueness
    JX(  %     append that to the cell array that stores the subsets
    u    %     remove duplicates (the only possible duplicate is the
         %     newly appended subset)
         %   end if implicitly
         % end for each implicitly
         % display implicitly

```
> 1 votes

# Answer
## Pyth, 8 bytes

```
{fqsTQyE

```

No bonus.

```
{ f         Unique elements of filter lambda T:
    q                     equals
      s T                        sum of T
      Q       First input
    y E    over all subsets of second input

```

Try it here.
> 1 votes

# Answer
# Ruby, 73 bytes

```
->x,n{(1..n).flat_map{|i|x.combination(i).select{|c|eval(c*?+)==n}.uniq}}

```

This is a lambda function that accepts an array and an integer and returns an array of arrays. To call it, assign it to a variable, say `f`, and do `f.call(x, n)`.

For each *i* from 1 to *n*, we get all combinations of size *i* of the elements of *x*, select those combinations *c* such that *c* sums to *n*, and take the unique elements.

Try it here
> 1 votes

# Answer
# Brachylog, 39 bytes

```
:1fd.,{,.[L:N]hs?{_,0 .|b:2&I,?h+I=.}N}

```

Called with a list containing the list of numbers first and the value of the sum second.
> 1 votes

# Answer
# 05AB1E, 8 bytes

Uses **CP-1252** encoding. Code:

```
æÙvyO²Q—

```

Try it online!
> 1 votes

# Answer
# PHP, 162 - 50% = 81 bytes

```
function c($a,$n){$o=[];for(;++$i<pow(2,count($a));){$s=[];foreach($a as$x=>$e)if($i&pow(2,$x))$s[]=$e;if(array_sum($s)==$n&&!in_array($s,$o))$o[]=$s;}return$o;}

```

Without a powerset built in this was kind of a pain.

```
for(;++$i<pow(2,count($a));)                    #generate integers
foreach($a as$x=>$e)if($i&pow(2,$x))$s[]=$e;    #use integers to generate subsets
if(array_sum($s)==$n&&!in_array($s,$o))$o[]=$s; #conditionally add suset to output

```

the rest is just necessary initialisation and output
> 1 votes

# Answer
# Jolf, 9 bytes, noncompeting

I had to do some bugfixes, ergo, invalid :( Try it here anyhow!

```
ψmψxd=uHj
 mψx      unique powerset of input array
ψ   d     filtered according to a function
     =uH   that tests if the sum of the member
        j  is the input number.

```

Test like

```
[1,2,2,4,4]

9

```
> 0 votes

# Answer
# Oracle SQL 11.2, 199 bytes

```
SELECT DISTINCT s FROM(SELECT SYS_CONNECT_BY_PATH(TRUNC(i),'+')s FROM(SELECT''||COLUMN_VALUE+ROWNUM/100 i FROM XMLTABLE((:a)))START WITH i>0 CONNECT BY i>PRIOR i),XMLTABLE(s)WHERE''||column_value=:n;

```

Inputs are :
:a the array of positive numbers, formated like "1","2","3","3"
:n the target number

Un-golfed :

```
SELECT DISTINCT s
FROM  (
        SELECT SYS_CONNECT_BY_PATH(TRUNC(i),'+')s
        FROM   (
                 SELECT ''||COLUMN_VALUE+ROWNUM/100 i
                 FROM   XMLTABLE((:a))
               )
        START WITH i>0 CONNECT BY i>PRIOR i
      ), XMLTABLE(s)
WHERE ''||column_value=:n;

```
> 0 votes

# Answer
# Mathematica, 33 bytes

```
Cases[{}⋃Subsets@#,s_/;Tr@s==#2]&

```

# Mathematica, 57 bytes (-50%) = 28.5 bytes

```
Cases[Fold[Append@@@Thread@{##}⋃#&,{{}},#],s_/;Tr@s==#2]&

```
> 0 votes

# Answer
# , 28 bytes

```
~.@((=+/@>)#])]<@#~2#:@i.@^#

```

Generates the power set and filters it before removing duplicates.

## Usage

Since J does not support ragged arrays, each subset is output within a box.

```
   f =: ~.@((=+/@>)#])]<@#~2#:@i.@^#
   9 f 1 2 2 4 4
┌─────┬───────┐
│1 4 4│1 2 2 4│
└─────┴───────┘

```

## Explanation

```
~.@((=+/@>)#])]<@#~2#:@i.@^#  Input: n on LHS, A on RHS
                           #  Get the size of A
                   2      ^   Get 2^len(A)
                       i.@    Get the range [0, 1, ..., 2^len(A)-1]
                    #:@       Convert each to binary to get the masks for each subset
                 #~           Copy using each mask from A
               <@             Box each subset
      +/@>                    Unbox each and reduce using addition
     =                        Check which sums are equal to n, 1 if true else 0
            ]                 Get the list of boxed subsets
           #                  Copy only those whose sums are equal to n
~.@                           Remove duplicates and return

```
> 0 votes

---
Tags: code-golf
---


title: King of the Hill - Spacewar!

text:
# Question
Title: King of the Hill - Spacewar!
If you've ever played Spacewar!, you know it was a fun game. If you haven't, know this: it was (and is) one of the very first and most important computer games. And it's still fun! The clone I grew up on is this one, which is, apparently and unfortunately, Windows only. So I recreated it!

**The KotH is hosted here: PPCG - Spacewar! King of the Hill.** I encourage you to play as a human against at least one other bot to get a feel for how the game works.

## The Game

* One frame is 30 milliseconds (thus, about 33 frames per second).
* The field is 800 pixels wide and 600 pixels tall.
* The field is toroidal, meaning that spaceships and missiles that move outside of the field reappear on the opposite side.
* There are two spaceships, red and blue.
    + Red is positioned at x=50 and random y between 50, (field height - 50) pixels.
    + Blue is positioned at x=(field width - 50) and random y between 50, (field height - 50) pixels.
    + Both face x = (field width)/2.
* The available controls are:
    + Turn left - 5 degrees per frame counterclockwise.
    + Turn right - 5 degrees per frame clockwise.
    + Fire missile - travels at an extra 10 pixels per frame in addition to the velocity of the ship, in the direction the ship was pointing.
    + Fire engine - accelerates the spaceship at 0.30 pixels per frame in the direction the spaceship is pointing.
    + Hyperspace jump - teleports to some random coordinates in the field, with a 25% chance of exploding. These random coordinates may be on top of the sun.
* The maximum speed for ships is 15 pixels per frame under engine power and 40 pixels per frame when gravity-boosted.
    + When traveling faster than 15 pixels per frame, engine thrust may only change direction or slow down.
* Regarding missiles:
    + Missiles travel in a straight line.
    + Missiles may be fired at a maximum rate of 1 per 0.1 seconds.
    + Missiles have a lifetime of 2.25 seconds.
    + Ships have a maximum of 20 missiles each.
    + Missiles are point particles internally.
* There is a sun in the very center that is extremely hazardous to your ship. The *slightest* contact is fatal. This sun also destroys missiles.
* The sun has gravity. The resultant acceleration is 5000/(distance^2) pixels/frame^2, where distance is in pixels. Spaceships and missiles are affected.
* Both ships have three strike zones: the nose, the left wing, and the right wing.
    + A hit on the nose is instant death.
    + A hit on either wing reduces the spaceship's turn rate and engine acceleration by half.
    + If both wings are destroyed, the spaceship cannot be maneuvered and can only fire missiles.
* Ships may collide with each other.
    + A nose-nose impact is fatal for both ships.
    + A nose-wing impact destroys the wing.
    + A wing-wing impact destroys both wings.
* Dead ships are solid and frozen until they explode 1 second later.
* After at least one ship has died, the field is reset 3 seconds later. Until then, the sun and any remaining missiles are still hazardous.

The original game also has deadly and indestructible asteroids, but I won't include those.

## The Rules

* Your bot must be written in JavaScript.
* Your bot should limit its decision to about 10 milliseconds. If I notice consistent lag *because of your bot*, I'll disqualify it and let you know so you can fix it.
* Bots will have access to the following:
    + Field width and field height
    + Sun position and radius
    + The position, rotation, velocity, shape, missile stock, and in-hyperspace status of both ships
    + The position and velocity of all missiles
* When prompted, your bot should return a list of strings.
    + These strings should be one of the following: `turn left`, `turn right`, `fire engine`, `fire missile`, `hyperspace`. Any other string will be ignored.
    + If there are any duplicates, only the first will be noted.
    + `hyperspace` takes precedence over all others.
    + `turn left` and `turn right` at the same time will have no effect.
    + `fire engine` will have no effect if the ship only has the nose or is dead.
    + `fire missile` will have no effect if a missile was fired too recently.
* In a change from the usual, **your bot is allowed to exploit the behavior of other bots.** I want to encourage a metagame.
    + Bots **may not** emulate other bots. (I.e., no mind-reading.)
    + Bots **may not** set any variables used by the game and physics code. (I.e., no cheating.)

## Bot Implementation Details

I will be storing your bot in its own JavaScript file that is automatically included, with the filename `bot_<name>.js`. So don't put any spaces or characters that would interfere with this or with naming a function in JavaScript. That's because you should define the following functions: `<name>_setup(team)` and `<name>_getActions(gameInfo, botVars)`. Further down the page, there exist textareas for the **userbot**, which you can edit to test your code.

### `<name>_setup(team)`

This function is for you to define any variables that you want to persist. `team` will be either `"red"` or `"blue"`. This function must return an object. Define variables like so:

```
var vars = {};
vars['example'] = "example";
return vars;

```

This `vars` object will be passed in to the other function:

### `<name>_getActions(gameInfo, botVars)`

`botVars` is the object returned by `<name>_setup(team)`. `gameInfo` is an object containing the following variables:

```
redScore
blueScore
timeLeft

fieldWidth
fieldHeight

sun_x
sun_y
sun_r //sun's radius

gravityStrength //acceleration in pixels/frame^2 at 1 pixel away from the sun's center
engineThrust    //acceleration in pixels/frame^2

speedLimit //maximum speed under engine power
maxSpeed   //maximum speed from gravity boosts

red_x
red_y
red_rot          //rotation in degrees
red_xv           //x velocity
red_yv           //y velocity
red_shape        //one of "full ship", "left wing", "right wing", "nose only"
red_missileStock //the number of missiles red has left
red_inHyperspace //true if red is in hyperspace
red_exploded     //until red explodes, it is still solid and hazardous
red_alive
// likewise for blue //

numMissiles
missiles //this is a list of objects, each with the following variables
  x
  y
  xv
  yv

```

Your bot has full access to these. I'm *pretty sure* that you can write to them and not affect the original variables, but don't do it anyway. **A note on rotations:** ships *point* in the +y direction, downwards, so anything that you want to align with the ship needs to be offset by 90 degrees. Also, positive rotation is clockwise.

This function must return a list of strings, representing your bot's actions. For example, `["turn right","thrust"]`. More details on this are in the **Rules** section.

## Additional Details

You may also make use of the following:

### `LineIntersection(L1, L2)`

L1 and L2 are two-element arrays of two-element arrays. That is, `L1 := [[x1,y1],[x2,y2]]` and `L2 := [[u1,v1],[u2,v2]]`. This function computes the intersection of two lines and returns this: `[[x,y], [a,b]]`. `[x,y]` are the coordinates of the intersection point and `[a,b]` is a pair of ratios that express how far along each line the intersection point is. As in, `a = 0.25` would mean that the intersection point is a quarter of the way from `[x1,y1]` to `[x2,y2]`, and likewise for `b`. **If there is no intersection, an empty array is returned.**

### `window["shipShapes"]`

```
var shipShapes = {
    'full ship': [[-8,16],[0,-8],[8,16]],
    'left wing': [[-8,16],[0,-8],[4,4],[0,8],[0,16]],
    'right wing':[[-4,4],[0,-8],[8,16],[0,16],[0,8]],
    'nose only': [[-4,4],[0,-8],[4,4],[0,8]]
};

```

These are the coordinates of the ships' polygons. To make getting the current coordinates easier, you may also use...

### `getShipCoords(<color>)`

`getShipCoords("red")` will return the current coordinates of the vertices of Red's ship, and likewise for `getShipCoords("blue")` and Blue. These coordinates are in a list like so: `[[x1,y1],[x2,y2],[x3,y3],...]`. Polygons are implicitly closed, so there is a line between the first and last coordinate pairs.

**You may not access or alter any other variables or functions in use by the game/website.** And definitely don't name your functions the same. I don't foresee that this will be a problem, but if your bot breaks the game code, that's one possibility. There is no logging or catching of exceptions.

## Winning

* Every pairing of bots shall be played at least 10 times, both ways. (So, at least 20 games total.)
* Aim to have the highest win/loss ratios *overall*. If your bot does super well against one other bot, but loses against the other three, that's not as good as winning against two and losing against two (as a general rule of thumb).
* For every bot, the ratios (wins+1)/(losses+1) will be calculated, then the mean and standard deviation of these ratios will be calculated. A higher mean will have priority, and in case means are within 1 unit of each other, the lower variance will have priority.
* Scoring will begin either in a week from today or after three days of no new submissions. This is so I don't have to repeat any pairing of bots.

**Above all, have fun!**

---

## Leaderboard (2016-01-08 05:15):

```
#   Name                       Mean      StdDev
1.  Helios                     13.625    6.852
2.  EdgeCase                    8.335    8.155
3.  OpponentDodger              8.415    8.186
4.  OrbitBot                    5.110    6.294
5.  SunAvoider                  5.276    6.772
6.  DangitBobby                 3.320    4.423
7.  SprayAndPray                3.118    4.642
8.  Engineer                    3.903    6.315
9.  RighthandedSpasms           1.805    2.477
10. AttackAndComeBack           2.521    2.921
11. PanicAttack                 2.622    3.102
12. FullSpeedAhead              2.058    3.295
13. UhhIDKWhatToCallThisBot     2.555    3.406
14. MissilesPlusScore           0.159    0.228
15. Hyper                       0.236    0.332
16. RandUmmm                    0.988    1.329
17. Kamikaze                    0.781    1.793

```

**Note:** This is subject to change as I run more games. Plus, the ordering of ranks 9-13 bothers me, so I may tweak the scoring method to better match one's intuition of how they should be ranked.

(Means and standard deviations were rounded to three decimal digits. Also, `Hyper` should be `HYPER` but that messes up the highlighting. :P)

# Answer
# Helios

This bot is the center of the universe, or at least he thinks he is. The first thing he makes is to correct a grave error and place himself in the center of the coordinate system. Then he rotates anything around himself.

He doesn't like the other (fake) sun, therefore he tries to stay away from it. He also doesn't like other bots, therefore he shoots at them, if he is in a good shooting position.

```
function Helios_setup(team) {
    var botVars = {};
    botVars.myPrefix = team + "_";
    botVars.enemyPrefix = team == "red" ? "blue_" : "red_";
    return botVars;
}

function Helios_getActions(gameInfo, botVars) {
    var actions = [];
    var halfPi = Math.PI / 2;
    var engageAngle = Math.PI / 8;

    var field = {};
    field.width = gameInfo.fieldWidth;
    field.height = gameInfo.fieldHeight;
    field.halfWidth = field.width / 2;
    field.halfHeight = field.height / 2;
    field.posOffsetX = field.width * 3 / 2 - gameInfo[botVars.myPrefix + "x"];
    field.posOffsetY = field.height * 3 / 2 - gameInfo[botVars.myPrefix + "y"];
    field.posAngle = (450 - gameInfo[botVars.myPrefix + "rot"]) % 360 * Math.PI / 180;
    field.posSin = Math.sin(-field.posAngle);
    field.posCos = Math.cos(-field.posAngle);
    field.movOffsetXV = -gameInfo[botVars.myPrefix + "xv"];
    field.movOffsetYV = gameInfo[botVars.myPrefix + "yv"];
    field.movAngle = Math.atan2(-field.movOffsetYV, -field.movOffsetXV);
    field.movSin = Math.sin(-field.movAngle);
    field.movCos = Math.cos(-field.movAngle);

    function zeroIfUndefined(v) {
        return v === undefined ? 0 : v;
    }

    function sqr(x) {
        return x * x
    }

    function getEntity(source, prefix) {
        var tmpX = (field.posOffsetX + zeroIfUndefined(source[prefix + "x"])) % field.width - field.halfWidth;
        var tmpY = field.halfHeight - (field.posOffsetY + zeroIfUndefined(source[prefix + "y"])) % field.height;
        var tmpXV = zeroIfUndefined(source[prefix + "xv"]);
        var tmpYV = -zeroIfUndefined(source[prefix + "yv"]);
        var e = {};
        e.posX = tmpX * field.posCos - tmpY * field.posSin;
        e.posY = tmpX * field.posSin + tmpY * field.posCos;
        e.posR = Math.sqrt(sqr(e.posX) + sqr(e.posY));
        e.posPhi = Math.atan2(e.posY, e.posX);
        e.posXV = tmpXV * field.posCos - tmpYV * field.posSin;
        e.posYV = tmpXV * field.posSin + tmpYV * field.posCos;
        e.posV = Math.sqrt(sqr(e.posXV) + sqr(e.posYV));
        e.movX = tmpX * field.movCos - tmpY * field.movSin;
        e.movY = tmpX * field.movSin + tmpY * field.movCos;
        e.movR = Math.sqrt(sqr(e.movX) + sqr(e.movY));
        e.movPhi = Math.atan2(e.movY, e.movX);
        e.movXV = (tmpXV + field.movOffsetXV) * field.movCos - (tmpYV + field.movOffsetYV) * field.movSin;
        e.movYV = (tmpXV + field.movOffsetXV) * field.movSin + (tmpYV + field.movOffsetYV) * field.movCos;
        return e;
    }

    function getShip(prefix) {
        var ship = getEntity(gameInfo, prefix);
        ship.missileStock = gameInfo[prefix + "missileStock"];
        ship.inHyperspace = gameInfo[prefix + "inHyperspace"];
        ship.exploded = gameInfo[prefix + "exploded"];
        ship.alive = gameInfo[prefix + "alive"];
        return ship;
    }

    var myShip = getShip(botVars.myPrefix);
    myShip.movAngle = (field.posAngle - field.movAngle + 3 * Math.PI) % (2 * Math.PI) - Math.PI;
    var enemyShip = getShip(botVars.enemyPrefix);
    var sun = getEntity(gameInfo, "sun_");

    enemyShip.intersectionLine = [[enemyShip.movX - enemyShip.movXV * 30, enemyShip.movY - enemyShip.movYV * 30],
            [enemyShip.movX + enemyShip.movXV * 30, enemyShip.movY + enemyShip.movYV * 30]];

    var intersection = LineIntersection([[0, 0], [Math.cos(myShip.movAngle) * 10 * 30, Math.sin(myShip.movAngle) * 10 * 30]],
            enemyShip.intersectionLine);
    if (intersection.length == 2) {
        myShip.intersection = Math.abs(intersection[1][0] / 2 + 0.5 - intersection[1][1]);
    }
    intersection = LineIntersection([[0, 0], [Math.cos(myShip.movAngle - 0.001) * 10 * 30, Math.sin(myShip.movAngle - 0.001) * 10 * 30]],
            enemyShip.intersectionLine);
    if (intersection.length == 2) {
        myShip.intersectionLeft = Math.abs(intersection[1][0] / 2 + 0.5 - intersection[1][1]);
    }
    intersection = LineIntersection([[0, 0], [Math.cos(myShip.movAngle + 0.001) * 10 * 30, Math.sin(myShip.movAngle + 0.001) * 10 * 30]],
            enemyShip.intersectionLine);
    if (intersection.length == 2) {
        myShip.intersectionRight = Math.abs(intersection[1][0] / 2 + 0.5 - intersection[1][1]);
    }

    function danger() {
        var tmp1 = sqr(sun.movXV) + sqr(sun.movYV);
        var tmp2 = tmp1 == 0 ? 0 : Math.max(0, Math.min(1, ((-sun.movX) * sun.movXV + (-sun.movY) * sun.movYV) / tmp1));
        var dis = Math.sqrt(sqr(sun.movX + tmp2 * sun.movXV) + sqr(sun.movY + tmp2 * sun.movYV));
        if (dis < 30) {
            return true;
        }
        var shipLine1 = [[-16, 8], [-16, -8]];
        var shipLine2 = [[-16, 8], [8, 0]];
        var shipLine3 = [[-16, -8], [8, 0]];
        if (gameInfo.missiles !== undefined) {
            for (var i = 0; i < gameInfo.missiles.length; i++) {
                var missile = getEntity(gameInfo.missiles[i], "");
                var missileLine = [[missile.movX + missile.movXV * 0.5, missile.movY + missile.movYV * 0.5],
                        [missile.movX + missile.movXV * 3, missile.movY + missile.movYV * 3]];
                if (LineIntersection(shipLine1, missileLine).length == 2 ||
                        LineIntersection(shipLine2, missileLine).length == 2 ||
                        LineIntersection(shipLine3, missileLine).length == 2) {
                  return true;
                }
            }
        }
        return false;
    }

    function fire() {
        return enemyShip.alive && !enemyShip.inHyperspace && myShip.intersection !== undefined &&
            myShip.intersection < 0.1 + myShip.missileStock / 200;
    }

    function evadeSun() {
        if ((sun.movPhi >= 0 && myShip.movAngle < 0) || (sun.movPhi <= 0 && myShip.movAngle > 0)) {
            actions.push("fire engine");
        }
        if (sun.movPhi > 0) {
            if (Math.abs(myShip.movAngle) < halfPi) {
                actions.push("turn right");
            } else {
                actions.push("turn left");
            }
        } else {
            if (Math.abs(myShip.movAngle) < halfPi) {
                actions.push("turn left");
            } else {
                actions.push("turn right");
            }
        }
    }

    function aim() {
        if (myShip.intersection !== undefined && myShip.intersectionLeft !== undefined && myShip.intersectionLeft < myShip.intersection) {
            actions.push("turn left");
        } else if (myShip.intersection !== undefined && myShip.intersectionRight !== undefined && myShip.intersectionRight < myShip.intersection) {
            actions.push("turn right");
        } else {
            if (enemyShip.posPhi > 0) {
                actions.push("turn left");
            } else {
                actions.push("turn right");
            }
        }
        if (myShip.posV < 2 || (enemyShip.alive && (enemyShip.movXV >= 0 || myShip.missileStock == 0))) {
            actions.push("fire engine");
        }
    }

    function brake() {
        if (myShip.movAngle > 0) {
            actions.push("turn left");
        } else {
            actions.push("turn right");
        }
        if (Math.abs(myShip.movAngle) > Math.PI * 3 / 4) {
            actions.push("fire engine");
        }
    }

    function engage() {
        if (enemyShip.missileStock > 0) {
            if ((enemyShip.posPhi > 0 && enemyShip.posPhi < engageAngle) || enemyShip.posPhi < -engageAngle) {
                actions.push("turn right");
            } else {
                actions.push("turn left");
            }
        } else {
            if (enemyShip.posPhi > 0) {
                actions.push("turn left");
            } else {
                actions.push("turn right");
            }
        }
        actions.push("fire engine");
    }

    if (myShip.alive && !myShip.inHyperspace) {
        if (danger()) {
            actions.push("hyperspace");
        }
        if (fire()) {
            actions.push("fire missile");
        }
        if (enemyShip.exploded || enemyShip.inHyperspace || sun.movR < 150 || (sun.movR < 300 && Math.abs(sun.movPhi) < Math.PI)) {
            evadeSun();
        } else if (enemyShip.posR < 300 || myShip.intersection !== undefined) {
            aim();
        } else if (myShip.posV > 10) {
            brake();
        } else {
            engage();
        }
    }

    return actions;
}

```
> 12 votes

# Answer
## SunAvoider

This one just tries to stay away from the sun. It does so pretty well...until it gets one or both wings destroyed, then it's usually only a matter of time before it falls in.

```
function SunAvoider_setup(team) {
    var botVars = {};

    botVars["color"] = team;

    return botVars;
}

function SunAvoider_getActions(gameInfo, botVars) {
    var actions = [];

    if (gameInfo[botVars["color"]+"_alive"]) {
        var shipx = gameInfo[botVars["color"]+"_x"];
        var shipy = gameInfo[botVars["color"]+"_y"];
        var sunx = gameInfo["sun_x"];
        var suny = gameInfo["sun_y"];
        var dx = shipx - sunx;
        var dy = shipy - suny;
        var dis = Math.sqrt(dx*dx+dy*dy);
        var fireEngineChance = (dis-100)/(gameInfo["fieldHeight"]/2);

        if (Math.random() > fireEngineChance){ actions.push("fire engine") }

        var ang1 = gameInfo[botVars["color"]+"_rot"]+90;
        var ang2 = Math.degrees( Math.atan2(dy, dx) );
        var angDiff = ang2 - ang1;
        if (angDiff < -180) { //http://stackoverflow.com/a/7869457/1473772
            angDiff += 360;
        } else if (angDiff > 180) {
            angDiff -= 360;
        }

        if (angDiff >= 0) {
            actions.push("turn left");
        } else if (angDiff < 0) {
            actions.push("turn right");
        }
    }

    return actions;
}

```
> 9 votes

# Answer
# EdgeCase

Flies at full speed away from the sun towards the edge of the map! When it finds itself pointed towards the sun it will start shooting while turning itself away to get back to the edge. It also enters hyperspace when it's about to hit the sun.

```
function EdgeCase_setup(team) {
  var botVars = {};
  botVars["color"] = team;
  return botVars;
}

function EdgeCase_getActions(gameInfo, botVars) {
  var actions = [];

  // Get our ship's position
  var rotation, x, y, opponentAlive;
  if(botVars.color == "red") {
    rotation = gameInfo.red_rot;
    x = gameInfo.red_x;
    y = gameInfo.red_y;
    opponentAlive = gameInfo.blue_alive;
  }
  else if(botVars.color == "blue") {
    rotation = gameInfo.blue_rot;
    x = gameInfo.blue_x;
    y = gameInfo.blue_y;
    opponentAlive = gameInfo.red_alive;
  }

  // Calculate our rotation compared to the sun in degrees
  var sunX = gameInfo.sun_x,
      sunY = gameInfo.sun_y,
      angle = Math.atan2(sunY - y, sunX - x) * 180 / Math.PI,
      rotationToSun = (rotation - angle + 360) % 360;

  // Check if we need to hyperspace to avoid the sun
  var rX = x - sunX,
      rY = y - sunY,
      distanceFromSun = Math.sqrt(rX * rX + rY * rY) - gameInfo.sun_r;
  if(distanceFromSun < 30) actions.push("hyperspace");
  else {

    // Turn away from the sun
    if(rotationToSun > 90 && rotationToSun < 270) {
      actions.push("turn right");
    }
    else actions.push("turn left");

    // Fire engines if we're pointing away from the sun
    if(rotationToSun > 180) {
      actions.push("fire engine");
    }

    // If we shoot while our opponent's dead we can only kill ourself
    else if(opponentAlive) actions.push("fire missile");
  }

  return actions;
}

```
> 9 votes

# Answer
# OrbitBot

Currently has no targeting ~~or collision avoidance~~. It tries to orbit the sun.

**Edit: Now goes into hyperspace when impact is imminent.**

```
function OrbitBot_setup(team) {
  var botVars = {};

  botVars.color = team;
  return botVars;
}

function OrbitBot_getActions(gameInfo, botVars) {
  var actions = [];

  function getVar(name) {
    return gameInfo[botVars.color + "_" + name];
  }

  function getEnemyVar(name) {
    var eColor;
    if (botVars.color == 'blue') {
        eColor = 'red';
    } else {
        eColor = 'blue';
    }
    return gameInfo[eColor + "_" + name];
  }

  function distance(x1, y1, x2, y2) {
    return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
  }

  function toroidDistance(x1, y1, x2, y2) {
    dx = Math.abs(x1 - x2);
        while (dx > gameInfo.fieldWidth) {
        dx -= gameInfo.fieldWidth;
    }
    dx = Math.min(dx, gameInfo.fieldWidth - dx);
    dy = Math.abs(y1 - y2);
        while (dx > gameInfo.fieldHeight) {
        dx -= gameInfo.fieldHeight;
    }
    dy = Math.min(dy, gameInfo.fieldHeight - dy);
    return Math.sqrt(dx*dx+dy*dy);
  }

  function angleDistance(theta1, theta2) {
    var d = theta1 - theta2;
    while (d < 0 || d > Math.PI) {
      if (d < 0) {
        d += Math.PI * 2;
      }
      if (d > Math.PI * 2) {
        d -= Math.PI * 2;
      } else if (d > Math.PI) {
        d = Math.PI * 2 - d;
      }
    }
    return d;
  }

  function toRad(degrees) {
    return degrees / 180 * Math.PI;
  }

  function cap(x, y, limit) {
    var r = x*x+y*y;
    if (r < limit * limit) {
        r = Math.sqrt(r);
        x = x * r / limit;
      y = y * r / limit;
    }
    return [x,y];
  }

  var shape = getVar('shape');

  if (shape != 'nose only') {
    var broken = shape != 'full ship';
    var sunX = gameInfo.sun_x,
      sunY = gameInfo.sun_y,
      sunG = gameInfo.gravityStrength;

    function desirability(x, y, vx, vy) {     //Borrowed from a useless bot.
      var lowest = distance(x, y, sunX, sunY) - 5;
      var missiles = gameInfo.missiles;
      for (var i = 0; i < missiles.length; i++) {
        var mx = missiles[i].x + missiles[i].xv / 2;
        var my = missiles[i].y + missiles[i].yv / 2;
        lowest = Math.min(lowest, toroidDistance(x, y, mx, my) - distance(0, 0, missiles[i].xv, missiles[i].yv));
      }
      return lowest - 16;
    }

    var x = getVar("x"),
      y = getVar("y"),
      vx = getVar("xv"),
      vy = getVar("yv");

    function desirabilityByAcceleration(ax, ay) {//Borrowed from a useless bot.
        var x1 = x,
            y1 = y,
          vx1 = vx,
          vy1 = vy;
      var speed = distance(0,0,vx1,vy1);
      var limit = Math.max(gameInfo.speedLimit, speed);

      vx1 += ax;
      vy1 += ay;
      var temp = cap(vx1, vy1, limit);
      vx1 = temp[0];
      vy1 = temp[1];

      var dx = x1 - sunX;
      var dy = y1 - sunY;
      var dis = Math.sqrt(dx*dx+dy*dy);
      if (dis > 5){
        var force = sunG / (dis * dis);
      } else {
        var force = sunG /5;
      }
      vx1 -= force*dx/dis;
      vy1 -= force*dy/dis;

      var temp = cap(vx1, vy1, 40);
      vx1 = temp[0];
      vy1 = temp[1];

      x1 += vx1;
      y1 += vy1;

      return desirability(x1, y1, vx1, vy1);
    }

    var r = distance(sunX, sunY, x, y);
    var theta = Math.atan((y - sunY) / (x - sunX));

    var sunA = sunG/r/r,
            sunAx = -Math.cos(theta) * sunA,
        sunAy = -Math.sin(theta) * sunA;

    var dv = Math.sqrt(sunG / r);
    var dvx = -dv * Math.sin(theta);
    var dvy = dv * Math.cos(theta);
    if (distance(-dvx, -dvy, vx, vy) < distance(dvx, dvy, vx, vy)) {
      dvx = -dvx;
      dvy = -dvy;
    }

    var dax = dvx - vx;
    var day = dvy - vy;

    var dAngle = Math.atan(day / dax);
    if (dax < 0) {
        dAngle += Math.PI;
    }
    var cAngle = toRad(getVar('rot') - 90);
    var dLeft = angleDistance(cAngle - toRad(broken ? 2.5 : 5), dAngle);
    var dRight = angleDistance(cAngle + toRad(broken ? 2.5 : 5), dAngle);
    var dNeither = angleDistance(cAngle, dAngle);
    if (dLeft < dRight && dLeft < dNeither) {
      actions.push('turn left');
    } else if (dRight < dLeft && dRight < dNeither) {
      actions.push('turn right');
    }

    var cax = Math.cos(cAngle) * (broken ? .15 : .3);
    var cay = Math.sin(cAngle) * (broken ? .15 : .3);

    var ax = 0;
    var ay = 0;

    if (distance(cax, cay, dax, day) < distance(0, 0, dax, day)) {
      actions.push('fire engine');
      ax = cax;
      ay = cay;
    }

    if (desirabilityByAcceleration(ax, ay) <= 16) {
        actions.push('hyperspace');
    }

  }

  return actions;
}

```
> 7 votes

# Answer
## RighthandedSpasms

The name is pretty descriptive. Chooses `turn right` with 0.5 probability, `fire engine` with 0.5 probability, and `fire missile` with 0.8 probability. Surprisingly difficult, mainly because it's really unpredictable.

```
function RighthandedSpasms_setup(team) {
    var botVars = {};

    botVars["color"] = team;

    return botVars;
}

function RighthandedSpasms_getActions(gameInfo, botVars) {
    var actions = [];

    if (gameInfo[botVars["color"]+"_alive"]) {
        if (Math.random() > 0.5) { actions.push("turn right") }
        if (Math.random() > 0.5) { actions.push("fire engine") }
        if (Math.random() > 0.8) { actions.push("fire missile") }
    }

    return actions;
}

```
> 5 votes

# Answer
# RandUmmm

This challenge needed a random bot. Bonus points for golfiness?

```
function RandUmmm_setup(t){
    function P(n,t,r,o,e,f,g){for(o=[e=1<<(f=n.length)];e;)for(t=e.toString(2),r=g=t.length,o[--e]=[];r;)~-t[--r]||o[e].push(n[r+f-g]);return o}var q=P(["fire missile","turn right","fire engine","turn left"]);q.pop();
    return {color:t,m:function(){return q[Math.random()*q.length|0]}};
}

function RandUmmm_getActions(g,b){
    return b.m();
}

```
> 5 votes

# Answer
# Engineer

Likes to use hyperspace when in danger. To see it's true power, open up your browser's console and type `overideHyperspace = 0;`. If you forget the semicolon, you'll get ASI for Christmas.

```
function Engineer_setup(t){
    return{c:t,C:"red0blue".split(0)[+(t=="red")]};
}

function Engineer_getActions(gameInfo,botVars){
    var actions = [];

    function d(x1,y1,x2,y2){return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))}
    function hS(g){return d(g.sun_x,g.sun_y,g[botVars.c+"_x"],g[botVars.c+"_y"])<50}
    function enemyDist(g){return d(g[botVars.c+"_x"],g[botVars.c+"_y"],g[botVars.C+"_x"],g[botVars.C+"_y"]);}

    function hSm(g){
        // get closest missile
        var r = (g.missiles||[{x:10000,y:10000}]).reduce(function(p,c){return Math.min(d(c.x,c.y,g[botVars.c+"_x"],g[botVars.c+"_y"]),p)},Infinity);
        return r<18;
    }
    function dF(g){
        var a = Math.degrees(Math.atan2(g[botVars.C+"_y"]-g[botVars.c+"_y"],g[botVars.C+"_x"]-g[botVars.c+"_x"]));
        var tP = (g[botVars.c+"_rot"]+360-a)%360;
        return [a,tP];
    }
    function lOr(g){
        var tP = dF(g)[1];
        return 90<tP&&tP<270?"turn left":"turn right";
    }
    function thrust(g){
        return Math.abs(dF(g)-g[botVars.c+"_rot"]);
    }

    // are we too close to the sun or a missile?
    if(hS(gameInfo)||hSm(gameInfo))actions.push("hyperspace");

    // should we fire?
    if(enemyDist(gameInfo)<200)actions.push("fire missile");

    // direction function
    actions.push(lOr(gameInfo,botVars));

    if(Math.random()<.7)actions.push("fire engine");
    return actions;
}

```
> 4 votes

# Answer
# SprayAndPray

```
function SprayAndPray_setup(team) {
    var botVars = {};
    botVars["color"] = team;
    return botVars;
}

function SprayAndPray_getActions(gameInfo, botVars) {
    var actions = [];

    if (gameInfo[botVars["color"]+"_alive"]) {
        actions.push("turn left");
        if (Math.random() > 0.5) { actions.push("fire engine")};
       actions.push("fire missile");
    }

    return actions;
}

```

Fires wildly in every direction. It's not very effective!
> 3 votes

# Answer
# Kamikaze

Not very competitive but I thought it would be fun! Just flies straight towards it's opponent while shooting.

```
function Kamikaze_setup(team) {
  var botVars = {};
  botVars["color"] = team;
  return botVars;
}

function Kamikaze_getActions(gameInfo, botVars) {
  var actions = [];

  // Get our ship's position
  var us, them, red = {
        rotation: gameInfo.red_rot,
        x: gameInfo.red_x,
        y: gameInfo.red_y,
        alive: gameInfo.blue_alive
      },
      blue = {
        rotation: gameInfo.blue_rot,
        x: gameInfo.blue_x,
        y: gameInfo.blue_y,
        alive: gameInfo.blue_alive
      };
  if(botVars.color == "red") {
    us = red;
    them = blue;
  }
  else if(botVars.color == "blue") {
    us = blue;
    them = red;
  }

  // Turn towards our opponent's position
  var angle = Math.degrees(Math.atan2(them.y - us.y, them.x- us.x)),
      rotationToOpponent = (us.rotation - angle + 360) % 360;
  if(rotationToOpponent > 90 && rotationToOpponent < 270) {
    actions.push("turn left");
  }
  else actions.push("turn right");

  actions.push("fire missile", "fire engine");

  return actions;
}

```
> 3 votes

# Answer
# UhhIDKWhatToCallThisBot

Just random stuff.

```
function UhhIDKWhatToCallThisBot_setup(team) {
var botVars = {};
 botVars['t'] = 0;
botVars["color"] = team;
     return botVars;

}

function UhhIDKWhatToCallThisBot_getActions(gameInfo, botVars) {
    var actions = [];
    //when i need it: "turn left",
    //Use missiles sparingly!
    var WCID = [
    "fire engine",
     "turn right",
    "fire engine",
    "fire missile",
    "turn right",
    "fire engine"]

    if (gameInfo[botVars["color"]+"_alive"]) {
        botVars['t']++;
        actions.push(WCID[botVars[t]%(WCID.length)]);
    }
     return actions;
}

```
> 2 votes

# Answer
# OpponentDodger

GET AWAY FROM ME OPPONENT!!!

```
function OpponentDodger_setup(t){b={};b["c"]=t;b['o']=(t=="red")?"blue":"red";return b;}function OpponentDodger_getActions(g,b){a=[];o=b["c"];j={r:g[o+"_rot"],x:g[o+"_x"],y:g[o+"_y"]};o=b["o"];p={r:g[o+"_rot"],x:g[o+"_x"],y:g[o+"_y"]};l=Math.degrees(Math.atan2(p.y-j.y,p.x-j.x)),x=(j.r-l+360)%360;if(x > 90 && x < 270)a.push("turn right");else a.push("turn left");a.push("fire engine");return a;}

```

Thanks to user81655 for some code!
> 2 votes

# Answer
# Spy

## The story

The prototype to this bot was a bot that had two modes: crazy mode and normal mode. When it was in crazy mode, it stayed there for a constant number of ticks. There was a contant probability of entering crazy mode. It also hyperspaced when it was close to the sun. In crazy mode, it aimed to the other bot and fired constantly. In normal mode, it flew away from the other bot, not firing.

I tweaked that prototype so that it would be in crazy mode if and only if the enemy was close enough. Then I had a crazy idea: what if it only stayed in crazy mode? After some experimentation (I added making the bot fire randomly when it was in normal mode) I found me new bot beat every bot but Helios. This is my code at the end of this process, but before cleaning up.

I wrote my entire bot in the KotH textarea or the JS beautifier. (I did briefly use the Atom editor when cleaning up - but for like two lines of code)

## The bot

This bot contains a lot of code borrowed from other bots. It flips the code from Kamikaze to run away from the other bot instead of running to the other bot and it takes code from EdgeCase for hyperspacing when it's close to the sun.

It's arch nemesis is Helios. It being the odd one out and long chats with a martini.

It runs away from the other bot with a 70% chance of firing a missile and hyperspaces when it's close to the sun. As simple as that. Yep.

Edit: I tested my bot with the new code and it fails for every other bot. I'm working on fixing it. I just confirmed this is only for my new bot.

## The code

```
function Spy_setup(team) {
  // Typical setup. Nothing to see here. ;)
  var botVars = {};
  botVars["color"] = team;
  return botVars;
}

function Spy_getActions(gameInfo, botVars) {
    var actions = [];
    var us, them, red = {
            rotation: gameInfo.red_rot,
            x: gameInfo.red_x,
            y: gameInfo.red_y,
            alive: gameInfo.blue_alive
        },
        blue = {
            rotation: gameInfo.blue_rot,
            x: gameInfo.blue_x,
            y: gameInfo.blue_y,
            alive: gameInfo.blue_alive
        };
    if (botVars.color == "red") {
        us = red;
        them = blue;
    } else if (botVars.color == "blue") {
        us = blue;
        them = red;
    }

    function distance(x1, y1, x2, y2) {
        return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
    }

    // Get our ship's position
    var rotation, x, y, opponentAlive;
    if (botVars.color == "red") {
        rotation = gameInfo.red_rot;
        x = gameInfo.red_x;
        y = gameInfo.red_y;
        opponentAlive = gameInfo.blue_alive;
    } else if (botVars.color == "blue") {
        rotation = gameInfo.blue_rot;
        x = gameInfo.blue_x;
        y = gameInfo.blue_y;
        opponentAlive = gameInfo.red_alive;
    }

    // Calculate our rotation compared to the sun in degrees
    var sunX = gameInfo.sun_x,
        sunY = gameInfo.sun_y,
        angle = Math.atan2(sunY - y, sunX - x) * 180 / Math.PI,
        rotationToSun = (rotation - angle + 360) % 360;

    // Check if we need to hyperspace to avoid the sun
    var rX = x - sunX,
        rY = y - sunY,
        distanceFromSun = Math.sqrt(rX * rX + rY * rY) - gameInfo.sun_r;
    if (distanceFromSun < 30) {
        actions.push("hyperspace");
        console.log("Command Module is Hyperspacing.")
    }
    if (gameInfo[botVars["color"] + "_alive"]) {
        var angle = Math.degrees(Math.atan2(them.y - us.y, them.x - us.x)),
            rotationToOpponent = (us.rotation - angle + 360) % 360;
        if (rotationToOpponent > 90 && rotationToOpponent < 270) {
            actions.push("turn right");
        } else {
            actions.push("turn left");
        };
        actions.push("fire engine");
        if (Math.random() > 0.3) {
            actions.push("fire missile")
        }

    }
    return actions;
}

```

## The misc

Note: I might've broke something when cleaning up the code because I didn't test the bot after cleaning up the code.

It's also much much much better than all my other bots - it actually beat every other bot except for Helios **(edit)** , SetCourseFor30Degrees, and OrbitBot! It ties with SunAvoider.

Side note: I'm horrible at javascript, don't know why.
> 2 votes

# Answer
# PanicAttack

Has a 50% chance of firing, and an 80% chance of turning left; but if it doesn't turn left, it'll turn right. After it runs out of missiles, time will eventually make it stop due to the sun.

**EDIT:** Added some logic to not fire when the enemy is alive because it could get killed by its own missiles.

```
function PanicAttack_setup(team) {
    var botVars = {};
    botVars["color"] = team;
    return botVars;
}

function PanicAttack_getActions(gameInfo, botVars) {
    var actions = [];
    actions.push("fire engine");
    if(botVars.color == "red") {
        var opponentAlive = gameInfo.blue_alive;
    }
    else if(botVars.color == "blue") {
        var opponentAlive = gameInfo.red_alive;
    }

    if ((Math.random()>0.5)&&opponentAlive) {
        actions.push("fire missile");
    }

    if (Math.random()>0.2) {
        actions.push("turn left");
    } else {
        actions.push("turn right");
    }

    return actions;
}

```
> 1 votes

# Answer
# AttackAndComeBack

Instead of swirling, it comes in at the top and exits at the bottom (returning at the top), firing very quickly. Generally avoids the sun.

```
function AttackAndComeBack_setup(team) {
    var botVars = {};
    botVars["color"] = team;
    return botVars;
}

function AttackAndComeBack_getActions(gameInfo, botVars) {
    var actions = [];
    actions.push("fire missile");
    if (Math.random()>0.4){actions.push("turn right");}
    else {actions.push("turn left");}
    actions.push("fire engine");
    return actions;
}

```
> 1 votes

# Answer
## FullSpeedAhead

Always fires both the engines and the missiles without turning ever. Sometimes lasts surprisingly long before hitting the sun.

```
function FullSpeedAhead_setup(team){
    return {color: team};
}

function FullSpeedAhead_getActions(gameInfo, botVars){
    var actions = [];

    if (gameInfo[botVars["color"]+"_alive"]) {
        actions.push("fire engine");
        actions.push("fire missile");
    }
    return actions;
}

```
> 1 votes

# Answer
# DangitBobby

Bobby Hill doesn't care what others think about him- he's quite content to swing lazily around the field and patiently wait for his opponent to run out of steam before striking like a "husky" cobra.

```
function DangitBobby_setup(team) {
    var botVars = {};
    botVars["color"] = team;
    if (team == 'red'){
        botVars['them'] = "blue";
    }
    else{
        botVars['them'] = 'red';
    }
    return botVars;
}

function DangitBobby_getActions(gameInfo, botVars) {
    var actions = [];
    if (gameInfo[botVars["color"]+"_alive"]) {
        actions.push('turn right');
        actions.push('fire engine');
        if (gameInfo[botVars['them']+'_missileStock'] == 0){
                actions.push('fire missile');
        }

    }
}

```

"THAT'S MY PURSE! I DON'T KNOW YOU!"
> 1 votes

# Answer
# Sniper

I've been playing with prediction for a bit to create a sniper bot that snipes his enemies. My javascript is too large to fit in an answer so here is a link, bot\_Sniper.
> 1 votes

# Answer
## SmartArrow

Like Arrow, but smart

```
function SmartArrow_setup(team) {
    var botVars = {};
    botVars['mpref'] = team + '_';
    botVars['epref'] = team == 'red' ? 'blue_' : 'red_';
    botVars['ecolor'] = team == 'red' ? 'blue' : 'red';
    return botVars;
}

function SmartArrow_getActions(gameInfo, botVars) {
    var actions = [];
    var x = gameInfo[botVars['mpref'] + 'x'],
        y = gameInfo[botVars['mpref'] + 'y'],
        rot = gameInfo[botVars['mpref'] + 'rot']; // SmartArrow position and rotation
    var ex = gameInfo[botVars['epref'] + 'x'],
        ey = gameInfo[botVars['epref'] + 'y']; // Enemy position
    var sunx = gameInfo.sun_x,
        suny = gameInfo.sun_y; // Sun position
    var Dsunx = Math.abs(x - sunx),
        Dsuny = Math.abs(y - suny); // Sun position delta
    var dex = Math.abs(x - ex),
        dey = Math.abs(y - ey); // Enemy position delta
    var sangle = Math.degrees(Math.atan2(suny - y, sunx - x)),
        snrot = (rot - sangle + 360) % 360;
    if (Dsunx < 40 && Dsuny < 40) // If SmartArrow is too close from sun, hyperspace !
        return ['hyperspace'];
    var missiles = gameInfo.missiles;
    for (var i = 0; i < missiles.length; i++) { // Avoid all these silly missiles
        var dx = Math.abs(x - missiles[i].x),
            dy = Math.abs(y - missiles[i].y);
        if (dx < 10 && dy < 10)
            return ['hyperspace'];
    }
    if (gameInfo[botVars['epref'] + 'alive']) { // If his enemy is alive, SmartArrow try to kill him (logic)
        var angle = Math.degrees(Math.atan2(ey - y, ex - x)),
            nrot = (rot - angle + 360) % 360;
        if (nrot > 90 && nrot < 270)
            actions.push('turn left');
        else
            actions.push('turn right');
        if (nrot > 80 && nrot < 100
         && Math.random() > 0.5) actions.push('fire missile'); // If SmartArrow is in a good spot, shot this silly oponnent
        if (Math.random() > 0.5) actions.push('fire engine');
    }
    else { // Simply (try to) act like SunAvoider if his enemy is dead
        if (snrot > 90 && snrot < 270)
            actions.push('turn right');
        else
            actions.push('turn left');
        if (Dsunx < 300 && Dsuny < 300)
            actions.push('fire engine');
        if (dex < 40 && dey < 40)
            actions.push('hyperspace'); // Dying on the corpse of his opponent is dumb.
    }
    return actions;
}

```
> 1 votes

# Answer
# Kamikaze-

**Also not designed to be competitive.** Just for fun. It hyperspaces when close to the sun and chases the player without firing bullets. It's fun to watch this bot chase an unarmed version of Spy, but you can't have more than one userbot, unfortunately.

El'endia: ever considered adding more than one userbot ;)

```
function KamikazePlus_setup(team) {
  // Typical setup. Nothing to see here. ;)
  var botVars = {};
  botVars["color"] = team;
  return botVars;
}

function KamikazePlus_getActions(gameInfo, botVars) {
    var actions = [];
    var us, them, red = {
            rotation: gameInfo.red_rot,
            x: gameInfo.red_x,
            y: gameInfo.red_y,
            alive: gameInfo.blue_alive
        },
        blue = {
            rotation: gameInfo.blue_rot,
            x: gameInfo.blue_x,
            y: gameInfo.blue_y,
            alive: gameInfo.blue_alive
        };
    if (botVars.color == "red") {
        us = red;
        them = blue;
    } else if (botVars.color == "blue") {
        us = blue;
        them = red;
    }

    function distance(x1, y1, x2, y2) {
        return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
    }

    // Get our ship's position
    var rotation, x, y, opponentAlive;
    if (botVars.color == "red") {
        rotation = gameInfo.red_rot;
        x = gameInfo.red_x;
        y = gameInfo.red_y;
        opponentAlive = gameInfo.blue_alive;
    } else if (botVars.color == "blue") {
        rotation = gameInfo.blue_rot;
        x = gameInfo.blue_x;
        y = gameInfo.blue_y;
        opponentAlive = gameInfo.red_alive;
    }

    // Calculate our rotation compared to the sun in degrees
    var sunX = gameInfo.sun_x,
        sunY = gameInfo.sun_y,
        angle = Math.atan2(sunY - y, sunX - x) * 180 / Math.PI,
        rotationToSun = (rotation - angle + 360) % 360;

    // Check if we need to hyperspace to avoid the sun
    var rX = x - sunX,
        rY = y - sunY,
        distanceFromSun = Math.sqrt(rX * rX + rY * rY) - gameInfo.sun_r;
    if (distanceFromSun < 30) {
        actions.push("hyperspace");
        console.log("Command Module is Hyperspacing.")
    }
    if (gameInfo[botVars["color"] + "_alive"]) {
        var angle = Math.degrees(Math.atan2(them.y - us.y, them.x - us.x)),
            rotationToOpponent = (us.rotation - angle + 360) % 360;
        if (rotationToOpponent > 90 && rotationToOpponent < 270) {
            actions.push("turn left");
        } else {
            actions.push("turn right");
        };
        actions.push("fire engine");
    }
    return actions;
}

```

Just took Kamikaze+'s code and got rid of the missile firing part.
> 1 votes

# Answer
# MissilesPlusScore

Some strange idea I came up with that takes that the absolute value of difference of the scores and uses a list of moves in a random based of the game way. It works well against bots with a strategy but fails against storms of missiles. Also my first .

```
function MissilesPlusScore__setup(team) {
var botVars = {};
botVars["color"] = team;
return botVars;
}
function MissilesPlusScore_getActions(gameInfo, botVars) {
var actions = [];
var moves=["fire missile","hyperspace","turn right","turn left","fire engine","fire missile","turn right","hyperspace","turn left","fire missile","hyperspace","turn right","turn left","hyperspace","fire engine","fire missile","turn right","turn left","hyperspace","fire missile","turn right","turn left","fire engine","hyperspace","fire missile","turn right","turn left","hyperspace"];
if(gameInfo[botVars["color"]+"_alive"]){
var num=gameInfo["redScore"]-gameInfo["blueScore"];
if(num<0){num=num*-1;}
if(num===0){actions.push(moves[Math.round(Math.random()*4)]);}
else{
actions.push(moves[num+gameInfo["numMissiles"]]);
}
}
    return actions;
}

```

# HYPER

HYPERSPACE IS COOL!!!!!!!!!!!!!!!!

```
function HYPER_setup(team){var botVars={};botVars["color"]=team;return botVars}function HYPER_getActions(gameInfo,botVars){var actions=[];if(gameInfo[botVars["color"]+"_alive"]){actions.push(["fire engine","fire missile","hyperspace"][Math.round(Math.random()*2)])};return actions}

```

# CoordinateInfluence

Based off the Coordinates, surprisingly effective:

```
function CoordinateInfluence_setup(team) {
var botVars = {};
botVars["color"] = team;
return botVars;
}
function CoordinateInfluence_getActions(gameInfo, botVars) {
var actions = [];
if (gameInfo[botVars["color"]+"_alive"]) {
if(gameInfo["blue_x"]>gameInfo["red_x"]){
if(gameInfo["blue_y"]<gameInfo["red_y"]){actions.push("turn right");}
else{actions.push("fire engine");}
}
else if(gameInfo["blue_y"]<gameInfo["red_y"]){
if(gameInfo["blue_x"]>gameInfo["red_x"]){actions.push("turn left");}
else{actions.push("fire missile");}
}
else{actions.push("hyperspace");}
}
return actions;
}

```
> 0 votes

# Answer
# SetCourseFor30Degrees

No idea why the captain is so insistent on setting the ship on a course of 30 degrees, but hey, as a lowly ensign, who are you to question? At least you have been given permission to avoid the sun! And you are allowed to fire the missiles... just not allowed to aim them...

```
function SetCourseFor30Degrees_setup(team)
{
  var botVars = {};
  botVars["color"] = team;
  return botVars;
}

function SetCourseFor30Degrees_getActions(gameInfo, botVars)
{
var actions = [];
var ang1 = gameInfo[botVars["color"]+"_rot"]+0;
var fireChance=0.95;
// sun avoidance
   var x = gameInfo[botVars["color"]+"_x"];
   var y = gameInfo[botVars["color"]+"_y"];
   var sunX = gameInfo["sun_x"]+0;
   var sunY = gameInfo["sun_y"]+0;
  var dx = sunX- x;
   var dy = sunY - y;
var shortRangeAvoidanceDistance = (dx * dx + dy * dy ) ;

 x = gameInfo[botVars["color"]+"_x"]+gameInfo[botVars["color"]+"_xv"]*10;
 y = gameInfo[botVars["color"]+"_y"]+gameInfo[botVars["color"]+"_yv"]*10;
 dx = sunX- x;
 dy = sunY - y;

var longRangeAvoidanceDistance = (dx * dx + dy * dy ) ;

var vel = Math.sqrt(gameInfo[botVars["color"]+"_xv"]*gameInfo[botVars["color"]+"_xv"]+
gameInfo[botVars["color"]+"_yv"]*gameInfo[botVars["color"]+"_yv"]);

var close=vel*1.5;

if (shortRangeAvoidanceDistance <= close* close)
{
  actions.push("hyperspace");
}
else
{
   if (longRangeAvoidanceDistance <= 200*200)
   {

     x = x+Math.cos((ang1-5)*Math.PI/180)*vel ;
     y = y+Math.sin((ang1-5)*Math.PI/180)*vel ;
     dx = sunX- x;
     dy = sunY - y;
     if (( dx * dx + dy * dy ) > longRangeAvoidanceDistance  )
     {
       actions.push("turn right")
     }
     else
     {
        actions.push("turn left")
     }
  }
  else
  {
    var course = botVars["color"]=="red"?30:-30;
    if (ang1>course ) {actions.push("turn left")}
    if (ang1<course ) {actions.push("turn right")}
  }
  if (Math.random() > fireChance){ actions.push("fire missile") }
  actions.push("fire engine")
}
return actions;
}

```
> 0 votes

# Answer
## Arrow

Simply chase his enemy, hyperspace when he is in danger and idle when his enemy is dead.

```
function Arrow_setup(team) {
    var botVars = {};
    botVars['mpref'] = team + '_';
    botVars['epref'] = team == 'red' ? 'blue_' : 'red_';
    return botVars;
}

function Arrow_getActions(gameInfo, botVars) {
    var actions = [];
    var x = gameInfo[botVars['mpref'] + 'x'],
        y = gameInfo[botVars['mpref'] + 'y'],
        rot = gameInfo[botVars['mpref'] + 'rot']; // My position and rotation
    var ex = gameInfo[botVars['epref'] + 'x'],
        ey = gameInfo[botVars['epref'] + 'y']; // Enemy position
    var Dsunx = Math.abs(x - gameInfo.sun_x);
    var Dsuny = Math.abs(y - gameInfo.sun_y);
    if (Dsunx < 30 && Dsuny < 30) // If Arrow is too close from sun, hyperspace !
        return ['hyperspace'];
    var missiles = gameInfo.missiles;
    for (var i = 0; i < missiles.length; i++) {
        var dx = Math.abs(x - missiles[i].x);
        var dy = Math.abs(y - missiles[i].y);
        if (dx < 10 && dy < 10)
            return ['hyperspace'];
    }
    if (gameInfo[botVars['epref'] + 'alive']) {
        var angle = Math.degrees(Math.atan2(ey - y, ex - x)),
            nrot = (rot - angle + 360) % 360;
        if (nrot > 90 && nrot < 270)
            actions.push('turn left');
        else
            actions.push('turn right');
        if (Math.random() > 0.5) actions.push('fire missile');
    }
    if (Math.random() > 0.5) actions.push('fire engine');
    return actions;
}

```
> 0 votes

# Answer
# Kamikaze+

**Not designed to be competitive.** Just for fun. Technically, it does the opposite of Spy: chase the player, hyperspace when close to the sun, fire missile 70% of the time. I sorta just want to see KamikazePlus chasing Spy and Spy running away like a madman.

```
function KamikazePlus_setup(team) {
  // Typical setup. Nothing to see here. ;)
  var botVars = {};
  botVars["color"] = team;
  return botVars;
}

function KamikazePlus_getActions(gameInfo, botVars) {
    var actions = [];
    var us, them, red = {
            rotation: gameInfo.red_rot,
            x: gameInfo.red_x,
            y: gameInfo.red_y,
            alive: gameInfo.blue_alive
        },
        blue = {
            rotation: gameInfo.blue_rot,
            x: gameInfo.blue_x,
            y: gameInfo.blue_y,
            alive: gameInfo.blue_alive
        };
    if (botVars.color == "red") {
        us = red;
        them = blue;
    } else if (botVars.color == "blue") {
        us = blue;
        them = red;
    }

    function distance(x1, y1, x2, y2) {
        return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
    }

    // Get our ship's position
    var rotation, x, y, opponentAlive;
    if (botVars.color == "red") {
        rotation = gameInfo.red_rot;
        x = gameInfo.red_x;
        y = gameInfo.red_y;
        opponentAlive = gameInfo.blue_alive;
    } else if (botVars.color == "blue") {
        rotation = gameInfo.blue_rot;
        x = gameInfo.blue_x;
        y = gameInfo.blue_y;
        opponentAlive = gameInfo.red_alive;
    }

    // Calculate our rotation compared to the sun in degrees
    var sunX = gameInfo.sun_x,
        sunY = gameInfo.sun_y,
        angle = Math.atan2(sunY - y, sunX - x) * 180 / Math.PI,
        rotationToSun = (rotation - angle + 360) % 360;

    // Check if we need to hyperspace to avoid the sun
    var rX = x - sunX,
        rY = y - sunY,
        distanceFromSun = Math.sqrt(rX * rX + rY * rY) - gameInfo.sun_r;
    if (distanceFromSun < 30) {
        actions.push("hyperspace");
        console.log("Command Module is Hyperspacing.")
    }
    if (gameInfo[botVars["color"] + "_alive"]) {
        var angle = Math.degrees(Math.atan2(them.y - us.y, them.x - us.x)),
            rotationToOpponent = (us.rotation - angle + 360) % 360;
        if (rotationToOpponent > 90 && rotationToOpponent < 270) {
            actions.push("turn left");
        } else {
            actions.push("turn right");
        };
        actions.push("fire engine");
        if (Math.random() > 0.3) {
            actions.push("fire missile")
        }

    }
    return actions;
}

```

Basically just took Spy's code and flipped "left" and "right".
> 0 votes

---
Tags: king-of-the-hill, javascript
---


title: Thwart LZMA2 compression

text:
# Question
Title: Thwart LZMA2 compression
## Goal

Create a program or pair of programs that collectively disrupt and fix files with the intent of preventing LZMA2 from working effectively. The disrupt and fix routines must be reciprocal, so you can recover the original file exactly.

## Targets

## Compression Methods

* Ubuntu/related: `xz -kz5 <infile>`
* Windows: `7z.exe a -txz -mx5 <outfile> <infile>`
* Other: Use a LZMA2 compressor with compression level 5 that compresses the works of Shakespeare to 1570550 bytes ± 100 bytes.

## Scoring; sum of (everything is in bytes, `ls -l` or `dir` it):

* Program(s) size (whatever it takes collectively to reversibly "break"/fix the file)
* Difference in size (absolute) between:
    + Raw collected works of Shakespeare and your modified (uncompressed) copy.
    + Raw photo and your modified (uncompressed) copy.
* Difference in size or 0, whichever is greater between:
    + Raw collected works of Shakespeare minus your modified, LZMA2 compressed copy.
    + Raw photo minus your modified, LZMA2 compressed copy.

## Example

Poorly scoring, lazily-golfed, but compliant Python 2.x example:

```
import sys
x = 7919 if sys.argv[1] == 'b' else -7919
i = bytearray(open(sys.argv[2], 'rb').read())
for n in range(len(i)):
    i[n] = (i[n] + x*n) % 256
o = open(sys.argv[2]+'~', 'wb').write(i)

```

Running...

```
$ python break.py b pg100.txt
$ python break.py f pg100.txt~
$ diff -s pg100.txt pg100.txt~~
Files pg100.txt and pg100.txt~~ are identical
$ python break.py b Glühwendel_brennt_durch.jpg
$ python break.py f Glühwendel_brennt_durch.jpg~
$ diff -s Glühwendel_brennt_durch.jpg Glühwendel_brennt_durch.jpg~~
Files Glühwendel_brennt_durch.jpg and Glühwendel_brennt_durch.jpg~~ are identical
$ xz -kz5 pg100.txt~
$ xz -kz5 Glühwendel_brennt_durch.jpg~
$ ls -ln
-rw-rw-r-- 1 2092 2092     194 May 23 17:37 break.py
-rw-rw-r-- 1 2092 2092 1659874 May 23 16:20 Glühwendel_brennt_durch.jpg
-rw-rw-r-- 1 2092 2092 1659874 May 23 17:39 Glühwendel_brennt_durch.jpg~
-rw-rw-r-- 1 2092 2092 1659874 May 23 17:39 Glühwendel_brennt_durch.jpg~~
-rw-rw-r-- 1 2092 2092 1646556 May 23 17:39 Glühwendel_brennt_durch.jpg~.xz
-rw-rw-r-- 1 2092 2092 5589891 May 23 17:24 pg100.txt
-rw-rw-r-- 1 2092 2092 5589891 May 23 17:39 pg100.txt~
-rw-rw-r-- 1 2092 2092 5589891 May 23 17:39 pg100.txt~~
-rw-rw-r-- 1 2092 2092 3014136 May 23 17:39 pg100.txt~.xz

```

Score

* = 194 + *abs*(5589891 − 5589891) + *max*(5589891 − 3014136, 0) + *abs*(1659874 − 1659874) + *max*(1659874 − 1646556, 0)
* = 194 + 0 + 2575755 + 0 + 13318
* **2,589,267 bytes.** Bad, but doing nothing to the files yields a score of 4,635,153 bytes.

> ## Clarification
>
> This is golf, so you are trying to *minimize* your score. I'm not sure if the comments are point out a legitimate hole in my scoring or if they are because I made it too complicated. In any case, you want the **SMALLEST**:
>
> * source code
> * difference between the uncompressed modified file and original file (e.g. if you modify it by appending a trillion 0's on the end, your score just went up a trillion bytes)
> * difference between the compressed modified file and original file (e.g. the more incompressible the files become, the higher your score). A perfectly incompressible file that grows slightly or not at all will score 0.

# Answer
> 8 votes
## Python, score = 120

```
import sys,hashlib
i=0
for c in sys.stdin.read():sys.stdout.write(chr(ord(c)^ord(hashlib.md5(str(i)).digest()[0])));i+=1

```

Makes a one-time pad using md5 in counter mode. xors the file with it. This has the advantage that the original and disrupted files are the same size, and that the disruptor and fixer are the same program.

The compressed disrupted files are larger than the originals.

# Answer
> 8 votes
# C, 51=51+0+0+0+0

```
main(c){for(;c=~getchar();putchar(~c^rand()>>23));}

```

Under the golf tricks, this program loops for each byte in standard input, and does exclusive-or with an infinite pad from rand(). I tested this with rand() in libc of OpenBSD 5.5.

Usage:

```
./scramble <orig >scrambled
./scramble <scrambled >orig.copy

```

To test my program, I wrote a shell script *test.sh* (57 lines) to compile my program and calculate my score.

```
$ sh test.sh
[1/4] Compiling scramble...
/tmp//ccbcB43x.o(.text+0x6): In function `main':
: warning: rand() isn't random; consider using arc4random()
[2/4] Scrambling files...
[3/4] Compressing scrambled files...
[4/4] Checking descrambler...
SCORE: 51=51+0+0+0+0
You may wish to rm -rf tmp.9Tjw89dgCs
$ ls -l tmp.9Tjw89dgCs/
total 43032
-rw-r--r--  1 kernigh  kernigh  1659874 May 28 17:23 filament.jpg.cp
-rw-r--r--  1 kernigh  kernigh  1659874 May 28 17:23 filament.jpg.sc
-rw-r--r--  1 kernigh  kernigh  1660016 May 28 17:23 filament.jpg.sc.xz
-rw-r--r--  1 kernigh  kernigh  5589891 May 28 17:23 pg100.txt.cp
-rw-r--r--  1 kernigh  kernigh  5589891 May 28 17:23 pg100.txt.sc
-rw-r--r--  1 kernigh  kernigh  5590232 May 28 17:23 pg100.txt.sc.xz
-rwxr-xr-x  1 kernigh  kernigh     8564 May 28 17:23 scramble

```

## Notes about rand() and the right shift

Any compression algorithm can't compress random data. I can disguise *pg100.txt* and *filament.jpg* as random data if I scramble them with a stream cipher.

My first idea was to exclusive-or *plaintext* with *pad* to make *ciphertext*, then store both *ciphertext* and *pad* in the scrambled file. This would increase the size of the file, and increase my score. The obvious choice is to use the same *pad* for every file, and store only *ciphertext* in the scrambled file. If I just call rand(), it uses a default seed of 1 and makes the same *pad* every time.

OpenBSD 5.5 defines rand() in stdlib.h and rand.c:

```
/* from stdlib.h */
#define RAND_MAX    0x7fffffff

/* from rand.c */
static u_int next = 1;

int
rand_r(u_int *seed)
{
    *seed = *seed * 1103515245 + 12345;
    return (*seed % ((u_int)RAND_MAX + 1));
}

int
rand(void)
{
    return (rand_r(&next));
}

```

This is a linear congruential generator. The big flaw is that low bits have short periods. The 1st bit has a period of 2: if you flip a coin with `rand()&1`, it would go heads, tails, heads, tails, and so on. The nth bit has a period of 2n. There are 31 bits, so the whole sequence has a period of 231.

LZMA2 can find patterns in short periods and compress them. The shortest code `~c^rand()` takes the low 8 bits and does not prevent compression. The right shift in `~c^rand()>>9` helps, but not enough. I use `~c^rand()>>23`.

* `~c` SCORE: 4227957=40+0+0+4019391+208526
* `~c^rand()` SCORE: 2474616=47+0+0+2463735+10834
* `~c^rand()>>9` SCORE: 350717=50+0+0+350667+0
* `~c^rand()>>23` SCORE: 51=51+0+0+0+0

# Answer
> 5 votes
# BrainFuck: 129 (129+0+0+0+0)\*

random.bf (linefeeds added for readability)

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

```

To create `unrandom.bf` you need to change the last + in the second line.

Most of the code is based on Daniel B Cristofani's Rule30 based random number generator adapted to add the number to each input and to terminate when there is no more input.

\*I've tested the bytes it has processed so far 212992 (processed after 12 hours) and both files turns into a 213064 compressed file. I guess it might be done by the end of the week for know for sure but I don't want to wait with posting. I'll update the score if it's wrong, but keep the solution since Rule30 rocks!

Trivia: Rule 30 was discovered by Stephen Wolfram in 1983 and according to Wikipedia it's used to produce random integers in Mathematica.

**Compilation and running:**

It uses exponential time and space (iterates over 32 more cells per char processed) so it requires a BrainFuck runtime that has at least 178,876,517 cells to encode the Shakespear file, do not treat non ascii as unicode, has wider than 8 bits cells and uses -1 as eof (to differ between 255 and -1). I usually use others peoples interpreters but this time I need to be a plug and promote my own:

```
jitbf --eof -1 -b 16 -c 200000000 random.bf < pg100.txt > pg100.txt.ran
jitbf --eof -1 -b 16 -c 200000000 random.bf < Glühwendel_brennt_durch.jpg > Glühwendel_brennt_durch.jpg.ran

```

jitfb compiles BrainFuck to optimized C and abuses perl Inline::C to run it. It's bundles with my Extended BrainFuck compiler. With the cell size and width in the argument it will allocate about 400MB.

# Answer
> 3 votes
# CJam, 22 bytes

```
G,~q{5$H$+255%_@^o}/];

```

This uses a lagged Fibonacci generator with recurrence relation **sn = (sn-5 \+ sn-16) % 255** (which I selected by mistake, but it works nevertheless) and a trivial seed to generate a pseudo-random stream of bytes, which it then XORs with the input.

I've tested my code with CJam 0.6, which was published on May 1, 2014.

### How it works

```
G,~                    e# Dump 0, 1, ... and 15 on the stack.
   q                   e# Read from STDIN.
    {             }/   e# For each character in the input.
     5$H$              e# Copy the sixth and 19th element from the stack.
         +255%         e# Push their sum modulo 255.
              _@       e# Duplicate and rotate the character on top.
                ^o     e# XOR and print.
                    ]; e# Clear the stack.

```

### Score

```
$ LANG=en_US
$ alias cjam='java -jar /usr/local/share/cjam/cjam-0.6.jar'
$ cjam thwart.cjam < pg100.txt > pg100.txt~
$ cjam thwart.cjam < pg100.txt~ > pg100.txt~~
$ diff -s pg100.txt pg100.txt~~
Files pg100.txt and pg100.txt~~ are identical
$ cjam thwart.cjam < Gluehwendel_brennt_durch.jpg > Gluehwendel_brennt_durch.jpg~
$ cjam thwart.cjam < Gluehwendel_brennt_durch.jpg~ > Gluehwendel_brennt_durch.jpg~~
$ diff -s Gluehwendel_brennt_durch.jpg Gluehwendel_brennt_durch.jpg~~
Files Gluehwendel_brennt_durch.jpg and Gluehwendel_brennt_durch.jpg~~ are identical
$ xz -kz5 pg100.txt~ Gluehwendel_brennt_durch.jpg~
$ wc -c thwart.cjam pg100.txt* Gluehwendel_brennt_durch.jpg*
      22 thwart.cjam
 5589889 pg100.txt
 5589889 pg100.txt~
 5589889 pg100.txt~~
 5590232 pg100.txt~.xz
 1659874 Gluehwendel_brennt_durch.jpg
 1659874 Gluehwendel_brennt_durch.jpg~
 1659874 Gluehwendel_brennt_durch.jpg~~
 1660016 Gluehwendel_brennt_durch.jpg~.xz
28999559 total

```

# Answer
> 2 votes
# shell script, 203

```
id|gpg --batch --passphrase-fd 0 --personal-compress-preferences Uncompressed $1 $2

```

Running it:

```
% sh break.sh -c pg100.txt
% sh break.sh -d pg100.txt.gpg > pg100.txt-original
gpg: CAST5 encrypted data
gpg: encrypted with 1 passphrase
gpg: WARNING: message was not integrity protected
% diff -s pg100.txt pg100.txt-original
Files pg100.txt and pg100.txt-original are identical
% sh break.sh -c Glühwendel_brennt_durch.jpg
% sh break.sh -d Glühwendel_brennt_durch.jpg.gpg > Glühwendel_brennt_durch.jpg-original
gpg: CAST5 encrypted data
gpg: encrypted with 1 passphrase
gpg: WARNING: message was not integrity protected
% diff -s Glühwendel_brennt_durch.jpg Glühwendel_brennt_durch.jpg-original
Files Glühwendel_brennt_durch.jpg and Glühwendel_brennt_durch.jpg-original are identical
% xz -kz5 Glühwendel_brennt_durch.jpg.gpg
% xz -kz5 pg100.txt.gpg
% ls -ln
total 28340
-rw-r--r-- 1 1000 1000      84 May 24 04:33 break.sh
-rw-r--r-- 1 1000 1000 1659874 Jan 19 17:22 Glühwendel_brennt_durch.jpg
-rw-r--r-- 1 1000 1000 1659943 May 24 04:46 Glühwendel_brennt_durch.jpg.gpg
-rw-r--r-- 1 1000 1000 1660084 May 24 04:46 Glühwendel_brennt_durch.jpg.gpg.xz
-rw-r--r-- 1 1000 1000 1659874 May 24 04:46 Glühwendel_brennt_durch.jpg-original
-rw-r--r-- 1 1000 1000 5589891 May 24 03:55 pg100.txt
-rw-r--r-- 1 1000 1000 5589941 May 24 04:43 pg100.txt.gpg
-rw-r--r-- 1 1000 1000 5590284 May 24 04:43 pg100.txt.gpg.xz
-rw-r--r-- 1 1000 1000 5589891 May 24 04:43 pg100.txt-original

```

Not very portable, but could be made at the cost of a couple of bytes. Requires PGP (an implementation with OpenSSL would be possible, too). The ~50 byte difference between encoded file and original can probably be saved.

**Scoring:**

84 + abs(1659874 - 1659943) + max(1659874 - 1660084, 0) + abs(5589891 - 5589941) + max(5589891 - 5590284, 0) = **203**

# Answer
> 2 votes
# PHP, 117 + 0 + 0 + 0 + 0 = 117

Because would you really entrust the task of mangling your data beyond recognition to any other language?

```
<?=substr(gmp_export(gmp_invert(2*gmp_import($s=stream_get_contents(STDIN))+1,$m=2*gmp_pow(256,strlen($s)))/2+$m),1);

```

While all the other solutions are based on “secure” constructions like “random number generators” or “military-grade cryptography”, this one simply interprets strings as representing odd numbers modulo 2⋅256^length, and computes their modular inverse.

Demo:

```
$ php thwart.php < 100.txt.utf-8 > 100.txt.utf-8~
$ php thwart.php < 100.txt.utf-8~ > 100.txt.utf-8~~
$ diff -s 100.txt.utf-8 100.txt.utf-8~~
Files 100.txt.utf-8 and 100.txt.utf-8~~ are identical
$ php thwart.php < Glühwendel_brennt_durch.jpg > Glühwendel_brennt_durch.jpg~
$ php thwart.php < Glühwendel_brennt_durch.jpg~ > Glühwendel_brennt_durch.jpg~~
$ diff -s Glühwendel_brennt_durch.jpg Glühwendel_brennt_durch.jpg~~
Files Glühwendel_brennt_durch.jpg and Glühwendel_brennt_durch.jpg~~ are identical
$ xz -kz5 100.txt.utf-8~ Glühwendel_brennt_durch.jpg~
$ wc -c *
 5589889 100.txt.utf-8
 5589889 100.txt.utf-8~
 5590232 100.txt.utf-8~.xz
 5589889 100.txt.utf-8~~
 1659874 Glühwendel_brennt_durch.jpg
 1659874 Glühwendel_brennt_durch.jpg~
 1660016 Glühwendel_brennt_durch.jpg~.xz
 1659874 Glühwendel_brennt_durch.jpg~~
     117 thwart.php
28999654 total

```

# Answer
> 1 votes
# Python, score=183+7+6+0+0=196

The scoring penalizes you for making the file completely uncompressible, since then the compressed file is larger from the compression overhead. Thus my program makes them slightly less than totally uncompressible:

```
import sys
from random import randint as J,seed
x=sys.stdin.read()
seed(ord(x[1]))
n=int(2362*J(1,2)**2.359)
sys.stdout.write(x[:n]+''.join(chr(ord(c)^J(0,255))for c in x[n:]))

```

Result:

```
Laxori@Laxori-PC /cygdrive/f/Programming/lzkill
$ cat photo.jpg | python break.py > photo.jpg~; cat photo.jpg~ | python break.py > photo.jpg~~; diff photo.jpg photo.jpg~~; xz -kz5 photo.jpg~

Laxori@Laxori-PC /cygdrive/f/Programming/lzkill
$ cat pg100.txt | python break.py > pg100.txt~; cat pg100.txt~ | python break.py > pg100.txt~~; diff pg100.txt pg100.txt~~; xz -kz5 pg100.txt~

Laxori@Laxori-PC /cygdrive/f/Programming/lzkill
$ ls -l
total 28337
----------+ 1 Laxori mkpasswd     183 2014-05-24 13:43 break.py
----------+ 1 Laxori mkpasswd 5589891 2014-05-23 19:19 pg100.txt
-rw-r--r--+ 1 Laxori mkpasswd 5589891 2014-05-24 13:45 pg100.txt~
-rw-r--r--+ 1 Laxori mkpasswd 5589884 2014-05-24 13:45 pg100.txt~.xz
-rw-r--r--+ 1 Laxori mkpasswd 5589891 2014-05-24 13:45 pg100.txt~~
----------+ 1 Laxori mkpasswd 1659874 2014-05-23 19:19 photo.jpg
-rw-r--r--+ 1 Laxori mkpasswd 1659874 2014-05-24 13:44 photo.jpg~
-rw-r--r--+ 1 Laxori mkpasswd 1659880 2014-05-24 13:44 photo.jpg~.xz
-rw-r--r--+ 1 Laxori mkpasswd 1659874 2014-05-24 13:44 photo.jpg~~

Laxori@Laxori-PC /cygdrive/f/Programming/lzkill
$ python
Python 2.5.2 (r252:60911, Dec  2 2008, 09:26:14)
[GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 183 + abs(5589891-5589884) + abs(1659874-1659880)
196

```

---
Tags: code-challenge, compression
---


title: Calculate the correlation coefficient

text:
# Question
Title: Calculate the correlation coefficient
Given a series of numbers for events X and Y, calculate Pearson's correlation coefficient. The probability of each event is equal, so expected values can be calculated by simply summing each series and dividing by the number of trials.

## Input

```
1   6.86
2   5.92
3   6.08
4   8.34
5   8.7
6   8.16
7   8.22
8   7.68
9   12.04
10  8.6
11  10.96

```

## Output

```
0.769

```

Shortest code wins. Input can be by stdin or arg. Output will be by stdout.

Edit: Builtin functions should not be allowed (ie calculated expected value, variance, deviation, etc) to allow more diversity in solutions. However, feel free to demonstrate a language that is well suited for the task using builtins (for exhibition).

Based on David's idea for input for Mathematica (86 char using builtin mean)

```
m=Mean;x=d[[All,1]];y=d[[All,2]];(m@(x*y)-m@x*m@y)/Sqrt[(m@(x^2)-m@x^2)(m@(y^2)-m@y^2)]

m = Mean;
x = d[[All,1]];
y = d[[All,2]];
(m@(x*y) - m@x*m@y)/((m@(x^2) - m@x^2)(m@(y^2) - m@y^2))^.5

```

Skirting by using our own mean (101 char)

```
m=Total[#]/Length[#]&;x=d[[All,1]];y=d[[All,2]];(m@(x*y)-m@x*m@y)/((m@(x^2)-m@x^2)(m@(y^2)-m@y^2))^.5

m = Total[#]/Length[#]&;
x = d[[All,1]];
y = d[[All,2]];
(m@(x*y)-m@x*m@y)/((m@(x^2)-m@x^2)(m@(y^2)-m@y^2))^.5

```

# Answer
## PHP 144 bytes

```
<?
for(;fscanf(STDIN,'%f%f',$$n,${-$n});$f+=${-$n++})$e+=$$n;
for(;$$i;$z+=$$i*$a=${-$i++}-=$f/$n,$y+=$a*$a)$x+=$$i*$$i-=$e/$n;
echo$z/sqrt($x*$y);

```

Takes the input from STDIN, in the format provided in the original post. Result:

> 0.76909044055492

Using the vector dot product:

where are the input vectors adjusted downwards by and respectively.

## Perl 112 bytes

```
/ /,$e+=$`,$f+=$',@v=($',@v)for@u=<>;
$x+=($_-=$e/$.)*$_,$y+=($;=$f/$.-pop@v)*$;,$z-=$_*$;for@u;
print$z/sqrt$x*$y

```

> 0.76909044055492

Same alg, different language. In both cases, new lines have been added for 'readability', and are not required. The only notable difference in length is the first line: the parsing of input.
> 3 votes

# Answer
# Mathematica 34 bytes

Here are a few ways to obtain the Pearson product moment correlation. They all produce the same result. From Dr. belisarius: 34 bytes

```
Dot@@Normalize/@(#-Mean@#&)/@{x,y}

```

---

**Built-in Correlation function I**: 15 chars

This assumes that `x` and `y` are lists corresponding to each variable.

```
x~Correlation~y

```

> 0.76909

---

**Built-in Correlation function II**: 31 chars

This assumes d is a list of ordered pairs.

```
d[[;;,1]]~Correlation~d[[;;,2]]

```

> 0.76909

The use of `;;` for `All` thanks to A Simmons.

---

**Relying on the Standard Deviation function**: ~~118~~ 115 chars

The correlation can be determined by:

```
s=StandardDeviation;
m=Mean;
n=Length@d;
x=d[[;;,1]];
y=d[[;;,2]];
Sum[((x[[i]]-m@x)/s@x)((y[[i]]-m@y)/s@y),{i,n}]/(n-1)

```

> 0.76909

---

**Hand-rolled Correlation**: 119 chars

Assuming `x` and `y` are lists...

```
s=Sum;n=Length@d;m@p_:=Tr@p/n;
(s[(x[[i]]-m@x)(y[[i]]-m@y),{i,n}]/Sqrt@(s[(x[[i]]-m@x)^2,{i,n}] s[(y[[i]] - m@y)^2,{i,n}]))

```

> 0.76909
> 5 votes

# Answer
# Q

Assuming builtins are allowed and x,y data are seperate vectors (7 chars):

```
x cor y

```

If data are stored as orderded pairs, as indicated by David Carraher, we get (for 12 characters):

```
{(cor).(+)x}

```
> 2 votes

# Answer
# MATLAB/Octave

For the purpose of demonstrating built-ins only:

```
octave:1> corr(X,Y)
ans =  0.76909
octave:2>

```
> 2 votes

# Answer
# J, ~~30~~ 27 bytes

```
([:+/*%*&(+/)&.:*:)&(-+/%#)

```

This time as a function taking two arguments. Uses the vector formula for calculating it.

## Usage

```
   f =: ([:+/*%*&(+/)&.:*:)&(-+/%#)
   (1 2 3 4 5 6 7 8 9 10 11) f (6.86 5.92 6.08 8.34 8.7 8.16 8.22 7.68 12.04 8.6 10.96)
0.76909

```

## Explanation

Takes two lists *a* and *b* as separate arguments.

```
([:+/*%*&(+/)&.:*:)&(-+/%#)  Input: a on LHS, b on RHS
                   &(     )  For a and b
                         #     Get the count
                      +/       Reduce using addition to get the sum
                        %      Divide the sum by the count to get the average
                     -         Subtract the initial value from the average
                             Now a and b have both been shifted by their average
                             For both a and b
                *:             Square each value
         (+/)&.:               Reduce the values using addition to get the sum
                               Apply in the inverse of squaring to take the square root
                               of the sum to get the norm
       *&                    Multiply norm(a) by norm(b)
     *                       Multiply a and b elementwise
      %                      Divide a*b by norm(a)*norm(b) elementwise
 [:+/                        Reduce using addition to the sum which is the
                             correlation coefficient and return it

```
> 2 votes

# Answer
## APL 57

Using the dot product approach:

```
a←1 2 3 4 5 6 7 8 9 10 11

b←6.86 5.92 6.08 8.34 8.7 8.16 8.22 7.68 12.04 8.6 10.96

(a+.×b)÷((+/(a←a-(+/a)÷⍴a)*2)*.5)×(+/(b←b-(+/b)÷⍴b)*2)*.5

0.7690904406

```
> 2 votes

# Answer
## Python 3, 140 bytes

```
E=lambda x:sum(x)/len(x)
S=lambda x:(sum((E(x)-X)**2for X in x)/len(x))**.5
lambda x,y:E([(X-E(x))*(Y-E(y))for X,Y in zip(x,y)])/S(x)/S(y)

```

2 helper functions (`E` and `S`, for expected value and standard deviation, respectively) are defined. Input is expected as 2 iterables (lists, tuples, etc). Try it online.
> 1 votes

# Answer
# Oracle SQL 11.2, 152 bytes (for exhibition)

```
SELECT CORR(a,b)FROM(SELECT REGEXP_SUBSTR(:1,'[^ ]+',1,2*LEVEL-1)a,REGEXP_SUBSTR(:1,'[^ ]+',1,2*LEVEL)b FROM DUAL CONNECT BY INSTR(:1,' ',2,LEVEL-1)>0);

```

Un-golfed

```
SELECT CORR(a,b)
FROM
(
  SELECT REGEXP_SUBSTR(:1, '[^ ]+', 1, 2*LEVEL-1)a, REGEXP_SUBSTR(:1, '[^ ]+', 1, 2*LEVEL)b
  FROM DUAL
  CONNECT BY INSTR(:1, ' ', 2, LEVEL - 1) > 0
)

```

Input string should use the same decimal separator as the database.
> 1 votes

# Answer
# Python 3 with SciPy, 52 bytes (for exhibition)

```
from scipy.stats import*
lambda x,y:pearsonr(x,y)[0]

```

An anonymous function that takes input of the two data sets as lists `x` and `y`, and returns the correlation coefficient.

**How it works**

There's not a lot going on here; SciPy has a builtin that returns both the coefficient and the p-value for testing non-correlation, so the function simply passes the data sets to this and returns the first element of the `(coefficient, p-value)` tuple returned by the builtin.

Try it on Ideone
> 1 votes

---
Tags: code-golf, statistics
---