title: Gilbreath's Conjecture

text:
# Question
Title: Gilbreath's Conjecture
Suppose we start with the infinite list of prime numbers:

```
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, ...

```

Then, we take the absolute differences between each pair of numbers, repeatedly:

```
[1, 2, 2, 4, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, ...
[1, 0, 2, 2, 2, 2, 2, 2, 4, 4, 2, 2, 2, 2, 0, 4, 4, 2, ...
[1, 2, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, 0, 2, 4, 0, 2, ...
[1, 2, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 2, 2, 4, 2, ...

```

Notice that the leading number is 1 every time. Gilbreath's Conjecture is the prediction that this continues to be the case forever.

The only way the leading number would stop being a 1 is if the next number after it was neither a 0 nor a 2. The only way the second number wouldn't be a 0 or a 2 is if the number after that was neither a 0 nor a 2. And so on.

The index of the earliest number, other than the leading 1, which is neither a 0 nor a 2, can never go down by more than 1 between a consecutive pair of sequences. This fact has been used to put a very strong lower bound on when, if ever, a sequence might not have a 1 as the first element.

In this challenge, you will be given the index of a sequence, and you must output the index of the first number in that sequence which is not the leading 1, and is not a 0 or a 2.

For instance, in the 4th absolute difference sequence above:

```
[1, 2, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 2, 2, 4, 2, ...

```

The first entry that's neither a zero or a two, other than the first entry, is the 15th position, 14 zero indexed. So if the input was 4, you would output 14.

For inputs from 1 to 30, the outputs should be:

`[3, 8, 14, 14, 25, 24, 23, 22, 25, 59, 98, 97, 98, 97, 174, 176, 176, 176, 176, 291, 290, 289, 740, 874, 873, 872, 873, 872, 871, 870]`

This is OEIS A000232.

This is assuming you have 1 indexed inputs and 0 indexed outputs. You may index your inputs and outputs starting at any constant integers, as long as you can accept the range of inputs corresponding to all sequences.

Requirements: Your solution must run in at most 1 minute on a input of up to 30. If it's close enough that it depends on the computer specs, it's allowed.

Shortest code wins.

# Answer
# Jelly, 17 bytes

```
ÆNạ2\Ḋ¿Ḣ’Ị
R‘ÇÐ¿L

```

Try it online!

Input is 2-indexing. Output is 1-indexing.

On TIO all testcases in total take 22.309 s.
> 1 votes

# Answer
# Mathematica, 66 bytes

```
(For[z=1,Last@Nest[Abs@*Differences,Array[Prime,z+#],#]<3,z++];z)&

```

Pure function taking a positive integer as argument and returning a 1-indexed integer. `Nest[Abs@*Differences,Array[Prime,z+#],#]` computes the `#`th iterated absolute difference list of the list of the first `z+#` primes. `For[z=1,Last@...<3,z++]` loops this computation until the last element of the resulting list is at least `3`, and then `z` is output. (Note that the correctness of the algorithm assumes Gilbreath's conjecture!)
> 4 votes

# Answer
# Pyth, 32 bytes

```
-l.W>3h.WtHaVZtZ>QH+ZfP_TheZ.fP_

```

Try it online!

Uses 2-indexing.
> 3 votes

# Answer
# MATL, 18 bytes

```
`@:YqG:"d|]3<A}@G-

```

Input and output are 1-based. It takes less than 40 seconds in TIO for each of the test cases.

Try it online!

### Explanation

This keeps trying longer initial sequences of primes until the iterated absolute consecutive differences give at least one value exceeding `2`.

```
`        % Do... while loop
  @:Yq   %   Array of first k primes, where k is iteration index
  G:"    %   Do this as many times as the input
    d|   %     Absolute value of consecutive differences
  ]      %   End
  3<A    %   Are they all less than 3? This is the loop condition
}        % Finally (execute before exiting loop)
  @G-    %   Push last iteration index minus input. This is the output
         % End (implicit). Continue with next iteration if top of stack is true
         % Display (implicit)

```
> 2 votes

# Answer
# Perl 6, ~~136~~ 120 bytes

```
{->\i,\n{i??&?BLOCK(i-1,lazy
n.rotor(2=>-1).map: {abs .[1]-.[0]})!!1+n.skip.first:
:k,none 0,2}($_,grep &is-prime,2..*)}

```

Ungolfed:

```
{   # Anonymous function with argument in $_
    sub f(\i, \n) {  # Recursive helper function
        if i != 0 {  # If we're not done,
            # Recurse on the absolute differences between adjacent entries:
            f(i - 1, lazy n.rotor(2 => -1).map: { abs .[1] - .[0] });
        } else {
            # Otherwise, return the first index after 0
            # where the value is neither 0 nor 2.
            1 + n.skip.first: :k, none 0, 2;
        }
    }
    # Call the helper function with the argument passed to the top-level
    # anonymous function (the recursion depth), and with the prime numbers
    # as the initial (infinite, lazy) list:
    f($_, grep &is-prime, 2 .. *);
}

```

With an input of 30, the function runs in about four seconds on my modest laptop.

...which becomes 1.4 seconds after upgrading my seven-month-old Perl 6 installation (which also gives me the `skip` method that lets me shave off several bytes from my first solution). All test cases from 1 to 30 take about ten seconds.
> 1 votes

# Answer
# Haskell, 94 bytes

```
f(a:b:r)=abs(a-b):f(b:r)
length.fst.span(<3).(iterate f[n|n<-[2..],all((>0).mod n)[2..n-1]]!!)

```

Try it online! The last line is an anonymous function. Bind to e.g. `g` and call like `g 4`. All test cases combined take less than 2 seconds on TIO.

### How it works

`[n|n<-[2..],all((>0).mod n)[2..n-1]]` generates an infinite list of primes.
`f(a:b:r)=abs(a-b):f(b:r)` is a function yielding the absolute differences of the elements of an infinite list. Given a number `n`, `(iterate f[n|n<-[2..],all((>0).mod n)[2..n-1]]!!)` applies `f` `n` times to the list of primes. `length.fst.span(<3)` computes the length of the prefix of the resulting list where the elements are smaller 3.
> 1 votes

# Answer
# Axiom, 289 bytes

```
g(n:PI):PI==(k:=n*10;c:List NNI:=[i for i in 1..(k quo 2)|prime?(i)];repeat(a:=concat(c,[i for i in (k quo 2+1)..k|prime?(i)]);j:=0;c:=a;repeat(j=n=>break;j:=j+1;b:=a;a:=[abs(b.(i+1)-b.i)for i in 1..(#b-1)]);j:=2;repeat(j>#a=>break;a.j~=2 and a.j~=1 and a.j~=0=>return j-1;j:=j+1);k:=k*2))

```

ungolf it and test

```
f(n:PI):PI==
  k:=n*10
  c:List NNI:=[i for i in 1..(k quo 2)|prime?(i)]
  repeat
    a:=concat(c,[i for i in (k quo 2+1)..k|prime?(i)])
    j:=0;c:=a
    repeat
       j=n=>break
       j:=j+1
       b:=a
       a:=[abs(b.(i+1)-b.i)  for i in 1..(#b-1)]
    j:=2
    repeat
       j>#a=>break
       a.j~=2 and a.j~=1 and a.j~=0 => return j-1
       j:=j+1
    k:=k*2

(4) -> [g(i)  for i in 1..30]
   (4)
   [3, 8, 14, 14, 25, 24, 23, 22, 25, 59, 98, 97, 98, 97, 174, 176, 176, 176,
    176, 291, 290, 289, 740, 874, 873, 872, 873, 872, 871, 870]

```

it if not find the solution expand the prime list of 2\*x in a loop and recompute all the remain lists. 3 seconds for find g(30)
> 0 votes

---
Tags: code-golf, sequence, number-theory
---


title: Name the Hadrons

text:
# Question
Title: Name the Hadrons
## Challenge

Given a quark composition of a particle as input, output the corresponding hadron's name.

Quarks will be represented by a capital letter and antiquarks by a lowercase letter.

The quarks may be in any order, not necessarily the order given below.

Built-in functions the access data about particles and/or quarks are disallowed.

The only quarks you will be given are U (up), u (antiup), D (down), d (antidown), S (strange), s (antistrange), C (charm), c (anticharm), B (bottom or beauty), b(antibottom or antibeauty).

## List of Hadrons and their quark compositions

Note that although there are various other hadrons such as pentaquarks and glueballs etc., you only need to support the hadrons given in the following lists

### Baryons (QQQ) and Antibaryons (qqq)

The names in brackets are alternative names for the particles. You may output either name.

```
Input - Output

UUU - delta++
uuu - antidelta++
UUD - delta+ (proton)
uud - antidelta+ (antiproton)
UDD - delta0 (neutron)
udd - antidelta0 (antineutron)
DDD - delta-
ddd - antidelta-
UUS - sigma+
uus - antisigma+
UDS - sigma0
uds - antisigma0
DDS - sigma-
dds - antisigma-
USS - xi0
uss - antixi0
DSS - xi-
dss - antixi-
SSS - omega-
sss - antiomega-

UUC - charmed sigma++
uuc - charmed antisigma++
UDC - charmed sigma+
udc - charmed antisigma+
DDC - charmed sigma0
ddc - charmed antisigma0
UUB - bottom sigma+
uub - bottom antisigma+
UDB - bottom sigma0
udb - bottom antisigma0
DDB - bottom sigma-
ddb - bottom antisigma-
USC - charmed xi+
usc - charmed antixi+
DSC - charmed xi0
dsc - charmed antixi0
UCC - double charmed xi++
ucc - double charmed antixi++
DCC - double charmed xi+
dcc - double charmed antixi+
USB - bottom xi0
usb - bottom antixi0
DSB - bottom xi-
dsb - bottom antixi-
UBB - double bottom xi0
ubb - double bottom antixi0
DBB - double bottom xi-
dbb - double bottom antixi-
UCB - charmed bottom xi+
ucb - charmed bottom antixi+
DCB - charmed bottom xi0
dcb - charmed bottom antixi0
SSC - charmed omega0
ssc - charmed antiomega0
SSB - bottom omega-
ssb - bottom antiomega-
SCC - double charmed omega+
scc - double charmed antiomega+
SCB - charmed bottom omega0
scb - charmed bottom antiomega0
SBB - double bottom omega-
sbb - double bottom antiomega-
CCB - double charmed bottom omega+
ccb - double charmed bottom antiomega+
CBB - charmed double bottom omega0
cbb - charmed double bottom antiomega0
CCC - triple charmed omega++
ccc - triple charmed antiomega++
BBB - triple bottom omega-
bbb - triple bottom antiomega-

```

### Mesons (Qq)

```
Input - Output

Ud - pion+
Uu - pion0
Dd - pion0
Du - pion-
Us - kaon+
Ds - kaon0
Sd - antikaon0
Su - kaon-
Ss - phion0
Cd - D meson+
Dc - D meson-
Cu - D meson0
Uc - antiD meson0
Cs - strange D meson+
Sc - strange D meson-
Cc - psion0
Bu - B meson-
Ub - B meson+
Db - B meson0
Bd - antiB meson0
Sb - strange B meson0
Bs - strange antiB meson0
Bb - upsilon0

```

## Winning

Shortest code in bytes wins.

# Answer
# SOGL 0.11, ~~341~~ ~~339~~ ~~333~~ ~~310~~ ~~305~~ ~~305~~ 300 bytes

```
‘θw±
on”≥
0c{≤
”=?"▒
on0”←"█
c SW?"▲
?ļ0←j ►
?"anti”o}▼
SD”;W¡+}□
=?ļ-←ļ+←■
‘B≤a=+}:?"⁽¬Τk⅜K±l?@+}ob@+o}▓
UCl2-? CA"K¼⁶▓ BA"δ╬▓cd≠▼≤: U=; D=++}"8}↕x╔:⁵F┘¹±o≤"B□"κ§)Ƨ7%s±p←"Ss▒phi█Cc▒psi█Bb▒upsil█SdUcBd”2n{=▼}≤"U□1>?▲ka≥pc DW►S■"pi≥Pcρ►D■▲)»β⁴‘o}ƧBs=▼ Dc BW?X B}" mes≥+p"D═S┐╔¬ν↑FνF⌠V3╗βstA\≈²‘:cW2+Wp

```
> 5 votes

# Answer
## JavaScript (ES6), ~~456~~ ~~448~~ ~~431~~ 420 bytes

This code is using only two small lookup tables:

* one to identify the quarks: 'CUBDScubds'
* another one to detect the 'anti' prefix of Mesons: 'SdUcBdBs'

Everything else is deduced from the quarks.

```
(s,[a,b]=[...s].map(c=>(i='CUBDScubds'.search(c)%5,m|=1<<i,j+=i<2,k+=i&1,p+=i?i-2?'':'bottom ':'charmed ',i),m=j=k=0,p=''))=>s[2]?p.replace(/(\w+) \1( \1)?/,(_,a,b)=>b?'triple'+b:'double '+a)+(s>'Z'?'anti':'')+['omega','xi','sigma','delta'][k]+('-0+'[j]||'++'):(m&16&&m&5?'strange ':'')+(~'SdUcBdBs'.search(s)?'anti':'')+(m&1?m^1?'D mes':'psi':m&4?m^4?'B mes':'upsil':m&16?m^16?'ka':'phi':'pi')+'on'+'-0+'[(a<2)-(b<2)+1]

```

```
let f =

(s,[a,b]=[...s].map(c=>(i='CUBDScubds'.search(c)%5,m|=1<<i,j+=i<2,k+=i&1,p+=i?i-2?'':'bottom ':'charmed ',i),m=j=k=0,p=''))=>s[2]?p.replace(/(\w+) \1( \1)?/,(_,a,b)=>b?'triple'+b:'double '+a)+(s>'Z'?'anti':'')+['omega','xi','sigma','delta'][k]+('-0+'[j]||'++'):(m&16&&m&5?'strange ':'')+(~'SdUcBdBs'.search(s)?'anti':'')+(m&1?m^1?'D mes':'psi':m&4?m^4?'B mes':'upsil':m&16?m^16?'ka':'phi':'pi')+'on'+'-0+'[(a<2)-(b<2)+1]

res = [
  "UUU", "uuu", "UUD", "uud", "UDD", "udd", "DDD", "ddd", "UUS", "uus", "UDS", "uds", "DDS", "dds", "USS", "uss",
  "DSS", "dss", "SSS", "sss", "UUC", "uuc", "UDC", "udc", "DDC", "ddc", "UUB", "uub", "UDB", "udb", "DDB", "ddb",
  "USC", "usc", "DSC", "dsc", "UCC", "ucc", "DCC", "dcc", "USB", "usb", "DSB", "dsb", "UBB", "ubb", "DBB", "dbb",
  "UCB", "ucb", "DCB", "dcb", "SSC", "ssc", "SSB", "ssb", "SCC", "scc", "SCB", "scb", "SBB", "sbb", "CCB", "ccb",
  "CBB", "cbb", "CCC", "ccc", "BBB", "bbb", "Ud",  "Uu",  "Dd",  "Du",  "Us",  "Ds",  "Sd",  "Su",  "Ss",  "Cd",
  "Dc",  "Cu",  "Uc",  "Cs",  "Sc",  "Cc",  "Bu",  "Ub",  "Db",  "Bd",  "Sb",  "Bs",  "Bb"
]
.map(s => s + ' - ' + f(s)).join("\n");

console.log(res);
```
> 12 votes

# Answer
# Perl 5, 318 bytes

```
$_=<>;$h=qw/- ++ + 0/[y/uc//*2*($i=3-map{${lc;}++}/./g)-$u-$c-$i];$a=($i?!$h&&/[dUB]/:/[a-z]/)&&anti;map{/(.)/;$q.=("","$_ ","double $_ ","triple $_ ")[$$1]}charmed,bottom;print(($i?($u+$d>1?pi:$s>1?phi:$c>1?psi:$b>1?upsil:$c+$b?($s?"strange $a":$a).($b?B:D).' mes':$a.ka).on:$q.$a.qw/omega xi sigma delta/[$u+$d]).$h)

```

Newlines added for readability (slightly):

```
$_=<>
$h=qw/- ++ + 0/[y/uc//*2*($i=3-map{${lc;}++}/./g)-$u-$c-$i]
$a=($i?!$h&&/[dUB]/:/[a-z]/)&&anti
map{/(.)/;$q.=("","$_ ","double $_ ","triple $_ ")[$$1]}charmed,bottom;
print(($i?($u+$d>1?pi:$s>1?phi:$c>1?psi:$b>1?upsil:$c+$b?($s?"strange $a":$a).($b?B:D).' mes':$a.ka).on:$q.$a.qw/omega xi sigma delta/[$u+$d]).$h)

```
> 2 votes

---
Tags: code-golf, kolmogorov-complexity, physics
---


# Question
Title: How many IP addresses are in a given range?
Inspired by...

> Networking - How can I work out how many IP addresses there are in a given range?

Write a program or function that takes two strings as input, each being an IPv4 address expressed in standard dotted notation and outputs or returns the number of IP addresses covered by this range, including the two IP addresses input.

* You must not use any external code, libraries or services designed to parse an IP address. (Other string processing standard library functions are acceptable.)
* All 2^32 IP addresses are equal. No distinction is made to broadcast, class E, etc.
* Normal code-golf rules apply.

For example:

```
"0.0.0.0","255.255.255.255" returns 4294967296.
"255.255.255.255","0.0.0.0" also returns 4294967296.
"1.2.3.4","1.2.3.4" returns 1.
"56.57.58.59","60.61.62.63" returns 67372037.
"1","2" is invalid input. Your code may do anything you like.

```

# Answer
# GolfScript, 20 bytes

```
~]7/${2%256base}/)\-

```

Try it online.

### Test cases

```
$ echo 0.0.0.0 255.255.255.255 | golfscript range.gs
4294967296
$ echo 255.255.255.255 0.0.0.0 | golfscript test.gs
4294967296
$ echo 1.2.3.4 1.2.3.4 | golfscript test.gs
1
$ echo 56.57.58.59 60.61.62.63 | golfscript test.gs
67372037

```

### How it works

```
~]        # Evaluate and collect into an array.
          #
          # “.” duplicates, so for "5.6.7.8 1.2.3.4", this leaves
          # [ 5 5 6 6 7 7 8 1 1 2 2 3 3 4 ] on the stack.
          #
7/        # Split into chunks of length 7: [ [ 5 5 6 6 7 7 8 ] [ 1 1 2 2 3 3 4 ] ]
$         # Sort the array of arrays: [ [ 1 1 2 2 3 3 4 ] [ 5 5 6 6 7 7 8 ] ]
{         # For each array:
  2%      # Extract every second element. Example: [ 1 2 3 4 ]
  256base # Convert the IP into an integer by considering it a base 256 number.
}/        #
)         # Add 1 to the second integer.
\-        # Swap and subtract. Since the integers were sorted, the result is positive.

```
> 21 votes

# Answer
# Python 2 - 106

See it here.

```
def a():x=map(int,raw_input().split("."));return x[0]*2**24+x[1]*2**16+x[2]*2**8+x[3]
print abs(a()-a())+1

```

**Example Input**

> 0.0.0.0
> 0.0.0.255

**Example Output**

> 256
> 10 votes

# Answer
# CJam - 15

```
{r'./256b}2*-z)

```

Try it at http://cjam.aditsu.net/

Thanks Dennis, wow, I don't know how to get the best out of my own language :p
> 8 votes

# Answer
# Pure bash, 66 bytes

```
p()(printf %02x ${1//./ })
r=$[0x`p $1`-0x`p $2`]
echo $[1+${r/-}]

```

Notes:

* Defines a function `p` that is passed a dotted decimal IP address, and outputs the hex representation of that address:
    + `${1//./ }` is a parameter expansion that replaces `.` with  in the IP address passed to `p()`
    + The `printf` is mostly self explanatory. Since there is only one format specifier `%02x` and four remaining args, the format specifier is reused for each remaining arg, effectively concatenating the 2 hex digits of each of the 4 octets together
* `$[]` causes arithmetic expansion. We do a basic subtraction, and assign to the variable `r`
* `${r/-}` is a parameter expansion to remove a possible `-` character - effectively abs()
* Display 1 + the absolute difference to give the range.

Output:

```
$ ./iprangesize.sh 0.0.0.0 255.255.255.255
4294967296
$ ./iprangesize.sh 255.255.255.255 0.0.0.0
4294967296
$ ./iprangesize.sh 1.2.3.4 1.2.3.4
1
$ ./iprangesize.sh 56.57.58.59 60.61.62.63
67372037
$ ./iprangesize.sh 1 2
2
$

```
> 6 votes

# Answer
## Python 2.7 - ~~96~~ ~~91~~ ~~90~~ 87

Made a function.

```
f=lambda a:reduce(lambda x,y:x*256+int(y),a.split("."),0)
p=lambda a,b:abs(f(a)-f(b))+1

```

Usage:

```
>>> p("1.2.3.4","1.2.3.5")
2

```

**Edit:** Removed unnecessary `int()` from `f` function. Thanks to isaacg

**Edit2:** Removed `LF` at the end of file (thanks to @Rusher) and removed `map()` at cost of `reduce()` initializer (thanks to @njzk2)
> 6 votes

# Answer
# CoffeeScript - ~~94~~, ~~92~~, ~~79~~, 72

```
I=(a)->a.split(".").reduce((x,y)->+y+x*256)
R=(a,b)->1+Math.abs I(b)-I a

```

**Un-golfed**:

```
I = ( a ) ->
    return a.split( "." ).reduce( ( x, y ) -> +y + x * 256 )

R = ( a, b ) ->
    return 1 + Math.abs I( b ) - I( a )

```

**Equivalent JavaScript**:

```
function ip2long( ip_str )
{
    var parts = ip_str.split( "." );
    return parts.reduce( function( x, y ) {
        return ( +y ) + x * 256; //Note: the unary '+' prefix operator casts the variable to an int without the need for parseInt()
    } );
}

function ip_range( ip1, ip2 )
{
    var ip1 = ip2long( ip1 );
    var ip2 = ip2long( ip2 );

    return 1 + Math.abs( ip2 - ip1 );
}

```

Try it online.
> 5 votes

# Answer
## GolfScript, 27 bytes

```
' '/{'.'/{~}%256base}/-abs)

```

Examples:

```
$ echo 0.0.0.0 255.255.255.255 | ruby golfscript.rb iprange.gs
4294967296
$ echo 255.255.255.255 0.0.0.0 | ruby golfscript.rb iprange.gs
4294967296
$ echo 1.2.3.4 1.2.3.4 | ruby golfscript.rb iprange.gs
1
$ echo 56.57.58.59 60.61.62.63 | ruby golfscript.rb iprange.gs
67372037

```
> 5 votes

# Answer
# Perl, 43 bytes

```
#!perl -pa
$_=1+abs${\map{$_=vec eval,0,32}@F}-$F[0]

```

Counting the shebang as two bytes.

Sample Usage:

```
$ echo 0.0.0.0 255.255.255.255 | perl count-ips.pl
4294967296

$ echo 255.255.255.255 0.0.0.0 | perl count-ips.pl
4294967296

$ echo 56.57.58.59 60.61.62.63 | perl count-ips.pl
67372037

```

---

**Notes**

* `vec eval,0,32` is a drop-in for `ip2long`. Perl allows character literals to be expressed as their ordinal prefixed with a `v`, for example `v0` can be used for the null char. These can also be chained together, for example `v65.66.67.68``ABCD`. When three or more values are present, the initial `v` is unnecessary. The `vec` function interprets a string as an integer array, each cell having the specified number of bits (here, 32). `unpack N,eval` would have worked equally as well.
> 5 votes

# Answer
# C# with LINQ - 139 bytes

(From 140 after applying Bob's suggestion.)

```
long f(params string[] a){return Math.Abs(a.Select(b=>b.Split('.').Select(long.Parse).Aggregate((c,d)=>c*256+d)).Aggregate((e,f)=>e-f))+1;}

```

Ungolfed....

```
    long f(params string[] a)                           // params is shorter than two parameters.
    {
        return Math.Abs(                                // At the end, make all values +ve.
             a.Select(                                  // Go through both items in the array...
                b =>                                    // Calling each one 'b'.
                    b.Split('.')                        // Separating out each "." separated byte...
                    .Select(long.Parse)                 // Converting them to a long.
                    .Aggregate((c, d) => c*256 + d)     // Shift each byte along and add the next one.
             )
             .Aggregate((e,f) => e-f)                   // Find the difference between the two remaining values.
         )+1;                                           // Add one to the result of Math.Abs.
    }

```

https://dotnetfiddle.net/XPTDlt
> 4 votes

# Answer
# dc, 61 characters

```
?[dXIr^*rdXIr^*256*+r1~dXIr^*r256*+65536*+]dspxsalpxla-d*v1+p

```

I think it's pretty amazing that this can be solved with dc at all since it has no ability to parse strings. The trick is that 192.168.123.185 goes on the stack as

```
.185
.123
192.168

```

and `dXIr^*` shifts the decimal point right as many fraction digits as there are and it even works for .100.

```
$ echo 56.57.58.59 60.61.62.63 | dc -e '?[dXIr^*rdXIr^*256*+r1~dXIr^*r256*+65536*+]dspxsalpxla-d*v1+p'
67372037.00

```

Subtract a character if you let the input already be on the stack.
> 4 votes

# Answer
# Powershell - ~~112~~ ~~108~~ ~~92~~ 78 bytes

This is my first time golfing. Here goes nothing:

### Golfed (Old):

```
$a,$b=$args|%{$t='0x';$_-split'\.'|%{$t+="{0:X2}"-f[int]$_};[uint32]$t};1+[math]::abs($a-$b)

```

### Golfed (new)

```
$a,$b=$args|%{$t='0x';$_-split'\.'|%{$t+="{0:X2}"-f+$_};[long]$t}|sort;1+$b-$a

```

### Ungolfed:

```
$a, $b = $args | % {           #powershell's way of popping an array. In a larger array
                               #$a would equal the first member and $b would be the rest.
    $t = '0x';                 #string prefix of 0x for hex notation
    $_ -split '\.' | % {       #split by escaped period (unary split uses regex)
        $t += "{0:X2}" -f +$_  #convert a dirty casted int into a hex value (1 octet)
    };
    [long]$t                   #and then cast to long
} | sort;                      #sort to avoid needing absolute value
1 + $b - $a                    #perform the calculation

```

### Usage

Save as file (in this case getipamount.ps1) and then call from the console

```
getipamount.ps1 255.255.255.255 0.0.0.0

```
> 4 votes

# Answer
## JavaScript ES6 - 68 bytes

```
f=x=>prompt().split('.').reduce((a,b)=>+b+a*256);1+Math.abs(f()-f())

```

Try it with the console (press F12) of Firefox.
> 3 votes

# Answer
# PHP, ~~138~~ 110 bytes

```
<?php

function d($a,$b){foreach(explode('.',"$a.$b")as$i=>$v){$r+=$v*(1<<24-$i%4*8)*($i<4?1:-1);}return 1+abs($r);}

// use it as
d('0.0.0.0','255.255.255.255');

```
> 2 votes

# Answer
# Perl, 72 bytes

```
#!perl -ap
@a=map{unpack N,pack C4,split/\./,$_}@F;$_=abs($a[1]-$a[0])+1

```

Usage:

```
$ echo 10.0.2.0 10.0.3.255 | perl ip-range.pl
512$

```

This is already longer than primo's Perl program, so not too interesting.

# Perl, 119 bytes, for obsolete IP address format

```
#!perl -ap
sub v(){/^0/?oct:$_}@a=map{$m=3;@p=split/\./,$_;$_=pop@p;$s=v;$s+=v<<8*$m--for@p;$s}@F;$_=abs($a[1]-$a[0])+1

```

Usage:

```
$ echo 10.0.2.0 10.0.3.255 | perl ip-obsolete.pl
512$
$ echo 10.512 10.1023 | perl ip-obsolete.pl
512$
$ echo 0xa.0x200 012.01777 | perl ip-obsolete.pl
512$

```

This program accepts the obsolete format for IP addresses! This includes addresses with 1, 2, or 3 parts, or with hexadecimal or octal parts. Quoting the inet\_addr(3) manual page,

> Values specified using dot notation take one of the following forms:
>
> ```
> a.b.c.d
> a.b.c
> a.b
> a
>
> ```
>
> ... When a three part address is specified, the last part is interpreted as a 16-bit quantity and placed in the rightmost two bytes of the network address. ... When a two part address is supplied, the last part is interpreted as a 24-bit quantity and placed in the rightmost three bytes of the network address. ... When only one part is given, the value is stored directly in the network address without any byte rearrangement.
>
> All numbers supplied as \`\`parts'' in a dot notation may be decimal, octal, or hexadecimal, as specified in the C language (i.e., a leading 0x or 0X implies hexadecimal; a leading 0 implies octal; otherwise, the number is interpreted as decimal).

Most programs no longer accept this obsolete format, but `ping 0177.1` still worked in OpenBSD 5.5.
> 2 votes

# Answer
# Python 2.7, 104 bytes

```
y=lambda:map(int,input().split("."));a,b=y(),y();print sum(256**(3-i)*abs(a[i]-b[i])for i in range(4))+1

```
> 2 votes

# Answer
# Mathematica 9, 108 bytes

```
c[f_,s_]:=1+First@Total@MapIndexed[#1*256^(4-#2)&,First@Abs@Differences@ToExpression@StringSplit[{f,s},"."]]

```

Ungolfed:

```
countIpAddresses[first_, second_] := Module[{digitArrays, differences},

  (* Split the strings and parse them into numbers.
  Mathematica automatically maps many/most of its functions across/
  through lists *)

  digitArrays = ToExpression[StringSplit[{first, second}, "."]];

  (* Find the absolute value of the differences of the two lists,
  element-wise *)
  differences = Abs[Differences[digitArrays]];

  (* differences looks like {{4, 4, 4, 4}} right now,
  so take the first element *)
  differences = First[differences];

  (* now map a function across the differences,
  taking the nth element (in code, '#2') which we will call x (in
  code, '#1') and setting it to be equal to (x * 256^(4-n)).
  To do this we need to track the index, so we use MapIndexed.
  Which is a shame,
  because Map can be written '/@' and is generally a huge character-
  saver. *)
  powersOf256 = MapIndexed[#1*256^(4 - #2) &, differences];

  (* now we essentially have a list (of singleton lists,
  due to MapIndexed quirk) which represents the digits of a base-256,
  converted to decimal form.
  Example: {{67108864},{262144},{1024},{4}}

  We add them all up using Total,
  which will give us a nested list as such: {67372036}

  We need to add 1 to this result no matter what. But also,
  to be fair to the challenge, we want to return a number -
  not a list containing one number.
  So we take the First element of our result. If we did not do this,
  we could chop off 6 characters from our code. *)

  1 + First[Total[powersOf256]]
]

```
> 1 votes

# Answer
# PHP, 46 Bytes

```
<?=abs(ip2long($argv[1])-ip2long($argv[2]))+1;

```

Try it online!

ip2long
> 1 votes

# Answer
# J, 25 bytes

Takes the dotted-quad IP strings as left and right arguments.

```
>:@|@-&(256#.".;.2@,&'.')

```

Explained:

```
>:@|@-&(256#.".;.2@,&'.')  NB. ip range
      &(                )  NB. on both args, do:
                   ,&'.'   NB.   append a .
               ;.2@        NB.   split by last character:
             ".            NB.     convert each split to number
        256#.              NB. convert from base 256
   |@-                     NB. absolute difference
>:@                        NB. add 1 to make range inclusive

```

Examples:

```
   '0.0.0.0' >:@|@-&(256#.".;.2@,&'.') '255.255.255.255'
4294967296
   iprange =: >:@|@-&(256#.".;.2@,&'.')
   '255.255.255.255' iprange '0.0.0.0'
4294967296
   '1.2.3.4' iprange '1.2.3.4'
1
   '56.57.58.59' iprange '60.61.62.63'
67372037

```
> 0 votes

# Answer
# Ruby, 93 bytes

```
a=->(x){s=i=0;x.split('.').map{|p|s+=256**(3-i)*p.to_i;i+=1};s}
s=->(x,y){1+(a[x]-a[y]).abs}

```

Output

```
irb(main):003:0> s['1.1.1.1', '1.1.1.2']
=> 2
irb(main):006:0> s['0.0.0.0', '255.255.255.255']
=> 4294967296

```
> 0 votes

# Answer
## C# - 135

```
long f(string x,string y){Func<string,long>b=s=>s.Split('.').Select((c,i)=>long.Parse(c)<<(3-i)*8).Sum();return Math.Abs(b(x)-b(y))+1;}

```

Properly formatted

```
long g(string x, string y) {
    Func<string, long> b = s => s.Split('.').Select((c, i) => long.Parse(c) << (3 - i) * 8).Sum();
    return Math.Abs(b(x) - b(y)) + 1;
}

```

https://dotnetfiddle.net/Q0jkdA
> 0 votes

# Answer
# Factor, 73 bytes

Translation of the CoffeeScript answer.

```
[ "." split [ 10 base> ] [ [ 256 * ] dip + ] map-reduce ] bi@ - abs 1 + ]

```
> 0 votes

# Answer
# Javascript ES6, 81 chars

```
(a,b)=>Math.abs(eval(`(((((${a})>>>0)-(((((${b})>>>0)`.replace(/\./g,")<<8|")))+1

```

Test:

```
f=(a,b)=>Math.abs(eval(`(((((${a})>>>0)-(((((${b})>>>0)`.replace(/\./g,")<<8|")))+1
;`0.0.0.0,255.255.255.255,4294967296
255.255.255.255,0.0.0.0,4294967296
1.2.3.4,1.2.3.4,1
56.57.58.59,60.61.62.63,67372037`.split`
`.map(x=>x.split`,`).every(x=>f(x[0],x[1])==x[2])

```

PS: I'll try to optimise it a bit later.
> 0 votes

# Answer
## Lua, 153 Bytes

It's a shame that lua doesn't have a split function, I had to define mine!

```
a,b=...r=0y=8^8x={}t={}function f(t,s)s:gsub("%d+",function(d)t[#t+1]=d end)end
f(x,a)f(t,b)for i=1,4 do r=r+y*math.abs(t[i]-x[i])y=y/256 end print(r+1)

```

### Ungolfed

```
a,b=...                    -- unpack the arguments into two variables
r=0                        -- initialise the sume of ip adress
y=8^8                      -- weight for the rightmost value
x={}t={}                   -- two empty arrays -> will contains the splittedip adresses
function f(t,s)            -- define a split function that takes:
                           --   a pointer to an array
                           --   a string
  s:gsub("%d+",function(d) -- iterate over the group of digits in the string
    t[#t+1]=d              -- and insert them into the array
  end)
end
f(x,a)                     -- fill the array x with the first address
f(t,b)                     -- fill the array t with the second address
for i=1,4                  -- iterate over t and x
do
  r=r+y*math.abs(t[i]-x[i])-- incr r by weight*abs(range a- range b)
  y=y/256                  -- reduce the weight
end
print(r+1)                 -- output the result

```
> 0 votes

# Answer
# Jelly, 12 bytes, language postdates challenge

```
ṣ”.V€ḅ⁹µ€ạ/‘

```

Try it online!

## Explanation

```
ṣ”.V€ḅ⁹µ€ạ/‘
       µ€     On each element of input:
ṣ”.             Split on periods
   V€           Convert string to number in each section
     ḅ⁹         Convert base 256 to integer
         ạ/   Take absolute difference of the resulting integers
           ‘  Increment

```

The number of elements in an inclusive range is the absolute difference of their endpoints, plus 1.
> 0 votes

# Answer
# Axiom, 385 bytes

```
c(a:String):INT==(d:=digit();s:NNI:=#a;t:INT:=0;for i in 1..s repeat(~member?(a.i,d)=>return-1;t:=t+(ord(a.i)-48)*10^(s-i)::NNI);t)
g(x:String):List NNI==(a:=split(x,char".");s:NNI:=#a;r:=[];for i in s..1 by -1 repeat(y:=c(a.i);y=-1=>return [];r:=concat(y,r));r)
m(x:NNI,y:NNI):NNI==x*256+y
f(a:String,b:String):INT==(x:=g(a);y:=g(b);#x~=4 or #y~=4=>-1;1+abs(reduce(m,x)-reduce(m,y)))

```

ungolf it and test

```
-- convert the string only digit a in one not negative number
-- return -1 in case of error
cc(a:String):INT==
     d:=digit();s:NNI:=#a;t:INT:=0
     for i in 1..s repeat
               ~member?(a.i,d)=>return -1
               t:=t+(ord(a.i)-48)*10^(s-i)::NNI
     t

-- Split the string x using '.' as divisor in a list of NNI
-- if error return []
gg(x:String):List NNI==
    a:=split(x,char".");s:NNI:=#a;r:=[]
    for i in s..1 by -1 repeat
          y:=cc(a.i)
          y=-1=>return []
          r:=concat(y,r)
    r

mm(x:NNI,y:NNI):NNI==x*256+y

-- Return absolute value of difference of address for IP strings in a and in b
-- Retrun -1 for error
-- [Convert the IP strings in a and in b in numbers ad subtract and return the difference]
ff(a:String,b:String):INT==(x:=gg(a);y:=gg(b);#x~=4 or #y~=4=>-1;1+abs(reduce(mm,x)-reduce(mm,y)))

(14) -> f("0.0.0.0", "255.255.255.255")
   (14)  4294967296
                                                    Type: PositiveInteger
(15) -> f("255.255.255.255", "0.0.0.0")
   (15)  4294967296
                                                    Type: PositiveInteger
(16) -> f("1.2.3.4", "1.2.3.4")
   (16)  1
                                                    Type: PositiveInteger
(17) -> f("56.57.58.59", "60.61.62.63")
   (17)  67372037
                                                    Type: PositiveInteger
(18) -> f("1", "2")
   (18)  - 1
                                                            Type: Integer

```
> 0 votes

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


# Question
Title: Further golfing this C# code from Scramble words while preserving their outlines
I'll start off by saying I checked and checked again that this question should be on topic.

I will also clearly state that this is a question about further golfing a certain set of code **not** a challenge.

---

I recently answered the following challenge: Scramble words while preserving their outlines:

> It is well known that a text can still be read while the innards of its words have been scrambled, as long as their first and last letters plus their overall outlines remain constant. Given a printable Ascii+Newline text, scramble each word according to these rules:
>
> 1. Scrambling must be (pseudo) random.
> 2. A word is a sequence of the Latin characters, A through Z.
> 3. Only initial letters will ever be uppercase.
> 4. The first and last letters must stay untouched.
> 5. When scrambling, only letters within one of the following groups may exchange places:
>
> 1. `acemnorsuvwxz`
>     2. `bdfhkl`
>     3. `gpqy`
>     4. `it`
>     5. `j` (stays in place)

My answer is in C# and coming in, currently, at 394 bytes:

```
namespace System{using Text.RegularExpressions;using Linq;s=>Regex.Replace(s,@"[A-Za-z](([acemnorsu-xz])|([bdfhkl])|([gpqy])|([it]))*?[a-z]?\b",m=>{var a=m.Value.ToCharArray();for(int i=1,j;++i<6;){var c=m.Groups[i].Captures;var n=c.Cast<Capture>().Select(p=>p.Index-m.Index).ToList();foreach(Capture p in c){a[j=n[new Random().Next(n.Count)]]=p.Value[0];n.Remove(j);}}return new string(a);});}

```

I think there's room for golfing in the Linq statement and `foreach` loop at least.

Can this code be further golfed down?

# Answer
> 0 votes
As I am using `linq` in my program, I can change `ToCharArray` to `ToArray` to save 4 bytes.

I can also change the `namespace` around to be either `System.Linq` or `System.Text.RegularExpressions` to save a further 6 bytes by removing the `using` for it:

```
namespace System.Text.RegularExpressions

```

As @MartinEnder♦ points out in the comments I can save 10 bytes by re-ordering the groups in the regex and changing `[A-Za-z]` to `\p{L}`:

```
\p{L}(([gpqy])|(i|t)|(j)|([bdf-l])|([a-z]))*?[a-z]?\b

```

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


title: Tell me, how many squares are there?

text:
# Question
Title: Tell me, how many squares are there?
Given a non-empty 2D array consisting of `0` and `1`, find the number of squares whose 4 corners are all `1`. The squares do not need to be "upright". All the rows are guaranteed to have the same length.

Reasonable input/output methods are allowed.

Testcases:

```
0001000
1000000
0000000
0000100
0100000

```

This returns `1`.

```
10101
00000
10100
00000
10001

```

This returns `2`.

```
1111
1111
1111
1111

```

This returns `20`.

This is . Shortest answer in bytes wins. Standard loopholes apply.

# Answer
## JavaScript (ES6), ~~127~~ ~~124~~ 119 bytes

*Saved 3 bytes thanks to nderscore*

```
m=>(F=(x,y)=>m.map((r,Y)=>r.map((i,X)=>i?1/y?n+=x<X&y<=Y&(g=(a,b)=>(m[b+X-x]||0)[a-Y+y])(x,y)&g(X,Y):F(X,Y):0)))(n=0)|n

```

### How?

This function iterates on all pairs of cells **(x, y)**, **(X, Y)** of the input matrix **m** such that:

* **m\[ x, y \] = m\[ X, Y \] = 1**
* **x \< X**
* **y ≤ Y**

Each matching pair describes the coordinates of a potential edge of a square. The inequations guarantee that each edge is tested only once.

We use the vector **\[ dx, dy \] = \[ X - x, Y - y \]** rotated 90° clockwise to test the cells located at **\[ x - dy, y + dx \]** and **\[ X - dy, Y + dx \]**. If they both contain a **1**, we've found a valid square.

### Test cases

```
let f =

m=>(F=(x,y)=>m.map((r,Y)=>r.map((i,X)=>i?1/y?n+=x<X&y<=Y&(g=(a,b)=>(m[b+X-x]||0)[a-Y+y])(x,y)&g(X,Y):F(X,Y):0)))(n=0)|n

console.log(f([
  [0,0,0,1,0,0,0],
  [1,0,0,0,0,0,0],
  [0,0,0,0,0,0,0],
  [0,0,0,0,1,0,0],
  [0,1,0,0,0,0,0]
]));

console.log(f([
  [1,0,1,0,1],
  [0,0,0,0,0],
  [1,0,1,0,0],
  [0,0,0,0,0],
  [1,0,0,0,1]
]));

console.log(f([
  [1,1,1,1],
  [1,1,1,1],
  [1,1,1,1],
  [1,1,1,1]
]));
```
> 18 votes

# Answer
# MATL, 20 bytes

```
&fJ*+4XN!"@&-|un3=vs

```

Input is a matrix.

Try it online!

### How it works

This finds all coordinates of nonzero entries in the input grid, and represents them as complex numbers, such that row and column indices correspond to real and imaginary parts respectively.

The code then generates an array of all combinations (order doesn't matter) of these numbers taken 4 at a time. Each combination represents a candidate square. For each combination, the 4×4 matrix of pair-wise absolute differences (i.e. distances in the complex plane) is computed. This is a symmetric matrix with zeros along its main diagonal. The current combination forms a square if and only if the matrix contains exactly 3 distinct values (these will be the square side, the square diagonal, and zero):

On the other hand, for example, a non-square rectangle would give rise to 4 distinct values (two sides, one diagonal value, and zero);

and a general quadrilateral can have up to 7 values (four sides, two diagonals, and zero):

```
&f      % Input (implicit). Push vectors of row and column indices of nonzero entries
J*      % Multiply by imaginary unit
+       % Add the two vectors. Gives a vector of complex coordinates
4XN     % Matrix of combinations of these complex numbers, taken 4 at a time. Each
        % row is a combination
!       % Transpose
"       % For each column
  @     %   Push current column: candidate set of four points
  &-    %   All pair-wise differences
  |     %   Absolute value
  u     %   Unique entries
  n3=   %   Does the number of elements equal 3? Gives true (1) or false (0)
  vs    %   Concatenate vertically with previous accumulated result, and sum
        % End (implicit). Display (implicit)

```
> 6 votes

---
Tags: code-golf, ascii-art
---


title: Draw Spiral Words

text:
# Question
Title: Draw Spiral Words
**The Scenario**

Given an input of ASCII lowercase letters and spaces, draw a spiral of characters that traces the original input of characters excluding spaces.

**The Rules**

1) The characters shall spiral counterclockwise to the left in an outwardly fashion. If a left turn is not possible, then move straight.

```
Given: abcdefg
Output:
  g
baf
cde

```

2) The characters can spiral into previous characters so long as rule #1 is not violated. Also, if that character is spiraled into, then that character is uppercased. Once a character is uppercased, it will stay uppercased regardless of the number of times it is reused.

```
Given: apples appeal
Output:
PAs
PLe
ea

```

# Answer
> 2 votes
# JavaScript, ~~225~~ ~~221~~ 212 bytes

-9 bytes thanks to Conor O'Brien

Please note that your text cases conflict with each other. Your first test case starts in the middle of the spiral. Your second test case starts in the top middle of the spiral. I went with your first test case, because it was the first one I saw. You haven't edited your question in over a year, so sorry for the presumption.

First Test Case:

```
9<-8<-7
|     |
2<-1  6
|     |
3->4->5

```

Second Test Case:

```
2<-1<-6
|     |
3->4->5
|     |
7->8->9

```

Without any further adieu, here is the golfed code. I am 100% sure that if the community chips it this could be cut significantly. This returns a multiline array.

```
s=>eval("s=[...s.replace(/ /g,'')];i=0;k=j=1;a=[[],[],[]];b='00122210';c=b*100+'';for(;;){for(l=0;l<8;l++){if(!s[i])break;if(a[k][j]==s[i])s[i]=s[i].toUpperCase();a[k][j]=s[i];k=b[l];j=c[l];i++}if(!s[i])break}a")

```

Prettification snippet (prints a multiline string to console). Please note the different in my test case #2 and OP's test case #2 (see above if you have not already):

(if someone with more experience with snippets wants to fix this into HTML input feel free to edit this, I need to go to bed).

```
f=
s=>eval("s=[...s.replace(/ /g,'')];i=0;k=j=1;a=[[],[],[]];b='00122210';c=b*100+'';for(;;){for(l=0;l<8;l++){if(!s[i])break;if(a[k][j]==s[i])s[i]=s[i].toUpperCase();a[k][j]=s[i];k=b[l];j=c[l];i++;g(a)}if(!s[i])break}a")

//replace argument here to change output
var arr = f("apples appeal");

function g(ar) {
  var str = "";

  for (x = 0; x < 3; x++) {
    for (y = 0; y < 3; y++) {
      str += ar[y][x] || " ";
    }
    str += "\n";
  }
  console.log(str);
}
```

# Ungolfed and Explanation

```
f=(input)=>{
    //remove spaces
    input = input.replace(/ /g, "");

    //convert to array (so I can uppercase individual letters)
    input = input.split("");

    //position in input
    var pos = 0;

    //positions inside output
    var xPos = 1;
    var yPos = 1;

    //output container (3 rows, 3 columns)
    var arr = [[],[],[]];

    //counterclockwise indexes for x
    var xOrder = "00122210";

    //counterclockwise indexes for y
    //var yOrder = "12221000"
    var yOrder = xOrder * 100 + "";

    //loop infinitely (breaks when input[pos] is undefined)
    for (;;) {
        //loop around circle
        for (var i = 0; i < 8; i++) {
            if (!input[pos]) {
                break;
            }

            //if item already in array equal next item in input, set next item in input to caps before
            if (arr[xPos][yPos] == input[pos]) {
                input[pos] = input[pos].toUpperCase();
            }

            //write or overwrite in array with current from input
            arr[xPos][yPos] = input[pos];

            //increment last because we do not prime our loops
            xPos = xOrder[i];
            yPos = yOrder[i];
            pos++;
        }
        if(!input[pos]) {
            break;
        }
    }
    return arr;
}

```

---
Tags: code-golf, ascii-art
---


title: Add up two algebraic numbers

text:
# Question
Title: Add up two algebraic numbers
## Definitions

* An algebraic number is a number that is a zero of a non-zero polynomial with integer coefficients. For example, the square root of `2` is algebraic, because it is a zero of `x^2 - 2`.
* The corresponding polynomial is called the minimal polynomial of the algebraic number, provided that the polynomial is irreducible over .

## Task

Given the minimal polynomials of two algebraic numbers, construct a set of numbers that are the sum of two numbers, one from the root of one polynomial, and one from the other. Then, construct a polynomial having those numbers as roots. Output the polynomial. Note that all roots are to be used, **including complex roots**.

## Example

* The two roots of `x^2-2` are `√2` and `-√2`.
* The two roots of `x^2-3` are `√3` and `-√3`.
* Pick one from a polynomial, one from the other, and form 4 sums: `√2+√3`, `√2-√3`, `-√2+√3`, `-√2-√3`.
* A polynomial containing those four roots is `x^4-10x^2+1`

## Input

Two polynomials in any reasonable format (e.g. list of coefficients). They will have degree at least `1`.

## Output

One polynomial in the same format, with **integer coefficients**.

You are **not** required to output an irreducible polynomial over .

## Testcases

Format: input, input, output.

```
x^4 - 10 x^2 + 1
x^2 + 1
x^8 - 16 x^6 + 88 x^4 + 192 x^2 + 144

x^3 - 3 x^2 + 3 x - 4
x^2 - 2
x^6 - 6 x^5 + 9 x^4 - 2 x^3 + 9 x^2 - 60 x + 50

4x^2 - 5
2x - 1
x^2 - x - 1

2x^2 - 5
2x - 1
4x^2 - 4 x - 9

x^2 - 2
x^2 - 2
x^3 - 8 x

```

The outputs are irreducible over  here. However, as stated above, you do not need to output irreducible polynomials over .

## Scoring

This is . Shortest answer in bytes wins.

# Answer
# Mathematica, 32 bytes

```
Resultant[#,#2/.x->z-x,x]/.z->x&

```

Or the same length:

```
Resultant[#/.x->y,#2/.x->x-y,y]&

```

### Example:

```
In[1]:= Resultant[#,#2/.x->z-x,x]/.z->x&[x^4 - 10 x^2 + 1, x^2 + 1]

Out[1]= 144 + 192 x^2 + 88 x^4 - 16 x^6 + x^8

In[2]:= Resultant[#/.x->y,#2/.x->x-y,y]&[x^2 - 2, x^2 - 2]

Out[2]= -8 x^2 + x^4

```

### Explanation:

If `x` is a root of `f(x)`, `y` is a root of `g(y)`, and let `z = x + y`, then `(x, z)` is a root of the simultaneous equations `f(x) = 0, g(z - x) = 0`. Then we can eliminate the variable `x` using the resultant.
> 7 votes

# Answer
# Octave, ~~81~~ 71 bytes

*10 bytes off thanks to Suever!*

```
@(a,b){[~,d]=rat(x=poly((roots(a)+roots(b)')(:)')),round(x*prod(d))}{2}

```

Try it online!

### Explanation

The code defines an anonymous function which uses a straightforward approach. It obtains the roots of each polynomial, computes all pairwise sums, and converts back from roots to polynomial. Since the resulting coefficients may not be integer, each is converted to a rational approximation and then they are all multiplied by the product of denominators.
> 3 votes

# Answer
# Pari/GP, ~~50~~ 49 bytes

```
p->q->polresultant(subst(p,x,y),subst(q,x,x-y),y)

```

Try it online!
> 2 votes

# Answer
# Jelly, 16 bytes

```
Ærp/S€Æṛær9µ÷g/Ḟ

```

Try it online! (runs the last test case)

Takes input as list of coefficients with lowest value exponent first, e.g. `[-5,0,2],[-1,2]` would be `2x^2-5,2x-1`

**Explanation**

```
Ærp/S€Æṛær5µ÷g/Ḟ
Ær                 - get roots of input polynomial
  p/               - Cartesian product (all pairs) of roots
    S€             - sum of each pair
      Æṛ           - find a polynomial given the sums as the roots
        ær9        - round to 10^(-9), used for output
           µ÷      - divide by ...
             g/    - the gcd of the coefficients of the output polynomial
               Ḟ   - take the floor to get integers.

```
> 0 votes

---
Tags: code-golf, number, polynomials
---


title: Neutralize data

text:
# Question
Title: Neutralize data
To neutralize data, recursively replace all numbers (not digits!) with zeros and all characters (not strings!) with spaces.

You must accept any single number, character, or string, or possibly recursive array\* of mixed numeric/character data that your language can handle. For example, you must accept actual strings (and not restrict your input to lists of single characters) if your language can handle such.

If your language contains a built-in which does all or most of this task, I would appreciate an additional alternative version without it.

The shortest submission in each language is a winner, and will receive an upvote from me.

**Sample cases**

1. `""``""`
2. `7``0`
3. `123.456``0`
4. `"X"``" "`
5. `" "``" "`
6. `"Yo!"``" "`
7. `[]``[]`
8. `[-1.2E3]``[0]`
9. `["Hey"]``[" "]`
10. `["H","e","y"]``[" "," "," "]`
11. `["R",2,"D",2]``[" ",0," ",0]`
12. `["C","3","P",0]``[" "," "," ",0]`
13. `["THX",[1138]]``[" ",[0]]`
14. `["T","H","X",[1138]]``[" "," "," ",[0]]`
15. `[[["H"],"e",1,1,0],[[-3],"arth"]]``[[[" "]," ",0,0,0],[[0]," "]]`

* If your language has several types which can equally well represent arrays like the above examples, you may chose to support only one. Two entries can both win, even though they are using the same language, by each going with a different data type.

# Answer
> 17 votes
## JavaScript (ES6), ~~53~~ 47 bytes

```
f=o=>o.big?o.replace(/./g,' '):o.map?o.map(f):0

```

### Test cases

```
f=o=>o.big?o.replace(/./g,' '):o.map?o.map(f):0

test = [
  "",
  7,
  123.456,
  "X",
  "  ",
  "Yo!",
  [],
  [-1.2E3],
  ["Hey"],
  ["H","e","y"],
  ["R",2,"D",2],
  ["C","3","P",0],
  ["THX",[1138]],
  ["T","H","X",[1138]],
  [[["H"],"e",1,1,0],[[-3],"arth"]]
];

test.map(o => {
  console.log(JSON.stringify(o), '=>', JSON.stringify(f(o)));
});
```

# Answer
> 7 votes
## Ruby, ~~54 53~~ 49 bytes

```
f=->a{a*0==0?0:a*0==[]?a.map{|x|f[x]}:" "*a.size}

```

Maybe there is a better way, but:

* x\*0 == 0 for integers
* x\*0 == "" for strings
* x\*0 == \[\] for arrays

# Answer
> 7 votes
# Python 2, 52 bytes

```
f=lambda x:1-(x<{})and map(f,x)if x<''else' '*len(x)

```

Try it online!

### How it works

Python lets you compare different types. Numeric types are always smaller than iterables, and iterables are sorted by their type names, so

```
0 < {} < [] < '' < ()

```

This way, **f** does the following.

* If **x** is numeric `x<{}` returns *True* and `1-(x<{})` returns **0**. The code after `and` does not get executed.
* If **x** is iterable, `1-(x<{})` returns **1** (truthy), so the code after `and` gets executed.

+ If **x** is a list, `x<''` is true and **f** gets mapped over its items.
    + If **x** is a string, `x<''` is false and **x** is replaced with a string of spaces of the same length.

# Answer
> 6 votes
## Mathematica, 51 bytes

I've currently got two solutions at this byte count:

```
#/._?NumberQ->0/.x_String:>StringReplace[x,_->" "]&
StringReplace[#,_->" "]~Check~#&//@#/._?NumberQ->0&

```

The second one throws a bunch of warnings which can be ignored.

### Explanation

In either case, we start by turning numbers into zeros with

```
#/._?NumberQ->0

```

Then to process the string, there are two options. Either, we use another substitution that only applies to strings:

```
.../.x_String:>StringReplace[x,_->" "]

```

Or, we use the `MapAll` operator `//@` which maps a function over every single element in a nested list. The catch here is that we'll be trying to use `StringReplace` on zeros as well as the symbol `List` (since `//@` also goes through the heads of expressions), so we need to use `Check` (sort of like a `catch` statement in other languages) to avoid wreaking havoc with those values:

```
StringReplace[#,_->" "]~Check~#&//@...

```

# Answer
> 5 votes
# Perl 6, ~~34~~ 48 bytes

~~```
{.deepmap:{$_~~Str??" "x.comb!!0}}

```~~
```
{$_~~List??$_».&?BLOCK!!$_~~Str??" "x .comb!!0}

```

Expanded:

```
{                          # block-based lambda
    $_ ~~ List             # if argument is a list/array
        ?? $_».&?BLOCK     # then recurse for each element (&?BLOCK is a compile-time var)
        !! $_ ~~ Str       # else if argument is a string
            ?? " "x .comb  # then use space repeated by the string's length,
            !! 0           # else use the number 0
}

```

# Answer
> 5 votes
# Jelly, 4 bytes

```
nOa⁶

```

This is a monadic link. Jelly's implicit printing does a lot of splatting; to verify that the output is what it should be, you can view the internal representation with `ŒṘ`. Note that this exposes strings as lists of characters, which is how the Jelly interpreter implements them.

Try it online!

### How it works

```
nOa⁶  Monadic link. Argument: z

 O    Ordinal; replace all characters with the code points.
      This does not affect numbers.
n     Vectorizing not-equal; compare z with the result to the right, replacing
      characters with 1 and numbers with 0.
  a⁶  Logical AND space; replace all 1's with spaces.

```

# Answer
> 3 votes
## GAP, 91 bytes

GAP has a method `Zero` that returns the neutral additive element corresponding to an element of an additive structure. That handles numbers and even lists of numbers which are considered vectors, but not arbitrary lists. So let's add these and Chars and use that Strings are lists of Chars:

```
InstallOtherMethod(Zero,[IsChar],c->' ');
InstallOtherMethod(Zero,[IsList],l->List(l,Zero));

```

(I'm not counting the newline as it isn't needed.) Of course this is far away from the intended use of `Zero`, and GAP would complain if I hadn't used `Install`*Other*`Method`. Now I can do:

```
gap> Zero([[["H"],"e",1,1,0],[[-3],"arth"]]);
[ [ [ " " ], " ", 0, 0, 0 ], [ [ 0 ], "    " ] ]

```

I wouldn't say that the builtin does most of the job, one might rather suspect that writing a normal function should be shorter, but my best try doing that was 92 bytes long:

```
f:=function(x)if IsInt(x)then return 0;elif IsList(x)then return List(x,f);fi;return' ';end;

```

# Answer
> 2 votes
## Haskell, 115 bytes

My language cannot handle any mix of numbers and strings in lists (but of course you can define a sum type and put that in a list), and its standard lists cannot handle differently nested lists. So I'm just doing what it can handle. I think that is not unfair because it is still long, and I mainly do it to show features of haskell that are rarely seen in haskell golfing solutions. Note that Strings are lists of Chars.

```
class N a where n::a->a
instance N Double where n _=0
instance N Char where n _=' '
instance N a=>N[a]where n=map n

```

This handles any number as Double:

```
*Main> n 42
0.0
*Main> n 123.456
0.0
*Main> n "hi"
"  "
*Main> n [[1,2],[3,4,5]]
[[0.0,0.0],[0.0,0.0,0.0]]
*Main> n ["hello","world!"]
["     ","      "]

```

# Answer
> 2 votes
# PHP, 91 bytes

```
function f($a){return!is_array($a)?is_string($a)?str_pad("",strlen($a)):0:array_map(f,$a);}

```

if parameter is array: recurse using `array_map`.
else if parameter is string: generate a strings of spaces with the same length.
else `0`.

`is_string` saves one byte over `is_numeric`; negating `is_array()` renders parentheses obsolete. Altogether it´s 17 bytes shorter than `if()recursion-loop;else x?string:number` with a call by reference.

# Answer
> 2 votes
## Python 2, 59 bytes

```
g=lambda d:0if d*0==0else " "*len(d)if d*0==""else map(g,d)

```

uses G B's way to determine types

# Answer
> 2 votes
## Common Lisp, 87

```
(defun c(e)(typecase e(list(mapcar'c e))(number 0)(string(map'string(lambda(u)#\ )e))))

```

Ungolfed

```
(defun c(e)
  (typecase e
    (list (mapcar #'c e))
    (number 0)
    (string (map 'string (lambda(u) #\space) e))))

```

Example

```
> (c '((("H") "e" 1 1 0) ((-3) "arth")))
(((" ") " " 0 0 0) ((0) "    "))

```

# Answer
> 2 votes
# APL (Dyalog) 13.2 and earlier, 1 byte

Until and including version 13.2, monadic  did exactly this. The old behaviour can be activated by setting `⎕ML` (**M**igration **L**evel) to zero.

Try it online!

Without using old behaviour it is 4 bytes:

```
⊃0⍴⊂

```

Try it online!

enclose

`0⍴` make a length-zero list of copies of the entire input (preserves only structure and type info)

coerce one element from that (creates a prototypical array)

# Answer
> 1 votes
## Groovy, 53 bytes

```
{[it].collectNested{it in String?" "*it.size():0}[0]}

```

This is an unnamed closure. Try it here!

**Explanation**:

Groovy has this method `.collectNested` which helps to iterate through a list as if it was flattened.

To handle special cases where only an integer or a string is passed without a list, simply wrap every input into a list and output the first element.

# Answer
> 1 votes
## Pyke, 8 bytes (Old version)

```
.FZ*0+d&

```

Explanation:

```
.FZ*0+d& - for i in deep_for(input):
  Z*     -    i*0
    0+   -   ^ + 0
      d& -  ^ and " "

```

This no longer works as an update made it so falsies of other types where there are truthies automatically convert to the falsey of the truthy type.

# Answer
> 1 votes
## C#, ~~197~~ 195 Bytes

```
a=>{if(a is string||a is char)return new string(' ',(a as string)?.Length??1);try{System.Convert.ToDecimal(a);return 0;}catch{}var b=(object[])a;for(int i=0;i<b.Length;)b[i]=n(b[i++]);return b;};

```

This function handles `char`, `string`, any builtin number type and recursive arrays.

Full program, ungolfed whit output helper:

```
using System.Linq;
class Class
{
    public static void Main()
    {
        System.Func<object, object> n = null;
        n = a =>
        {
            if (a is string || a is char)
                return new string(' ', (a as string)?.Length ?? 1);
            try
            {
                System.Convert.ToDecimal(a);
                return 0;
            }
            catch { }

            var b = (object[])a;
            for (int i = 0; i < b.Length;)
                b[i] = n(b[i++]);
            return b;
        };

        var result = n(new object[] { new object[] { new object[] { "H" }, 'e', 1.5, 1, 0 }, new object[] { new object[] { -3 }, "arth" } });
        System.Console.WriteLine(Output(result));
        System.Console.Read();
    }

    static string Output(object x)
    {
        var arr = x as object[];
        if (arr != null)
            return "[" + string.Join(",", arr.Select(Output)) + "]";
        else
            return x.ToString();
    }
};

```

The `using` statement is only needed for the output helper, not for the actual function.

Try Online

# Answer
> 0 votes
# Javascript ES6, 81 chars

```
f=(x,t)=>(t=g=>eval(`try{x.${g}}catch(e){}`))`replace(/./g,' ')`||t`map(f)`||x&&0

```

Test:

```
f=(x,t)=>(t=g=>eval(`try{x.${g}}catch(e){}`))`replace(/./g,' ')`||t`map(f)`||x&&0

console.log(
`"" → ""
7 → 0
123.456 → 0
"X" → " "
"  " → "  "
"Yo!" → "   "
[] → []
[-1.2E3] → [0]
["Hey"] → ["   "]
["H","e","y"] → [" "," "," "]
["R",2,"D",2] → [" ",0," ",0]
["C","3","P",0] → [" "," "," ",0]
["THX",[1138]] → ["   ",[0]]
["T","H","X",[1138]] → [" "," "," ",[0]]
[[["H"],"e",1,1,0],[[-3],"arth"]] → [[[" "]," ",0,0,0],[[0],"    "]]`
.split`
`.map(s => s.split` → `.map(eval))
.every(([s,k]) => JSON.stringify(f(s))==JSON.stringify(k)))
```

# Answer
> 0 votes
# Java 7, 262 (268) bytes

```
import java.util.*;Object c(Object o){if(o instanceof List){List r=new ArrayList();for(Object x:(List)o)r.add(c(x));return r;}if(o instanceof String){String r="\"";for(int i=((String)o).length();i-->0;r+=" ");return r+"\"";}return o instanceof Number?0:o instanceof Character?"' '":"";}

```

282 + 6 for the added `\"` and `'` to pretty-print the String and characters.

**Explanation:**

```
import java.util.*;            // Required import for List and ArrayList
Object c(Object o){            // Method with Object parameter and Object return-type
  if(o instanceof List){       //  If the input is a List
    List r=new ArrayList();    //   Create a result-list
    for(Object x:(List)o)      //   Loop over the items of the input-list
      r.add(c(x));             //    And add all items with a recursive-call to this method
                               //   End of loop (implicit / single-line body)
    return r;                  //   Return result-list
  }if(o instanceof String){    //  If the input is a String instead
    String r="\"";             //   Create a result-String (starting with `"`
    for(int i=((String)o).length();i-->0;r+=" ");
                               //   Replace all characters in the String with a space
    return r+"\"";             //   Return the result within double-quotes
  }
  return o instanceof Number?  //  If the input is an integer or decimal instead:
    0                          //   Return 0
   :o instanceof Character?    //  If the input is a character instead:
    "' '"                      //   Return ' '
   :                           //  Else:
    "";                        //   Return an empty String
}                              // End of method

```

**Test code:**

Try it here.

```
import java.util.*;
class M{
  static Object c(Object o){if(o instanceof List){List r=new ArrayList();for(Object x:(List)o)r.add(c(x));return r;}if(o instanceof String){String r="\"";for(int i=((String)o).length();i-->0;r+=" ");return r+"\"";}return o instanceof Number?0:o instanceof Character?"' '":"";}

  public static void main(String[] a){
    System.out.println(c(""));
    System.out.println(c(7));
    System.out.println(c(123.456));
    System.out.println(c('X'));
    System.out.println(c("  "));
    System.out.println(c("Yo!"));
    System.out.println(c(new ArrayList()));
    System.out.println(c(new ArrayList(){{add(-1.2e3);}}));
    System.out.println(c(new ArrayList(){{add("Hey");}}));
    System.out.println(c(new ArrayList(){{add('H');add('e');add('y');}}));
    System.out.println(c(new ArrayList(){{add('R');add(2);add('D');add(2);}}));
    System.out.println(c(new ArrayList(){{add("THX");add(new ArrayList(){{add(1138);}});}}));
    System.out.println(c(new ArrayList(){{add('T');add('H');add('X');add(new ArrayList(){{add(1138);}});}}));
    System.out.println(c(new ArrayList(){{add(new ArrayList(){{add(new ArrayList(){{add('H');}});add('e');add(1);add(1);add(0);}});add(new ArrayList(){{add(new ArrayList(){{add(-3);}});add("arth");}});}}));
  }
}

```

**Output:**

```
""
0
0
' '
"  "
"   "
[]
[0]
["   "]
[' ', ' ', ' ']
[' ', 0, ' ', 0]
["   ", [0]]
[' ', ' ', ' ', [0]]
[[[' '], ' ', 0, 0, 0], [[0], "    "]]

```

---
Tags: code-golf, array, conversion, data-structures, substitution
---


# Question
Title: Does the sum of 2 numbers in the list equal the desired sum?
# The Task

This is my first challenge so apologies if it is very simple! In this challenge, your task is to write a program or function which takes in a list of integers and a desired sum and outputs a truthy or falsey value based on whether the list contains two numbers that can be summed together to achieve the desired sum.

# Input

The input must be acquired in a standard way for your language. The list of integers can be any standard collection type for your language but cannot be a hashed set, sorted set, or any highly functional collection type. Don't assume the input is sorted, any valid integer type is acceptable.

The desired sum is also an integer and must be provided to your program as input.

# Output

The output may be a function return, console log, writing to a file, etc... Any valid Truthy or Falsey value is acceptable.

# Additional Rules

* The input list may or may not be sorted.
* Duplicate values may occur in the list
* The same item in the list may not be summed to itself to achieve the desired sum (Eg. \[3,4,5\] with desired sum 6 will expect False because 3 cannot be used twice)
* Standard loopholes are not allowed.

Test Cases

```
INPUT                 OUTPUT
[3,4,5], 6            Falsey
[1,2,3,4,5,6],11      Truthy
[4,23,8174,42,-1],41  Truthy
[1,1,1,1,1,3],3       Falsey
[2,1,1,1,53,2],4      Truthy
[2,2,2,2],4           Truthy
[3],3                 Falsey
[],-43                Falsey

```

This is , so the shortest code in bytes wins!

# Answer
# Brachylog, 3 bytes

```
⊇Ċ+

```

Try it online!

```
⊇Ċ+   input as STDIN, output as ARG1
      (prove that:)
⊇     the input is a superset of
 Ċ       a list of two elements
  +         which sums up to the output

```
> 9 votes

# Answer
# Jelly, ~~7~~ ~~6~~ 5 bytes

```
ŒcS€ċ

```

Try it online!

-1 byte by using the Unordered Pairs atom

```
ŒcS€ċ  Main Link; left argument is the array, right argument is the required sum
  S€   Take the sum of each...
Œc     ...unordered pair...
    ċ  Check if the sum array contains the right argument

```

-1 byte thanks to Erik!

# 4 bytes

```
Œc§i

```

This does the same thing but with a newer language feature of vectorize-at-depth-1 sum. Thanks Dennis! :D Credit to @Riolku for noticing this.
> 6 votes

# Answer
# 05AB1E, 6 bytes

```
æ2ùOIå

```

Try it online!

**Explanation**

```
æ        # get powerset of first input
 2ù      # keep only those of size 2
   O     # sum each
    Iå   # check if 2nd input is in the list of sums

```
> 4 votes

# Answer
# Python 2, ~~43~~ 42 bytes

<sup>-1 byte thanks to mbomb007</sup>

```
lambda a,b:any(b-a.pop()in a for x in a*1)

```

Try it online!
> 4 votes

# Answer
# Mathematica, 29 bytes

```
!FreeQ[Tr/@#~Subsets~{2},#2]&

```
> 4 votes

# Answer
# MATL, 6 bytes

```
2XN!sm

```

Try it online!

### Explanation

```
2XN   % Implicitly input an array. Combinations of elements taken 2 at a time
      % The result is a matrix where each row is a combination
!s    % Sum of each row
m     % Implicitly input a number. Ismember function. Implicitly display

```
> 3 votes

# Answer
# JavaScript (ES6), ~~38~~ 43 bytes

```
a=>n=>[...a].some(_=>a.includes(n-a.pop()))

```

---

## Try It

```
f=
a=>n=>[...a].some(_=>a.includes(n-a.pop()))
o.innerText=`           f([3,4,5])(6) = ${f([3,4,5])(6)}
    f([1,2,3,4,5,6])(11) = ${f([1,2,3,4,5,6])(11)}
f([4,23,8174,42,-1])(41) = ${f([4,23,8174,42,-1])(41)}
     f([1,1,1,1,1,3])(3) = ${f([1,1,1,1,1,3])(3)}
    f([2,1,1,1,53,2])(4) = ${f([2,1,1,1,53,2])(4)}
         f([2,2,2,2])(4) = ${f([2,2,2,2])(4)}
               f([3])(3) = ${f([3])(3)}
              f([])(-43) = ${f([])(-43)}
     f([1,2,3,4,5,6])(3) = ${f([1,2,3,4,5,6])(3)}`
```

```
pre{font-size:14px;line-height:1.75}
```

```
<pre id=o>
```
> 3 votes

# Answer
# Haskell, ~~39 37~~ 36 bytes

```
(a:t)#n=n`elem`map(a+)t||t#n
_#n=1<0

```

Try it online! Example usage: `[1,3,2,5] # 3`. Returns `True` or `False`.

---

**Alternative** (also 36 bytes)

```
f(a:t)=map(a+)t++f t
f e=e
(.f).elem

```
> 3 votes

# Answer
# C, ~~114~~ 113 bytes

```
i,j,k="F";main(c,v)char**v;{for(--c;++i<c;)for(j=0;++j<c;)k=j^i&atoi(v[i])+atoi(v[j])==atoi(v[c])?"T":k;puts(k);}

```

Here's the output

```
C:\eng\golf>a.exe 3 4 5 6
F
C:\eng\golf>a.exe 1 2 3 4 5 6 11
T
C:\eng\golf>a.exe 4 23 8174 42 -1 41
T
C:\eng\golf>a.exe 1 1 1 1 1 3
F
C:\eng\golf>a.exe 2 1 1 1 53 2 4
T
C:\eng\golf>a.exe 2 2 2 2 4
T

```
> 3 votes

# Answer
# Ruby, ~~59~~ ~~53~~ 37 bytes

inspiration comes from this answer

```
->a,b{a.map{|e|a.include?(b-e)}.any?}

```

will now look where can I chop a few bytes -))

**HISTORY**

```
#53 bytes
->a,b{a.combination(2).map{|e|e.reduce(&:+)==b}.any?}

#59 bytes
->a,b{a.combination(2).map{|e|e.reduce(&:+)}.any?{|x|x==b}}

```
> 2 votes

# Answer
## PHP (\>= 7.1), ~~53~~ ~~51~~ ~~50~~ 46 Bytes

```
<?foreach($_GET[0]as$c)+$$c||${$_GET[1]-$c}=a;

```

sadly it's quite big but at least better than 2 loops. `+a` fails with a warning if the sum can be made =\> non empty output =\> *truthy*. Outputs nothing if the sum can not be made =\> *falsey*.

Thanks @user63956 !
> 2 votes

# Answer
# TAESGL, 8 bytes

```
Ş⇒AĨB-AĖ

```

**Interpreter**

**Explanation**

```
Ş⇒        Array.some with anonymous function on implicit input
  AĨ      first input includes
    B-    second input minus
      AĖ  first input popped

```
> 2 votes

# Answer
## Clojure, 53 bytes

```
#(loop[[v & r]%](if v(or((set r)(- %2 v))(recur r))))

```

Uses destructuring to take the first and rest of the input list (and subsequent `recur` of rest), and returns the number "target - value1" if found in the set of remaining numbers (a "truthy"), nil otherwise.
> 2 votes

# Answer
# Java 7, 138 bytes

```
boolean c(int[]a,int s){String r="";for(int l=a.length,i=0,j;i<l;i++)for(j=-1;++j<l;)if(i!=j)r+=(a[i]+a[j])+",";return r.contains(s+",");}

```

**Explanation:**

```
boolean c(int[]a,int s){             // Method with integer-array and integer parameters and boolean return-type
  String r="";                       // Temp String
  for(int l=a.length,i=0,j;i<l;i++)  //  Loop (1) over the input array
    for(j=-1;++j<l;)                 //   Inner loop (2) over the input array again
      if(i!=j)                       //    If the index of both loops aren't equal (so not the same item in the list)
        r+=(a[i]+a[j])+",";          //     Append the sum with a comma to the temp-String
                                     //   End of loop (2) (implicit / single-line body)
                                     //  End of loop (1) (implicit / single-line body)
  return r.contains(s+",");          //  Return whether the temp-String contains the given sum (+ comma)
}                                    // End of method

```

**Test code:**

Try it here.

```
class M{
  static boolean c(int[]a,int s){String r="";for(int l=a.length,i=0,j;i<l;i++)for(j=-1;++j<l;)if(i!=j)r+=(a[i]+a[j])+",";return r.contains(s+",");}

  public static void main(String[] a){
    System.out.println(c(new int[]{1,2,3,4,5,6},11));
    System.out.println(c(new int[]{4,23,8174,42,-1},41));
    System.out.println(c(new int[]{2,1,1,1,53,2},4));
    System.out.println(c(new int[]{2,2,2,2},4));
    System.out.println();
    System.out.println(c(new int[]{1,1,1,1,1,3},3));
    System.out.println(c(new int[]{3,4,5},6));
  }
}

```

**Output:**

```
true
true
true
true

false
false

```
> 2 votes

# Answer
## Mathematica, 38 bytes

```
MemberQ[Total/@#~Permutations~{2},#2]&

```

input style \[{1,2,3,4,5,6},11\]
> 1 votes

# Answer
# R, 32 bytes

```
function(x,l)x%in%combn(l,2,sum)

```

Returns an anonymous function. `combn` returns all combinations of `l` taken `m` at a time, in this case 2, and then optionally applies a function, in this case `sum`. Returns an empty logical vector `logical(0)` for an empty first input, which I define for this problem as falsey, and `TRUE` or `FALSE` corresponding to the other elements otherwise.

Try it online!
> 1 votes

# Answer
# Python 3, 41 bytes

```
f=lambda a,b,*c:a-b in c or c and f(a,*c)

```

Try it online!
Recursive aproach with *flexible* input and output. Returns an empty set as falsy.
> 1 votes

# Answer
# MATLAB, 28 bytes

```
@(a,b)any(pdist(a,@plus)==b)

```

This defines an anonymous function with inputs `a`: column vector (possibly empty); `b`: number.

The code also works in Octave except if the first input is empty, which causes an error. **Try it online!**

### Explanation

`pdist(a,@fun)` applies function `fun` (in our case, addition) to each combination of two rows of the input matrix `a` (in our case, a column vector). The output is a column vector. `any(...==b)` gives true if any of the results equals the input number `b`.
> 1 votes

# Answer
# Pyth - 9 bytes

```
/msd.cE2E

```

Try it

```
/msd.cE2E
    .cE2     # All subsets of length 2
 msd         # The sum of each subset
/       E    # Number of occurrences of the input number

```
> 1 votes

# Answer
# Axiom, ~~90~~ 92 bytes

```
f(a,k)==(for i in 1..#a-1 repeat for j in i+1..#a repeat(q:=a.i+a.j;q=k=>return true);false)

```

test

```
(42) -> f([3,4,5],6)
   (42)  false
                                                            Type: Boolean
(43) -> f([1,2,3,4,5,6],11)
   (43)  true
                                                            Type: Boolean
(44) -> f([4,23,8174,42,-1],11)
   (44)  false
                                                            Type: Boolean
(45) -> f([4,23,8174,42,-1],41)
   (45)  true
                                                            Type: Boolean
(46) -> f([2,23,8174,42,2],2)
   (46)  false

```
> 0 votes

# Answer
# Python 2, 71 bytes

```
from itertools import*
lambda L,n:n in map(sum,list(combinations(L,2)))

```

**Try it online**

Yes, I know there is already a better solution posted.
> 0 votes

# Answer
## C#, ~~96~~ 90 bytes

```
using System.Linq;a=>n=>Enumerable.Range(0,a.Count).Any(i=>a.Skip(i+1).Any(j=>a[i]+j==n));

```

Compiles to a `Func<List<int>, Func<int, bool>>`. Formatted version:

```
Func<List<int>, Func<int, bool>> f = a => n =>
    Enumerable.Range(0, a.Count).Any(i => a.Skip(i + 1).Any(j => a[i] + j == n));

```

Old `for` loop version for 96 bytes:

```
a=>n=>{for(int i=0,j,l=a.Count;i<l;++i)for(j=i+1;j<l;)if(a[i]+a[j++]==n)return 1>0;return 1<0;};

```
> 0 votes

# Answer
## C#, ~~103~~ 102 bytes

---

### Data

* **Input** `Int32[]` `l` A list of `Int32` to sum
* **Input** `Int32` `r` The result to check against
* **Output** `Boolean` A result indicating if the sum can be performed

---

### Golfed

```
(int[] l,int r)=>{for(int x=l.Length,y;--x>=0;)for(y=0;y<x;)if(l[x]+l[y++]==r)return 1>0;return 0>1;};

```

---

### Ungolfed

```
( int[] l, int r ) => {
   for( int x = l.Length, y; --x >= 0; )
      for( y = 0; y < x; )
         if( l[ x ] + l[ y++ ] == r )
            return 1 > 0;

   return 0 > 1;
};

```

---

### Ungolfed readable

*`Working on it...`*

---

### Full code

```
using System;
using System.Collections.Generic;

namespace Namespace {
   class Program {
      static void Main( String[] args ) {
        Func<Int32[], Int32, Boolean> f = ( int[] l, int r ) => {
            for( int x = l.Length, y; --x >= 0; )
                for( y = 0; y < x; )
                    if( l[ x ] + l[ y++ ] == r )
                        return 1 > 0;

            return 0 > 1;
        };

        List<KeyValuePair<Int32[], Int32>>
            testCases = new List<KeyValuePair<Int32[], Int32>>() {
                new KeyValuePair<Int32[], Int32>( new Int32[] { 3, 4, 5 }, 6 ),
                new KeyValuePair<Int32[], Int32>( new Int32[] { 1, 2, 3, 4, 5, 6 }, 11 ),
                new KeyValuePair<Int32[], Int32>( new Int32[] { 4, 23, 8174, 42, -1 }, 41 ),
                new KeyValuePair<Int32[], Int32>( new Int32[] { 1, 1, 1, 1, 1, 3 }, 3 ),
                new KeyValuePair<Int32[], Int32>( new Int32[] { 2, 1, 1, 1, 53, 2 }, 4 ),
                new KeyValuePair<Int32[], Int32>( new Int32[] { 2, 2, 2, 2 }, 4 ),
                new KeyValuePair<Int32[], Int32>( new Int32[] { 3 }, 3 ),
                new KeyValuePair<Int32[], Int32>( new Int32[] {  }, -43 ),
            };

        foreach( var testCase in testCases ) {
            Console.WriteLine( $" Input: {testCase.Value}; {{ {String.Join(", ", testCase.Key)} }}\nOutput: {f( testCase.Key, testCase.Value )}\n" );
        }

         Console.ReadLine();
      }
   }
}

```

---

### Releases

* **v1.1** \- `-1 byte` \- Thanks to TheLethalCoder suggestion.
* **v1.0** \- `103 bytes` \- Initial solution.

---

### Notes

* None
> 0 votes

# Answer
# AWK, 77 bytes

```
{for(s=i=0;++i<NF;)for(j=0;++j<NF;){if(i==j)continue
if($i+$j==$NF)s=1}$0=s}1

```

Try it online!

I could save 2 bytes by removing the `i=` in the `for(s=i=0...)`, but then it would only work for one line of data. Since this isn't the shortest answer, I thought I'd make a general solution :)

Input is whitespace separated numbers with the last value being the desired sum.
> 0 votes

# Answer
# Jellyfish, 13 bytes

```
p
cd!i
i 2
 1

```

Try it online!

## How it works

```
print(exists(i,from_base(1,permutations(i,2)))

```

where `i` are the inputs.
> 0 votes

---
Tags: code-golf, arithmetic, array, decision-problem
---


title: KOTH: Hit and Sunk

text:
# Question
Title: KOTH: Hit and Sunk
# Introduction

For my 5th KOTH, I present to you a challenge based on the well-known game Battleship with a few twists. You'll only command one ship, whose type you'll be able to select between the 5 "traditionnal" classes, but you'll be able to undertake multiple actions each turn, including moving! This is played as a FFA (Free For All) and your goal will be to be the last ship standing.

# Principle

The game is turn-based. At the start of the game, you'll have to choose the class of your ship. Then each turn, players will be able to execute several actions depending on their ship.

The game takes place on a 2D grid (X, Y) whose side is defined this way :
`X = 30 + numberOfPlayer`
`Y = 30 + numberOfPlayer`
The starting position of each ship is random.

Play order is randomized each turn, and you won't know your position in the "queue" nor the number of players. The game lasts for **100 turns** or until there's only one ship left alive.

Each time you hit an enemy ship or get hit, you'll earn or lose points. The player with the highest score wins. A bounty will be awarded to the winner (value depending on the number of participants).

The controller provides you with input via command arguments, and your program has to output via stdout.

# Syntax

***First Turn***

Your program will be called **once** without any argument. You'll have to ouput an integer between 1 and 5 (inclusive) to select your ship :

`1` : Destroyer \[length: 2, moves/turn: 3, shots/turn: 1, range: 9, mines: 4\]
*Skill* : Free ship rotations (no cooldown)

`2` : Submarine \[length: 3, moves/turn: 2, shots/turn: 1, range: 5, mines: 4\]
*Skill* : Can Plunge/Surface (see outputs). While underwater, you can only use "Movement" actions and can be seen only with a scan. You can't be hit by a shot, but can take damage from mines.

`3` : Cruiser \[length: 3, moves/turn: 1, shots/turn: 2, range: 9, mines: 2\]
*Skill* : Can Repair (see outputs)

`4` : Battleship \[length: 4, moves/turn: 1, shots/turn: 3, range: 7, mines: 1\]
*Skill* : Can Shield (see outputs)

`5` : Carrier \[length: 5, moves/turn: 1, shots/turn: 1, range: 7, mines: 3\]
*Skill* : Shots deal AOE (Area Of Effect) damage to target (1 range splash damage). If the target is hit with the shot, up to 2 cells of **this** ship will also be damaged.

***Turns***

**Input**

Each time your program is called, it will receive arguments in this format:

`Round;YourPlayerId;X,Y,Direction;Hull;Moves,Shots,Mines,Cooldown;Hits,Sunken,Damage;Underwater,Shield,Scan;Map`

Rounds are 1-indexed.

**Example input**

```
1;8;1,12,0;111;1,2,2,0;0,0,0;0,0,0;UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUXXXX.......UUUUUUUUXXXX.......UUUUUUUUXXXX.......UUUUUUUUXXXX.......UUUUUUUUXXXX.......UUUUUUUUXXXX.O.....UUUUUUUUXXXX.O.....UUUUUUUUXXXX.O.....UUUUUUUUXXXX.......UUUUUUUUXXXX.......UUUUUUUUXXXX.......UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU

```

Here, it's the 1st round, you're player 8.
Your ship is positioned on (X = 1, Y = 12) and your direction is toward the top (0 = Top, 1 = Right, 2 = Bottom, 3 = Left).
Your hull is not damaged (your ship has a length of 3, and each bit is true \[1 = OK, 0 = Damaged\]). You can move 1 time, shoot 2 times, have 2 mines left and your "skill" is available (cooldown = 0).
You didn't hit anything, nor have sunken any ship and you didn't get hit either.
You're not underwater, your shields (if any) are not activated and your scan isn't either.
More on the map later...

**Output**

You have to output a String describing what actions you'll execute this turn. The order of the characters in your output String will define the orders of the actions. You can output the same actions multiple times if it doesn't exceed the limits of your ship. If one or multiple actions is invalid, each one will separately be considered as `W`. Here's the list of available actions :

`M` : Move 1 cell in the direction you're facing (consume 1 move)
`B` : Back 1 cell from the direction you're facing (consume 1 move)
`C` : Rotate your ship clockwise (consume 1 move / free for Destroyers)
`K` : Rotate your ship counterclockwise (consume 1 move / free for Destroyers)
`A` : Ram your ship in the direction you're facing (works only if another ship is occupying the cell in the direction you're facing / doesn't move your ship / consume all moves)
`F` : Fire 1 shot to a cell in range (consume 1 shot). Must be followed by the targetted cell in this format (\[+-\]X\[+-\])Y / example : `F+2-3`)
`N` : Place 1 mine to a cell adjacent to your ship (consume all shots and 1 mine). Must be followed by the targetted cell in this format (\[+-\]X\[+-\])Y / example : `N+0+1`)
`S` : Activate your scan for the next turn (consume all shots)
`R` : Repair the damaged hull the closest to the "head" of your ship (consume all shots, cooldown = 3 turns / Cruiser only)
`P` : Plunge/Surface (consume all shots, cooldown = 3 turns, max duration = 5 turns / Submarine only)
`D` : Activate your shield preventing the next damage during your next turn (consume all shots, cooldown = 3 / Battleship only)
`W` : Wait (does nothing)

*Clarification*: "Consume all moves/shots" means you can only use this action if you have not used any of your moves/shots before during this turn.

**Example output**

`MF+9-8CM` : Moves 1 cell, then fires on the cell whose relative position to the "head" of your ship is (targetX = X + 9, targetY = Y - 8), turns clockwise and finally moves 1 cell again.

# Gameplay

**The Grid**

Here's an example grid (33 x 13) where 3 players are placed :

```
███████████████████████████████████
█                                 █
█       00                        █
█   2                             █
█   2                             █
█   2                             █
█                                 █
█       11111                     █
█        M                        █
█                                 █
█                                 █
█                                 █
█                                 █
█                                 █
███████████████████████████████████

```

As we can see, there's also a Mine `M` right next to the player 1.

Let's take player 2 to understand positioning and direction :

Player 2's position is X = 3, Y = 4, Direction = 3. Since its direction is "Bottom", the rest of his "ship cells" are positioned "over" its "head" (X = 3, Y = 3) & (X = 3, Y = 2)

**Player's map**

The last argument each players receive is their "own" map. By default a ship detects everything in a **range of 5 cells**, but it can activate a **Scan** to increase this range to **9**.

The argument is always 361 (19 x 19) characters long. It represents the square centered around the "head" of your ship, where each character corresponds to an element defined this way :

`.` : Empty cell
`O` : Your ship
`M` : Mines
`X` : Wall (cells out of the map)
`U` : Unknown (will be revealed by a scan)
`A` : Enemy ship undamaged cell
`B` : Enemy ship damaged cell
`C` : Enemy ship underwater undamaged cell (only seen with a scan)
`D` : Enemy ship underwater damaged cell (only seen with a scan)
`W` : Wreckage (dead ship)

The string is composed of 19 characters of the first line, followed by 19 charcters of the second lines ... until the 19th line.

Lets take a look at what player 2 receives with and without a scan (line breaks for better understanding, but not send to players) :

```
XXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXX
XXXXXX.............
XXXXXX.......AA....
XXXXXX...O.........
XXXXXX...O.........
XXXXXX...O.........
XXXXXX.............
XXXXXX.......AAAAA.
XXXXXX........M....
XXXXXX.............
XXXXXX.............
XXXXXX.............
XXXXXX.............
XXXXXX.............
XXXXXXXXXXXXXXXXXXX

UUUUUUUUUUUUUUUUUUU
UUUUUUUUUUUUUUUUUUU
UUUUUUUUUUUUUUUUUUU
UUUUUUUUUUUUUUUUUUU
UUUUXXXXXXXXXXXUUUU
UUUUXX.........UUUU
UUUUXX.......AAUUUU
UUUUXX...O.....UUUU
UUUUXX...O.....UUUU
UUUUXX...O.....UUUU
UUUUXX.........UUUU
UUUUXX.......AAUUUU
UUUUXX........MUUUU
UUUUXX.........UUUU
UUUUXX.........UUUU
UUUUUUUUUUUUUUUUUUU
UUUUUUUUUUUUUUUUUUU
UUUUUUUUUUUUUUUUUUU

```

**Mines**

The mines are triggered when a ship moves to a cell occupied by a mine or when a shot is fired on the mine. Mines can't be triggered with the action "Ram".

Mines deal AOE damage (1 range splash damage) to everyone, even to the person who placed the mine. Mines can trigger "chain" explosions if another mine is in the radius of the explosion.

**Rotations**

The rotations are central symmetries centered on the ship's "head". Rotations will only trigger a mine if it is placed on the "destination position" (you won't trigger mines in an arc.

**Area of effect**

1 range splash damage (for mines and Carrier's shots) is defined by a 3x3 (9 cells) square centered on the initial shot/explosion (x, y). It hits those coordinates : `[x - 1; y - 1],[x - 1; y],[x - 1; y + 1],[x; y - 1],[x; y],[x; y + 1],[x + 1; y - 1],[x + 1; y],[x + 1; y + 1]`

# Scoring

The scoring is defined by this formula :
`Score = Hits + (Sunken x 5) - Damage taken - (Alive ? 0 : 10)`

where :
`hits` : number of hits on enemy ship, either by Ram, Shot or Mine explosion (1 hit by enemy ship cell damaged, including chain explosions)
`sunken` : number of "last hit" on an enemy ship which caused it to sink
`damage` : number of hits received (not decreased by Repair, but prevented by Shield)
`alive` : checks wether your ship is alive at the end (at least 1 hull cell undamaged)

# Controller

You can find the controller on GitHub. It also contains two samplebots, written in Java. To make it run, check out the project and open it in your Java IDE. The entry point in the main method of the class Game. Java 8 required.

To add bots, first you need either the compiled version for Java (.class files) or the sources for interpreted languages. Place them in the root folder of the project. Then, create a new Java class in the players package (you can take example on the already existing bots). This class must implement Player to override the method String getCmd(). The String returned is the shell command to run your bots. You can for example make a Ruby bot work with this command : return "C:\Ruby\bin\ruby.exe MyBot.rb";. Finally, add the bot in the players array at the top of the Game class.

# Rules

* Bots should not be written to beat or support specific other bots.
* Writing to files is allowed. Please write to"yoursubmissionname.txt", the folder will be emptied before a game starts. Other external resources are disallowed.
* Your submission has 1 second to respond.
* Provide commands to compile and run your submissions.
* You can write multiple submissions

# Supported Languages

I'll try and support every language, but it needs to be available online for free. Please provide instructions for installation if you're not using a "mainstream" language.

As of right now, I can run : Java 6-7-8, PHP, Ruby, Perl, Python 2-3, Lua, R, node.js, Haskell, Kotlin, C++ 11.

# Answer
> 3 votes
# RandomBot

This is an example bot. It chooses a ship, an action and a target cell (if needed) randomly.

```
import java.util.Random;

public class RandomBot {

    int round;
    int playerID;

    public static void main(String[] args) {

        if (args.length == 0) {
            Random random = new Random();
            int ship = random.nextInt(5);
            String[] ships = { "1", "2", "3", "4", "5" };
            System.out.println(ships[ship]);
        } else {
            new RandomBot().play(args[0].split(";"));
        }
    }

    private void play(String[] args) {

        round = Integer.parseInt(args[0]);
        playerID = Integer.parseInt(args[1]);

        String[] actions = { "M", "B", "C", "K", "F", "S", "N", "A" };
        Random random = new Random();
        int action = random.nextInt(8);

        int rangeX = random.nextInt(5);
        int rangeY = random.nextInt(5);
        int mineX = random.nextInt(1);
        int mineY = random.nextInt(1);

        String signX = random.nextInt(1) == 1 ? "+" : "-";
        String signY = random.nextInt(1) == 1 ? "+" : "-";

        System.out.println(actions[action] + (action == 4 ? signX + rangeX + signY + rangeY : "") + (action == 6 ? signX + mineX + signY + mineY : ""));
    }

}

```

# PassiveBot

This is an example bot. It does nothing.

```
public class PassiveBot {

    int round;
    int playerID;

    public static void main(String[] args) {

        if (args.length == 0) {
            System.out.println("5");
        } else {
            new PassiveBot().play(args[0].split(";"));
        }
    }

    private void play(String[] args) {

        round = Integer.parseInt(args[0]);
        playerID = Integer.parseInt(args[1]);

        System.out.println("W");
    }

}

```

# Answer
> 3 votes
# PeaceMaker, Python 2 (Battleship)

PeaceMaker shoots 3 times on the nearest enemies (spiral distance) and moves back and forth in a line while staying at least 2 cells away from mines.

```
from os import sys

def reversedSpiralOrder(length):

    #Initialize our four indexes
    top = 0
    down = length - 1
    left = 0
    right = length - 1
    result = ""

    while 1:

        # Print top row
        for j in range(left, right + 1):
            result += str(top * length + j) + ";"
        top += 1
        if top > down or left > right:
            break

        # Print the rightmost column
        for i in range(top, down + 1):
            result += str(i * length + right) + ";"
        right -= 1
        if top > down or left > right:
            break

        # Print the bottom row
        for j in range(right, left + 1, -1):
            result += str(down * length + j) + ";"
        down -= 1
        if top > down or left > right:
            break

        # Print the leftmost column
        for i in range(down, top + 1, -1):
            result += str(i * length + left) + ";"
        left += 1
        if top > down or left > right:
            break

    result = result.split(";")
    del result[-1]
    return result[::-1]

def canMove(x, y, direction, hull, map):

    # M = 1, B = 2
    moves = 0

    if direction == 0:
        y1 = -1
        y2 = -2
        hx1 = hx2 = x1 = x2 = 0
        hy1 = -y1 + hull
        hy2 = -y2 + hull
    elif direction == 1:
        x1 = 1
        x2 = 2
        hy1 = hy2 = y1 = y2 = 0
        hx1 = -x1 - hull
        hx2 = -x2 - hull
    elif direction == 2:
        y1 = 1
        y2 = 2
        hx1 = hx2 = x1 = x2 = 0
        hy1 = -y1 - hull
        hy2 = -y2 - hull
    elif direction == 3:
        x1 = -1
        x2 = -2
        hy1 = hy2 = y1 = y2 = 0
        hx1 = -x1 + hull
        hx2 = -x2 + hull

    if map[y + y1][x + x1] == "." and map[y + y2][x + x2] != "M":
        moves += 1

    if map[y + hy1][x + hx1] == "." and map[y + hy2][x + hx2] != "M":
        moves += 2

    return moves

if len(sys.argv) <= 1:
    f = open("PeaceMaker.txt","w")
    f.write("")
    print "4"
else:
    arguments = sys.argv[1].split(";")
    sight = 19

    round = int(arguments[0])
    playerID = int(arguments[1])
    x = int(arguments[2].split(",")[0])
    y = int(arguments[2].split(",")[1])
    direction = int(arguments[2].split(",")[2])
    hull = arguments[3]
    moves = int(arguments[4].split(",")[0])
    shots = int(arguments[4].split(",")[1])
    mines = int(arguments[4].split(",")[2])
    cooldown = int(arguments[4].split(",")[3])
    hits = int(arguments[5].split(",")[0])
    kills = int(arguments[5].split(",")[0])
    taken = int(arguments[5].split(",")[0])
    underwater = int(arguments[6].split(",")[0])
    shield = int(arguments[6].split(",")[1])
    scan = int(arguments[6].split(",")[2])
    map = [[list(arguments[7])[j * sight + i] for i in xrange(sight)] for j in xrange(sight)]

    initialShots = shots

    priorities = reversedSpiralOrder(sight)

    actions = ""
    sighted = 0
    for priority in priorities:
        pX = int(priority) % sight
        pY = int(priority) / sight

        if map[pY][pX] == "A":
            sighted += 1
            if shots > 0:
                shots -= 1
                actions += "F" + ("+" if pX - 9 >= 0 else "") + str(pX - 9)  + ("+" if pY - 9 >= 0 else "") + str(pY - 9)

    if shots == initialShots and sighted > 0:
        actions += "D"
    elif shots == initialShots and sighted <= 0:
        actions += "S"
    else:
        actions += ""

    f = open("PeaceMaker.txt","r")
    fC = f.read(1)
    lastDirection = int("1" if fC == "" else fC)

    y = 9
    x = 9

    if lastDirection == 1:
        if canMove(x, y, direction, len(hull), map) == 1 or canMove(x, y, direction, len(hull), map) == 3:
            actions += "M"
        elif canMove(x, y, direction, len(hull), map) == 2:
            actions += "B"
            lastDirection = 0
    elif lastDirection == 0:
        if canMove(x, y, direction, len(hull), map) == 2 or canMove(x, y, direction, len(hull), map) == 3:
            actions += "B"
        elif canMove(x, y, direction, len(hull), map) == 1:
            actions += "M"
            lastDirection = 1

    f = open("PeaceMaker.txt","w")
    f.write(str(lastDirection))

    print actions

```

---
Tags: king-of-the-hill
---