title: Fibonacci Spiral

text:
# Question
Title: Fibonacci Spiral
Your goal is to generate a Fibonacci spiral with numbers.

### Example Input / Output

```
1 -> 1

2 -> 1 1

3 -> 1 1
     2 2
     2 2

6 -> 8 8 8 8 8 8 8 8 5 5 5 5 5
     8 8 8 8 8 8 8 8 5 5 5 5 5
     8 8 8 8 8 8 8 8 5 5 5 5 5
     8 8 8 8 8 8 8 8 5 5 5 5 5
     8 8 8 8 8 8 8 8 5 5 5 5 5
     8 8 8 8 8 8 8 8 1 1 3 3 3
     8 8 8 8 8 8 8 8 2 2 3 3 3
     8 8 8 8 8 8 8 8 2 2 3 3 3

```

Input of 9

**Input** The input can be taken through STDIN or function argument. It will be a single number

**Output** The output can be from STDOUT or a function's return value. It should be a single string.

Extra whitespace at the very end of the line is not allowed. The output can contain digits, linefeeds (newlines), and spaces.

Orientation does not matter, this means rotations and reflections. As long as it follows a valid Fibonacci spiral pattern.

Numbers with different amounts of digits (e.g. 1 and 13) should be right-aligned with each other. A space may need to be added to the very beginning of a line so everything can line up.

```
1   1                          1   1
100 100  should actually be  100 100

```

You can see an example here

---

This is so shortest code in bytes wins!

# Answer
> 15 votes
## APL, 23

```
{a,⍴⍨2⍴⊃⍴a←⌽⍉⍵}⍣(⎕-1)⍪1

```

Explanation:

```
⍪1               this creates a 1x1 matrix containing just 1
{..}⍣(⎕-1)     the power operator (⍣) repeats the function {} user input - 1 times
a,⍴⍨2⍴⊃⍴a←⌽⍉⍵   the function being iterated rotates the matrix and appends the next matrix to it.

```

Try it on tryapl.org

# Answer
> 8 votes
# Matlab, 84 bytes

A function is used. Output is in stdout.

```
function f(N)
s=0;t=1;y=1;for n=2:N
u=s+t;s=t;t=u;y=[rot90(y) t*ones(t)];end;disp(y)

```

Examples:

```
>> f(1)
     1
>> f(2)
     1     1
>> f(3)
     1     2     2
     1     2     2
>> f(6)
     5     5     5     5     5     8     8     8     8     8     8     8     8
     5     5     5     5     5     8     8     8     8     8     8     8     8
     5     5     5     5     5     8     8     8     8     8     8     8     8
     5     5     5     5     5     8     8     8     8     8     8     8     8
     5     5     5     5     5     8     8     8     8     8     8     8     8
     3     3     3     1     1     8     8     8     8     8     8     8     8
     3     3     3     2     2     8     8     8     8     8     8     8     8
     3     3     3     2     2     8     8     8     8     8     8     8     8
>> f(7)
     8     8     8     8     8     8     8     8    13    13    13    13    13    13    13    13    13    13    13    13    13
     8     8     8     8     8     8     8     8    13    13    13    13    13    13    13    13    13    13    13    13    13
     8     8     8     8     8     8     8     8    13    13    13    13    13    13    13    13    13    13    13    13    13
     8     8     8     8     8     8     8     8    13    13    13    13    13    13    13    13    13    13    13    13    13
     8     8     8     8     8     8     8     8    13    13    13    13    13    13    13    13    13    13    13    13    13
     8     8     8     8     8     8     8     8    13    13    13    13    13    13    13    13    13    13    13    13    13
     8     8     8     8     8     8     8     8    13    13    13    13    13    13    13    13    13    13    13    13    13
     8     8     8     8     8     8     8     8    13    13    13    13    13    13    13    13    13    13    13    13    13
     5     5     5     5     5     1     2     2    13    13    13    13    13    13    13    13    13    13    13    13    13
     5     5     5     5     5     1     2     2    13    13    13    13    13    13    13    13    13    13    13    13    13
     5     5     5     5     5     3     3     3    13    13    13    13    13    13    13    13    13    13    13    13    13
     5     5     5     5     5     3     3     3    13    13    13    13    13    13    13    13    13    13    13    13    13
     5     5     5     5     5     3     3     3    13    13    13    13    13    13    13    13    13    13    13    13    13

```

## Matlab, 78 bytes

```
function y=f(N)
s=0;t=1;y=1;for n=2:N
u=s+t;s=t;t=u;y=[rot90(y) t*ones(t)];end

```

Same as above except a Matlab's feature is exploited, namely, it automatically displays function output (as a string) in stdout. This avoids the conversion to string in the above approach.

```
f(6)
ans =
     5     5     5     5     5     8     8     8     8     8     8     8     8
     5     5     5     5     5     8     8     8     8     8     8     8     8
     5     5     5     5     5     8     8     8     8     8     8     8     8
     5     5     5     5     5     8     8     8     8     8     8     8     8
     5     5     5     5     5     8     8     8     8     8     8     8     8
     3     3     3     1     1     8     8     8     8     8     8     8     8
     3     3     3     2     2     8     8     8     8     8     8     8     8
     3     3     3     2     2     8     8     8     8     8     8     8     8

```

# Answer
> 7 votes
# Ruby, ~~243~~ ~~242~~ ~~236~~ ~~233~~ ~~222~~ ~~170~~ 130 bytes

```
s,l,r=0,1,[]
gets.to_i.times{s+=l
l=s-l
s.times{r<<[s]*s}
r=r.transpose.reverse}
r.map{|w|puts w.map{|c|"%#{s.to_s.size}s"%c}*" "}

```

# Answer
> 7 votes
# Python 2, 121 bytes

```
a,b=0,1;L=[]
exec"a,b=b,a+b;L=zip(*L[::-1])+[[a]*a]*a;"*input()
for r in L:print" ".join("%*d"%(len(str(a)),x)for x in r)

```

The relaxed rules on rotations makes this a lot simpler.

I haven't used backticks in place of `str(a)` here because I'm not sure whether we're allowed more leading spaces than necessary, if we ever reach longs. Although, even if we were, using `a` itself would be shorter anyway.

# Answer
> 6 votes
# Python - ~~189~~ ~~179~~ 174

```
n=int(input())
f=[1,1]
while len(f)<n:f+=[f[-1]+f[-2]]
o=[[]]
for i in f:o=(list(zip(*o)))[::-1]+[[i]*i]*i
for x in o:print(' '.join(str(y).rjust(len(str(f[-1])))for y in x))

```

# Answer
> 6 votes
## Haskell, 183 176 171 163 bytes

```
import Data.List
s t=map((t>>[l t])++)t
e 1=[[1]];e n=s.reverse.transpose$e$n-1
f=g.e
g m=unlines$map(>>=((show$l m)#).show)m
a#b|l a<l b=b;a#b=a#(' ':b)
l=length

```

The function is `f`, which takes a number and returns a single string:

```
λ: putStr $ f 8
 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21  5  5  5  5  5  8  8  8  8  8  8  8  8
 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21  5  5  5  5  5  8  8  8  8  8  8  8  8
 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21  5  5  5  5  5  8  8  8  8  8  8  8  8
 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21  5  5  5  5  5  8  8  8  8  8  8  8  8
 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21  5  5  5  5  5  8  8  8  8  8  8  8  8
 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21  3  3  3  1  1  8  8  8  8  8  8  8  8
 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21  3  3  3  2  2  8  8  8  8  8  8  8  8
 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21  3  3  3  2  2  8  8  8  8  8  8  8  8
 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 13 13 13 13 13 13 13 13 13 13 13 13 13
 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 13 13 13 13 13 13 13 13 13 13 13 13 13
 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 13 13 13 13 13 13 13 13 13 13 13 13 13
 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 13 13 13 13 13 13 13 13 13 13 13 13 13
 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 13 13 13 13 13 13 13 13 13 13 13 13 13
 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 13 13 13 13 13 13 13 13 13 13 13 13 13
 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 13 13 13 13 13 13 13 13 13 13 13 13 13
 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 13 13 13 13 13 13 13 13 13 13 13 13 13
 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 13 13 13 13 13 13 13 13 13 13 13 13 13
 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 13 13 13 13 13 13 13 13 13 13 13 13 13
 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 13 13 13 13 13 13 13 13 13 13 13 13 13
 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 13 13 13 13 13 13 13 13 13 13 13 13 13
 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 13 13 13 13 13 13 13 13 13 13 13 13 13

```

# Answer
> 6 votes
# J, 36 bytes

```
1&(($~,~)@(1{$@]),.|:@|.@])&(,.1)@<:

```

Usage:

```
   (1&(($~,~)@(1{$@]),.|:@|.@])&(,.1)@<:) 6
8 8 8 8 8 8 8 8 5 5 5 5 5
8 8 8 8 8 8 8 8 5 5 5 5 5
8 8 8 8 8 8 8 8 5 5 5 5 5
8 8 8 8 8 8 8 8 5 5 5 5 5
8 8 8 8 8 8 8 8 5 5 5 5 5
8 8 8 8 8 8 8 8 1 1 3 3 3
8 8 8 8 8 8 8 8 2 2 3 3 3
8 8 8 8 8 8 8 8 2 2 3 3 3

```

Method:

The function rotates the current square and adds the new square to the current one `input-1` times. Square size and element values are gathered from the size of the previous rectangle.

Code explanation:

```
1&(           loop
    ($~,~)      new square with size and elements
    @(1{$@])    with the size of the second dimension of the current rectangle
    ,.          attached to
    |:@|.@]     rotated current rectangle
)&(,.1)       starting the loop with matrix 1
@<:           looping input-1 times

```

Try it online here.

# Answer
> 5 votes
# Pyth, 34 bytes

```
jbmsm.[hl`lhZ`k\ d=Zu+_CGmmlGGGQ]]

```

Surprisingly, more than half of the code is printing/padding, rather than generating the matrix.

The generation of the matrix is really simple however, it consists of a transpose and reversal, and adding N lines containing N copies of N, where N is the current number of lines.

Example output for 7:

```
  5  5  5  5  5  8  8  8  8  8  8  8  8
  5  5  5  5  5  8  8  8  8  8  8  8  8
  5  5  5  5  5  8  8  8  8  8  8  8  8
  5  5  5  5  5  8  8  8  8  8  8  8  8
  5  5  5  5  5  8  8  8  8  8  8  8  8
  3  3  3  1  1  8  8  8  8  8  8  8  8
  3  3  3  2  2  8  8  8  8  8  8  8  8
  3  3  3  2  2  8  8  8  8  8  8  8  8
 13 13 13 13 13 13 13 13 13 13 13 13 13
 13 13 13 13 13 13 13 13 13 13 13 13 13
 13 13 13 13 13 13 13 13 13 13 13 13 13
 13 13 13 13 13 13 13 13 13 13 13 13 13
 13 13 13 13 13 13 13 13 13 13 13 13 13
 13 13 13 13 13 13 13 13 13 13 13 13 13
 13 13 13 13 13 13 13 13 13 13 13 13 13
 13 13 13 13 13 13 13 13 13 13 13 13 13
 13 13 13 13 13 13 13 13 13 13 13 13 13
 13 13 13 13 13 13 13 13 13 13 13 13 13
 13 13 13 13 13 13 13 13 13 13 13 13 13
 13 13 13 13 13 13 13 13 13 13 13 13 13
 13 13 13 13 13 13 13 13 13 13 13 13 13

```

# Answer
> 4 votes
## Perl, ~~289 277~~ 257 bytes

```
@f=(0,1);push@f,$f[-1]+$f[-2]while(@f<=$ARGV[0]);$d=1+length$f[-1];shift@f;map{$v=$f[$_];$t=sprintf("%${d}d",$v)x$v;$_%4||map{unshift@s,$t}1..$v;$_%4==3&&map{$_.=$t}@s;$_%4==2&&map{push@s,$t}1..$v;$_%4==1&&map{$_=$t.$_}@s;}0..$#f;$\=$/;for(@s){s/^ //;print}

```

# Answer
> 4 votes
# K, 48 bytes

```
{{`0:1_',/'(1+#$|//x)$x}(x-1){+|x,\:t#t:#x}/,,1}

```

And in action:

```
  {{`0:1_',/'(1+#$|//x)$x}(x-1){+|x,\:t#t:#x}/,,1}7
 8  8  8  8  8  8  8  8  5  5  5  5  5
 8  8  8  8  8  8  8  8  5  5  5  5  5
 8  8  8  8  8  8  8  8  5  5  5  5  5
 8  8  8  8  8  8  8  8  5  5  5  5  5
 8  8  8  8  8  8  8  8  5  5  5  5  5
 8  8  8  8  8  8  8  8  1  1  3  3  3
 8  8  8  8  8  8  8  8  2  2  3  3  3
 8  8  8  8  8  8  8  8  2  2  3  3  3
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13
13 13 13 13 13 13 13 13 13 13 13 13 13

```

May still be some good opportunities for golfing.

The program basically consists of two parts- generating the concatenated matrix and formatting it for output. The former is fairly simple:

```
  {(x-1){+|x,\:t#t:#x}/,,1}5
(3 3 3 2 2
 3 3 3 2 2
 3 3 3 1 1
 5 5 5 5 5
 5 5 5 5 5
 5 5 5 5 5
 5 5 5 5 5
 5 5 5 5 5)

```

Beginning with a 1x1 matrix containing 1, build a T-length vector of T where T is the length of the starting matrix on the first dimension (`t#t:#x`) and attach that to each row of the original matrix (`x,\:`). Reversing and transposing the result (`+|`) rotates it 90 degrees. We do this N-1 times.

Formatting is pretty clunky, because K's natural approach to printing a matrix won't align number columns the way we need:

```
{`0:1_',/'(1+#$|//x)$x}

```

The basic idea is to take the maximum element of the matrix (`|//x`), convert it to a string (unary `$`), take its length plus one (`1+#`) and then format the elements of the matrix to right aligned strings of that size. Then to tidy up, join those strings (`,/'`) and drop the resulting leading space (`1_'`).

# Answer
> 4 votes
# CJam, 48 bytes

```
1saali({z{W%}%_0=,__sa*a*+}*_W=W=,):U;{USe[}f%N*

```

Try it online

The core part of generating the pattern seems reasonably straightforward. Rotate the rectangle created so far, and add a square of values at the bottom.

The code for padding the result looks awful, though. I tried a bunch of combinations of `f` and `:` operators to apply the padding to the nested list, but nothing worked. If anybody has better suggestions, they are most welcome.

```
1s    First value. Using string for values so that we can pad them in the end.
aa    Wrap it twice. Data on stack will be a list of lists (list of lines).
li    Get input.
(     Decrement, since we seeded the list at n=1.
{     Loop over n.
  z     Transpose...
  {W%}% ... and reverse all lines, resulting in a 90 degree rotation.
  _0=,  Get length of line, which is the size of square we need to add.
  __    Create two copies of size.
  sa    Convert one size to string, and wrap it in array.
  *     Replicate it size times. This is one line.
  a     Wrap the line...
  *     ... and replicate it size times. The square of new values is done.
  +     Add the list of lines to the previous list of lines.
}*    End of loop over n.
_W=W= Get last value produced.
,)    Take its length, and increment it. This is the output field width.
:U;   Store the field width in variable, and pop it. This is ugly.
{     Start of block applied to all values.
  U     Field width stored in variable.
  S     Space.
  e[    Pad left.
}f%   End of block applied to all values.
N*    Join lines with newline.

```

# Answer
> 2 votes
# Pyth, 29 bytes

```
Vu+C_GmmlGGGQ\]Yjdm.\[l`lN`d\ N

```

Demonstration.

If padding was free/implicit, like in APL, or matrix output was allowed, this would be 14 bytes:

```
u+C_GmmlGGGQ]Y

```

# Answer
> 2 votes
## Ruby, 129 bytes

I edited the other ruby answer a bunch, but my most recent change is not being accepted or something, so here it is:

```
s,r=0,[[1]]
gets.to_i.times{s+=r[0][0]
r=(r+[[s]*s]*s).transpose.reverse}
r.map{|w|puts w.map{|c|"%#{r[0][s].to_s.size}s"%c}*' '}

```

# Answer
> 1 votes
## ES6, 248 bytes

```
n=>(f=(n,o=n)=>Array(n).fill(o),g=n=>n<3?[f(n,1)]:(a=g(n-2)).reverse().concat(f(l=a[0].length,f(l))).map((e,i,a)=>f(a.length).concat(e.reverse())),a=g(n),s=' '.repeat(l=` ${a[0][0]}`.length),a.map(a=>a.map((e,i)=>(s+e).slice(!i-1)).join``).join`\n`)

```

Where `\n` represents a literal newline character.

Annoyingly the formatting takes up a large chunk of the code.

`f` is a helper function that makes a filled array. It's used mostly to create the filled squares but also handily doubles up to produce the base cases for the recursion.

`g` is the main gruntwork. It recursively generates the last but one solution, rotates it 180 degrees, then appends the next two squares.

---
Tags: code-golf, fibonacci
---


title: Tips for golfing in CoffeeScript

text:
# Question
Title: Tips for golfing in CoffeeScript
What tricks do you know to make CoffeeScript code shorter?

CoffeeScript is language that compiles into JavaScript ("transpiles" into ES3, to be exact). The golden rule is "It's just JavaScript", meaning there's no runtime overhead. Most of JavaScript Tips & Tricks apply as well.

As a side-effect that also means: developers coming from JavaScript (including myself) tend to use JavaScript constructs instead of shorter CoffeeScript alternatives.

**This thread focuses on tips specific to CoffeeScript.**

Links to related topics:

Tips for golfing in JavaScript

Tips for Golfing in ECMAScript 6 and above

# Answer
# Use destructuring assignments, if structure elements are used often

Eg. get elements of first argument array

```
func = ([x,y,z])->
    [i,j] = doSomething x, y, x+y
    doSomethingElse i, j

# instead of

func = (a)->
    b = doSomething a[0], a[1], a[0]+a[1]
    doSomethingElse b[0], b[1]

```

This can be combined with splats

```
[first, rest..., last] = doSmth()

```
> 3 votes

# Answer
## Short-circuit evaluation in place of ternary operator

CoffeeScript does not have JavaScript's ternary operator `?`, however the functionality of short-circuit evaluation can sometimes be used instead:

```
foo = a && b || c

# Long form:
foo = if a then b else c

```

Is somewhat equivalent to in JavaScript:

```
foo = a ? b : c

```

It will **not** work if b is (or can evaluate to) a falsy value such as `0`.
> 2 votes

# Answer
## Integer division operator `//`

Saves up to 10 bytes by avoiding the need to floor numbers when dividing.

Using the `//` operator:

```
foo = 61/3                 # foo = 20.333333333333332
foo = Math.floor 61/3      # foo = 20 (15 bytes)
foo = 61/3|0               # foo = 20 (6 bytes)
foo = 61//3                # foo = 20 (5 bytes)

```

Compared to JavaScript:

```
foo = 61/3                // foo = 20.333333333333332
foo = Math.floor(61/3)    // foo = 20 (16 bytes)
foo = 61/3|0              // foo = 20 (6 bytes)

```
> 2 votes

# Answer
# Space is fun. Space is significant for calling functions

```
a=b[i]  # get i-th element of array b
a=b [i] # a = b( [i] ) # pass [i] to function b

m=n+k   # simple math
m=n +k  # m = n( +k ) # convert k to number and pass to function n
m=n -k  # m = n( -k ) # pass -k to function n
m=n + k # simple math again

a(b c)+d   # a( b( c ) ) + d
a (b c)+d  # a( b( c ) + d )
a (b c) +d # a( b( c )( +d ) )

```
> 2 votes

# Answer
# Omit parentheses when possible

```
func1 func2 func3(a),func3 b

#instead of

func1(func2(func3(a),func3(b))

```
> 1 votes

# Answer
## Not `null` but possibly falsy (`0`, `NaN`, `""`, `false`, etc.)

If you need to check if a variable is defined and not `null`, use the trailing question mark:

```
alert 'Hello world!'if foo?

```

Compiles to:

```
if (typeof foo !== 'undefined' && foo !== null) {
    alert('Hello world!')
}

```

This probably won't apply to many code golf entries but might be useful if you need to distinguish from a zero, false, empty string, or other falsy value.
> 1 votes

# Answer
## Exponentiation operator `**`

Saves 9 bytes:

```
foo = 2**6
# foo = 64

```

Compared to JavaScript:

```
foo = Math.pow(2,6)
// foo = 64

```
> 1 votes

# Answer
## Searching arrays

Save approximately 8 bytes if you just want to check if an element is in an array, you can use the `in` operator.

```
y = x in['foo', 'bar', 'baz']

```

Compared to alternatives in JavaScript:

```
y = ~['foo', 'bar', 'baz'].indexOf(x)   // ES5, returns Number
y = ['foo', 'bar', 'baz'].includes(x)   // ES7, returns boolean
y = ~$.inArray(x,['foo', 'bar', 'baz']) // jQuery, returns Number

```

However in the rare case that you need the index of the element then this trick won't work for you.
> 1 votes

# Answer
# Use splats

```
obj.method a, params...

# instead of

obj.method.apply obj, [a].concat params

# especially useful with new objects

obj = new Obj a, params...

# alternative is complicated, unreadable and not shown here.

```
> 0 votes

# Answer
# Safe accessors: `?.` and `func? args...`

Existential operator `?` has many forms and uses. Apart from just checking if variable is set, you can access object methods and properties without prior checking if object is null:

```
obj.property?.method? args...

```

will execute `obj.property.method args...` only if `obj.property` and `obj.property.method` are defined and not null.

Useful if you iterate over several sparse arrays at the same time:

```
arr1[i]?.prop = arr2[i]?.method? args... for i in[0..99]

```
> 0 votes

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


# Question
Title: How do I alias member functions in Python?
In Python, one can save bytes by aliasing functions that are used repeatedly. For example:

```
r=range
a=r(100)
b=r(200)
c=r(300)

```

However, when the functions are member functions together, I don't know how to alias them in a way that allows chaining. For example:

```
s='Hello'

// Plain code
s=s.replace('H','J').replace('e','i').replace('l','m').replace('o','y')

// What I am trying to do
q=replace
s=s.q('H','J').q('e','i').q('l','m').q('o','y')

```

Obviously, what I am trying to do is not valid. And neither is this:

```
q=s.replace
s=q('H','J') // Replaces the 'H' in 'Hello'
s=q('e','i') // Replaces the 'e' in 'Hello'... and the J is gone.
s=q('l','m')
s=q('o','y')

```

Is there a another way to alias member functions and chained functions that saves characters?

# Answer
**No problemo!** You can alias a method, but you have to know how to use it:

```
>>> r=str.replace
>>> a='hello'
>>> r(r(r(r(a,'h','j'),'e','i'),'l','m'),'o','y')
'jimmy'

```

The key is that you have to pass `self` explicitly, because the alias is a kind of function that takes an extra argument that takes `self`:

```
>>> type(r)
<type 'method_descriptor'>

```
> 34 votes

# Answer
Define your own class, with a shorter method name.

For example, if you're using the method `replace()` belonging to the `String` class, you could make your own class `S` have a method called `q` which does the same thing.

Here is one implementation:

```
class m(str):
 def q(a,b,c):return m(a.replace(b,c))

```

Here is a much better implementation:

```
class m(str):q=lambda a,b,c:m(a.replace(b,c))

```

Use it like so:

```
s="Hello"
s=m(s).q('H','J').q('e','i').q('l','m').q('o','y')

```
> 6 votes

# Answer
This is a few characters shorter anyway

```
j=iter('HJeilmoy')
for i in j:s=s.replace(i,next(j))

```

even shorter for a small number of replacements is

```
for i in['HJ','ei','lm','oy']:s=s.replace(*i)

```

of course this just covers one particular case. However code golf is all about finding those special cases that can save you bytes.

It's possible to write a wrapper function that handles the general case, but the code will be too large to have a place in most code golf challenges.

You instead need to think "I can do this transformation efficiently (strokewise) with str.replace. Can I shift the internal representation of my solution to take advantage of that? (without wasting so many strokes to negate the advantage)"
> 5 votes

# Answer
You may use the `reduce` function.

```
reduce(lambda s,(a,b):s.replace(a,b),[('H','J'),('e','i'),('l','m'),('o','y')],'Hello')

```
> 4 votes

# Answer
If you're doing a *lot* of replaces, you could do this:

```
s=''.join({'H':'J','e':'i','l':'m','o':'y'}[a] for a in list(s))

```
> 2 votes

# Answer
How about defining a lambda function?

```
r=lambda s,a,b:s.replace(a,b)

s=r(r(r(r(s,'H','J'),'e','i'),'l','m'),'o','y')

```
> 1 votes

# Answer
If your replacements don't need to be chained, you can use \`str.translate'. The numbers are the ASCII ordinals. Using it this way requires Python 3:

```
print("Hello".translate({72:74,101:105,108:109,111:121}))

```

**Try it online**
> 1 votes

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


title: Are there brackets in disguise?

text:
# Question
Title: Are there brackets in disguise?
Someone's given us a string, but all bracket-like characters have been changed into normal ones, and we don't know which, or even how many there were. All we know is that if `L1,L2,L3,...,LN` were different kinds of left brackets and `R1,R2,R3,...,RN` were different corresponding kinds of right brackets, all being distinct (2N distinct bracket characters), a string would be valid iff it is one of (+ is normal string concatenation):

* `L1+X+R1`,`L2+X+R2`,...,`LN+X+RN`, where `X` is a valid string,
* `X+Y`, where `X` and `Y` are valid strings,
* Any single character that is not a bracket character.
* The empty string

We know they started out with a valid string before they changed the brackets, and they didn't change them into any characters that already existed in the string. At least one pair existed for each bracket as well. Can you reconstruct which characters were originally left and right bracket pairs (find the `Li` and `Ri` following the given conditions)?

Output the pairs of characters that were brackets. For example, if `(){}[]` were actually bracket characters, you might output `(){}[]` or `{}[]()` or `[](){}`, etc. There may be multiple ways to do this for a string, you only need to return one such that there is no bracket assignment with more pairs (see examples). Note that the output string should always have an even length.

Examples:

`abcc` \- `c` cannot be a bracket, since there is no other character with two occurrences, but `ab` can be a bracket pair, so you would output exactly `ab`.

`fffff` \- any string with at most one character cannot have brackets, so you would return the empty string or output nothing.

`aedbedebdcecdec` \- this string cannot have any brackets because there is 1 a, 2 bs, 3 cs, 4 ds, and 5 es, so no two characters occur the same number of times, which is a requirement to have brackets.

`abcd` \- possible assignments are `ab`, `cd`, `abcd`, `cdab`, `adbc`, `bcad`, `ac`, `ad`, `bc` and `bd`, (as well as the empty assignment, which all of them have) but you must return one of the longest assignments, so you must return `abcd`, `cdab`, `adbc`, or `bcad`.

`aabbcc`,`abc` \- these both have `ab`, `ac`, and `bc` as valid pairs. You must return one of these pairs, doesn't matter which.

`abbac` \- a and b have the same character count, but they can't actually work, since one of them occurs to both the left and right of all occurrences of the other. Return nothing.

`aabcdb` \- `cd` and `ab` are the exact two bracket pairs, so output either `cdab` or `abcd`.

`abcdacbd` \- only one pair can be achieved at once, but `ab`,`ac`,`bd`,`cd`, and `ad` are all of the possible pairs you can return. No matter which pair you choose, it has an instance where a single other character is within it, which prohibits any other pairs, except in the case of `ad`, where the other pairs `bc` and `cb` are not possible alone either, and so can't be possible with `ad`.

This is code golf, so shortest code in bytes wins. Input is from STDIN if possible for your language. If it isn't possible, indicate the input method in your answer.

# Answer
## Ruby, 373 bytes

```
i=gets.chomp
b=[*(i.chars.group_by{|x|x}.group_by{|x,y|y.size}.map{|x|s=x[1].size
x[1][0...s-s%2].map{|x|x[0]}*''}*'').chars.each_slice(2)]
puts [*[*b.size.downto(1).map{|n|b.combination(n).map{|t|[t*'',(h=Hash[t]
s=[]
o=1
i.each_char{|c|s.push(c)if h.keys.include?c
(o=false if s.empty?||!h[s.pop].eql?(c))if h.values.include?c}
o ?s.empty?: o)]}}.find{|x|x[0][1]}][0]][0]

```

This uses a golfed version of the stack parser here.

It can probably be simplified further, but I don't think my brain can handle any more.

**All test cases:** http://ideone.com/gcqDkK

**With whitespace:** http://ideone.com/pLrsHg

**Ungolfed (mostly):** http://ideone.com/oM5gKX
> 4 votes

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


title: The powerful connection

text:
# Question
Title: The powerful connection
# Introduction

There is a plantation defined by one big *square-board* like this one:

The numbers inside each small square represents its area's value/cash/...

The farmer needs help to find the *N* squares that connected *(it means all N squares should have at least one shared border)* give him the greatest value.

For example:

If `N=1`, then the output must be `140`.

If `N=6`, then..

..the output must be `315`.

# Challenge

Your program/function must take the the **matrix's values** and the number **N** as input/arguments and must output **the powerful connection**'s value.

Since this is , the shortest answer in bytes wins!

# Examples

Input:

```
10 -7 11 7 3 31
33 31 2 5 121 15
22 -8 12 10 -19 43
12 -4 54 77 -7 -21
2 8 6 -70 109 1
140 3 -98 6 13 20
6

```

Output: `315`

---

Input:

```
35 -7
-8 36
2

```

Output: `29`

# Answer
# JavaScript (ES6), 190 bytes

```
(m,n)=>m.map((a,r)=>a.map((_,c)=>f(r,c,[0],0)),o=f=(x,y,s,t)=>s[n]?o>t?0:o=t:s.indexOf(w=x+","+y)<0&&m[y]&&(v=m[y][x])<1/0&&f(x+1,y,s=[...s,w],t+=v)+f(x,y+1,s,t)+f(x-1,y,s,t)+f(x,y-1,s,t))|o

```

## Explanation

Takes the matrix as an array of arrays.

Starts from each square then uses a recursive function to test every possible combination. This is a brute-force approach, but it finishes almost instantly for the first test case on my machine.

```
(m,n)=>
  m.map((a,r)=>                 // for each row
    a.map((_,c)=>               // for each column
      f(r,c,[0],0)              // start checking paths from the coordinate of the square
    ),
    o=                          // o = output number (max total)
    f=(x,y,s,t)=>               // recursive function f, x & y = current square, t = total
                                // s = array of used squares (starts as [0] so length = +1)
      s[n]?                     // if we have used n squares
        o>t?0:o=t               // set o to max of o and t
      :s.indexOf(w=x+","+y)<0&& // if the square has not been used yet
      m[y]&&(v=m[y][x])<1/0&&   // and the square is not out of bounds
                                // ( if value of square is less than Infinity )

        // Check each adjacent square
        f(x+1,y,
          s=[...s,w],           // clone and add this square to s
          t+=v                  // add the value of this square to the total
        )
        +f(x,y+1,s,t)
        +f(x-1,y,s,t)
        +f(x,y-1,s,t)
  )
  |o                            // return output

```

## Test

```
var solution = (m,n)=>m.map((a,r)=>a.map((_,c)=>f(r,c,[0],0)),o=f=(x,y,s,t)=>s[n]?o>t?0:o=t:s.indexOf(w=x+","+y)<0&&m[y]&&(v=m[y][x])<1/0&&f(x+1,y,s=[...s,w],t+=v)+f(x,y+1,s,t)+f(x-1,y,s,t)+f(x,y-1,s,t))|o
```

```
<textarea rows="7" cols="40" id="Matrix">10 -7 11 7 3 31
33 31 2 5 121 15
22 -8 12 10 -19 43
12 -4 54 77 -7 -21
2 8 6 -70 109 1
140 3 -98 6 13 20</textarea><br />
N = <input type="number" id="N" value="6" /><br />
<button onclick="result.textContent=solution(Matrix.value.split('\n').map(x=>x.split(' ').map(z=>+z)),N.value)">Go</button>
<pre id="result"></pre>
```
> 4 votes

---
Tags: code-golf, grid
---


title: Like a quine, but not

text:
# Question
Title: Like a quine, but not
Very simple, write a program that at first glance appears to be a quine, but is not. Upon running, the program actually prints the source to a real quine, obviously distinct from the original program in some way, preferably creative, but since this is a popularity contest, the answer with the most upvotes wins.

Standard Loopholes which are no longer funny are forbidden.

# Answer
> 18 votes
# CJam

```
{"_~"}_~

```

Well, whether this *looks* like a real quine to you depends on whether you're used to CJam or GolfScript, but anyway, it looks like and prints the standard quine:

```
{"_~"}_~

```

Wait, isn't that the same thing?

> Nope, there's a space at the end of the first code. I believe the same thing would work in almost any language with almost any quine.

Test it here.

# Answer
> 12 votes
# H9+

```
"Hello, world!"

```

It's easy: In H9+, anything other than H, 9, or + is ignored, and therefore, this is a quine. Or is it?

> Nope. H actually outputs `Hello, world!`, with no quotes.

# Answer
> 9 votes
# Python

```
s="s=%r\nprint(s%%s)"
print(s%s)

```

Explanation:

> The output actually has single quotes instead of double quotes.

**Try it here**

# Answer
> 4 votes
# Mathematica

This one can be quite tricky to newer users.

```
Function[Print[StringJoin[ToString[FullForm[#0]], "[];"]]][];

```

Explanation:

> Some people might not notice the `#0` as not being part of the `FullForm`. In the output, it is replaced with `Slot[0]`. Everything else is the same.

# Answer
> 1 votes
# Haskell

Recursion can be tricky at times.

```
let s = "let s = " ++ show s ++ " in putStrLn s" in putStrLn s

```

---

> This actually outputs the same as '`s = "let s = " ++ show s in putStrLn s`', namely '`let s = "let s = \"let s = \\\"let s = \\\\\\\"let s = \\\\\\\\\\\\\\\"let s = \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"...`'

---

> Basically, Haskell is trying to let `s` be equal to itself, with `let s =` appended to it, and escaping the string.

---

> Obviously, in order to escape `"` you need `\"`, and in order to escape `\` you get `\\`, which is how the long stream of backslashes is formed.

---
Tags: popularity-contest, quine, underhanded
---


title: Calculating distances mod N

text:
# Question
Title: Calculating distances mod N
You have been collecting data from a *Advanced Collecting Device Controller™* for a long time. You check the logs, and to your horror you discover that something has gone terribly wrong: the data only contains the last bits of the numbers!

Luckily, you know the starting value and that the value never changes fast. That means you can recover the rest by just finding the distance from the start.

## Challenge

You will write a program or a function to calculate the amount a value has changed, given a modulus `N` and a list of the intermediate values modulo `N`.

The change between every pair of numbers **is always less than `N/2`**, so there will only be one valid answer for each test case.

You will be given as input an integer `N` \> 2 and a list of values, in a format of your choice. Input may be given via STDIN or command line or function arguments.

You will output a single integer, the amount the original value has changed. Output may be printed to STDOUT or returned.

## Rules

* Your program must work for any distance and modulus less than `2^20`.
* You may assume that:
    + `N` is at least `3`.
    + The list has at least 2 values.
    + All the values in the list are at least 0 and less than `N`.
    + All changes in the numbers are less than `N/2`.
* Anything else is an invalid input, and your program may do whatever it wants.
* Standard loopholes, any non-standard libraries and built-in functions for this exact purpose are forbidden.
* This is , so the shortest program in bytes wins.

## Example test cases

Input:

```
3
0 1 2 2 0 1 0 2 1 2 0 1 2 1 1

```

Output:

```
4

```

Explanation (with example value):

```
Value mod 3: 0 1 2 2 0 1 0 2 1 2 0 1 2 1 1
Value:       0 1 2 2 3 4 3 2 1 2 3 4 5 4 4

```

Input:

```
10
5 2 8 9 5

```

Output:

```
-10

```

Explanation (with example value):

```
Value mod 10:  5  2  8  9  5
Value:        15 12  8  9  5

```

### Invalid inputs:

```
2
0 0 0 0 0

```

(too small modulus)

```
6
2 5 4 2

```

(too large change between 2 and 5)

# Answer
> 2 votes
## TI-BASIC, 15 bytes

```
Input N
sum(N/πtan⁻¹(tan(ΔList(πAns/N

```

Takes the list from `Ans` and the modulus from `Input`.

```
                       πAns/N    ; Normalize the list to [0,π)
                 ΔList(          ; Take differences, which are in the range (-π,π)
       tan⁻¹(tan(                ; Modulo, but shorter. Now elements are in (-π/2,π/2)
    N/π                          ; Multiply by N/π. These are displacements at each step.
sum(                             ; Add up all the displacements

```

# Answer
> 9 votes
# Python 2, 53 bytes

```
lambda n,l:sum((b-a+n/2)%n-n/2for a,b in zip(l,l[1:]))

```

Super straight forward answer. I wonder if there is a shorter way.

# Answer
> 7 votes
# Mathematica, 30 bytes

```
Tr@Mod[Differences@#2,#,-#/2]&

```

This is an anonymous function which takes two arguments. Example usage:

```
Tr@Mod[Differences@#2,#,-#/2]&[3, {0, 1, 2, 2, 0, 1, 0, 2, 1, 2, 0, 1, 2, 1, 1}]
(* 4 *)
Tr@Mod[Differences@#2,#,-#/2]&[10, {5, 2, 8, 9, 5}]
(* -10 *)

```

This works by taking the `Differences` between successive elements, wrapping them to the range `-n/2` to `+n/2` with `Mod` and its offset parameter, then taking the total with `Tr` (matrix trace, sum of diagonal elements).

---

Note that even ungolfed it's only 43 bytes!

```
f[n_, l_] := Total[Mod[Differences[l], n, -n/2]]

```

# Answer
> 5 votes
# J, 24 bytes

```
[+/@(]-(>-:)~*[)[|2-~/\]

```

Usage:

```
   f=:[+/@(]-(>-:)~*[)[|2-~/\]

   3 f 0 1 2 2 0 1 0 2 1 2 0 1 2 1 1
4

   10 f 5 2 8 9 5
_10

```

Will try to golf more and add some explanation after that.

Try it online here.

# Answer
> 4 votes
# Pyth, 20 19 bytes

```
sm-J/Q2%+-FdJQ.:vw2

```

Stole `.:_2` from Jakube, idea from Mauris.

# Answer
> 3 votes
# R, 38 bytes

```
function(n,v)sum((diff(v)+n/2)%%n-n/2)

```

This creates an unnamed function that accepts an integer and a vector as input and returns a single integer. To call it, give it a name, e.g. `f=function(n,v)...`.

Ungolfed + explanation:

```
f <- function(n, v) {
    # Compute the differences between sequential elements of v
    d <- diff(v)

    # Add n/2 to the differences and get the result modulo n
    m <- (d + n/2) %% n

    # Subtract n/2 then sum the vector
    sum(m - n/2)
}

```

Examples:

```
> f(3, c(0, 1, 2, 2, 0, 1, 0, 2, 1, 2, 0, 1, 2, 1, 1))
[1] 4

> f(10, c(5, 2, 8, 9, 5))
[1] -10

```

# Answer
> 3 votes
# MatLab, 33 bytes

```
@(x,y)sum(mod(diff(y)+x/2,x)-x/2)

```

My apologies, this is my first answer on this website. Typing this in MatLab then using the input `ans(modulus_value, [intermediate_values])` will return the requested value, where 'modulus\_value' is the modulus value, and 'intermediate\_values' is a list of the intermediate values separated by either spaces or commas.

Example:

```
ans(3, [0 1 2 2 0 1 0 2 1 2 0 1 2 1 1])

```

The anonymous function takes advantage of MatLab's `mod`, `diff`, and `sum` functions to compute the answer. First, the difference between each of the intermediate values is calculated. The result is then offset by the modulus divided by two, resulting in a set of difference values that is bound by \[-modulus/2 modulus/2\]. The result is then offset and summed again.

I think this can be golfed more, I'll be back soon with an update. Special thanks to @2012rcampion for the idea.

**Edit:** Matlab's `unwrap` function almost works here, but it's tough to golf. The following code returns an array where the last value is the amount the first value has changed: `@(x,y)unwrap(y/x*2*pi)/2/pi*x-y(1)`

The intermediate values are scaled to the range of \[-pi pi\], then "unwrapped" such that no consecutive value is more than pi apart. These values are then re-scaled and shifted, resulting in an array of distances from the starting value.

Interesting, but not very practical for this challenge :D

# Answer
> 2 votes
# Pyth, 29 bytes

```
+sm**._K-Fdvz>y.aKvz.:Q2-eQhQ

```

Try it online: Pyth Compiler/Executor

# Answer
> 2 votes
# CJam, 27 bytes

```
0q~:_2ewf{~\m1$2/:I+\,=I-+}

```

Test it here.

# Answer
> 2 votes
# Pip, 39 bytes

```
Qn$+({a>n/2?a-na<-n/2?a+na}Mg@>1-g@<-1)

```

Requires the list of data as command-line arguments and the modulus on STDIN. If that's too much of a stretch, I have a version that takes two command-line args for 5 bytes more.

Explanation:

```
                                         g is list of cmdline args (implicit)
Qn                                       Read n from stdin
                            g@>1         All but the first of the cmdline args
                                -g@<-1   ...minus all but the last of the cmdline args
                                         (i.e. a list of the differences of adjacent items)
     {                    }M             ...to which, map the following function:
      a>n/2?a-n                            If diff is too big, subtract n;
               a<-n/2?a+n                  else if too small, add n;
                         a                 else return unchanged
  $+(                                 )  Sum; print (implicit)

```

And just to prove that this not-so-competitive score is more reflective on my golfing skills than my language, here's a port of Mauris's Python solution in **30 bytes**:

```
Qn$+({(n/2-$-a)%n-n/2}MgZg@>1)

```

# Answer
> 2 votes
# Jelly

**6 bytes**

```
Iæ%H}S

```

Try it online!

### How it works

```
Iæ%H}S    Main link. Left input: A (list). Right input: N (integer).

I         Compute the increments (deltas of consecutive elements) of A.
   H}     Halve the right input (N).
 æ%       Mod the increments into (-N/2, N/2].
     S    Take the sum of all results.

```

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


# Question
Title: Output the spoken names of numbers used on planet Flapus
The residents of Flapus use a base-8 number system. The numbers are:

0 - Kuzla
1 - Ponara
2 - Boqkel
3 - Colopee
4 - Vruenat
5 - Foham
6 - Stikty
7 - Kricola

For numbers over 7, the full name of the last digit comes first, followed by apostrophe and the first characters of the other digit(s), up to and including the first vowel:

*11 - Ponara(1)'po(1)
13 - Colopee(3)'po(1)
* 64 - Vruenat'sti
55 - Foham'fo
47 - Kricola'vru

As the numbers go up, the formula stays the same - the full name last digit comes first, followed by an apostrophe and the first characters of the other digits, up to and including the first vowel. Note that apart from the final digit (first word), the order remains the same.

*123 - Colopee(3)'po(1)bo(2)
205 - Foham(5)'bo(2)ku(0)
* 1123 - Colopee'popobo
7654 - Vruenat'kristifo

The exception to the rule is for numbers ending in 0. Here the word begins with Ku and is completed with the first letters of the other digits, up to and including the first vowel. No apostrophe is used.

10 - Kupo
70 - Kukri
350 - Kucofo
630 - Kustico
1000 - Kupokuku

### Challenge

Write a program or function that accepts a valid base-8 number, and outputs the spoken equivalent. You may assume you will always receive a valid number. Trailing whitepace / single newline after your answer is ok. The first character needs to be upper-case, as per examples.

This is . Shortest code in bytes wins. Standard loopholes apply. Answers whose lengths are converted and additionally submitted in Flapussian get extra cookies.

### Test cases

0 -\> Kuzla
1 -\> Ponara
2 -\> Boqkel
3 -\> Colopee
4 -\> Vruenat
5 -\> Foham
6 -\> Stikty
7 -\> Kricola
10 - \> Kupo
11 -\> Ponara'po
23 -\> Colopee'bo
56 -\> Stikty'fo
70 -\> Kukri
100 -\> Kupoku
222 -\> Boqkel'bobo
2345 -\> Foham'bocovru

# Answer
> 5 votes
## Pyth, 117 bytes (Kricola'popo)

```
Jc"Ku Po Bo Co Vru Fo Sti Kri";K+kc"nara qkel lopee enat ham kty cola";=TsezIszp@JTp@KTp?&T>sz7\'kVPzpr@JsN0;.?"Kuzla

```

Hand-transpiled to pythonic pseudocode:

```
                                           z = input()      # unevaluated, raw
                                           k = ""
Jc"Ku Po Bo Co Vru Fo Sti Kri";            J = "Ku Po...Kri".split()
K+kc"nara qkel lopee enat ham kty cola";   K = k + "nara...cola".split() # k casted to [""]
=Tsez                                      T = int(end(z))  # end(z) means z[-1]
Isz                                        if int(z):
  p@JT                                         print(J[T])
  p@KT                                         print(K[T])
  p?&T>sz7\'k                                  print("'" if T and s > z else k)
  VPz                                          for N in z[:-1]:  # P(z) is z[:-1]
    pr@JsN0                                        print(J[int(N)].lower())
.?                                         else:
  "Kuzla                                       print("Kuzla")

```

# Answer
> 9 votes
## Retina, Colopee'pokri, ~~165~~ ~~157~~ ~~143~~ ~~127~~ 123 bytes

```
(.+)(.)
$2'$1
0
Kuzla
1
Ponara
2
Boqkel
3
Colopee
4
Vruenat
5
Foham
6
Stikty
7
Kricola
(?<='.*[iou])[a-z]+

T`L`l`'.+
zla'

```

The trailing linefeed is significant.

Try it online!

### Explanation

```
(.+)(.)
$2'$1

```

We start by bringing the trailing digit to the front and inserting an apostrophe after it. Note that this leaves single-digit numbers unchanged, since the regex doesn't match - so those never get an apostrophe in the first place.

```
0
Kuzla
1
Ponara
2
Boqkel
3
Colopee
4
Vruenat
5
Foham
6
Stikty
7
Kricola

```

This replaces each digit with its full name, regardless of where it appears.

```
(?<='.*[iou])[a-z]+

```

This shortens all the digit names that appear after an apostrophe. Note that only the vowels `iou` appear first in a digit name, so we check a position that is right after one of those, *and* after an apostrophe and then match (and remove) all lower case letters that follow that position. Since we've inserted the digit names in title case, this will stop before the next digit.

```
T`L`l`'.+

```

This uses transliteration to turn all upper case characters, `L`, into their lower case counterpart, `l`, provided they are found in a match that starts with `'` (in order to leave the leading capital untouched).

```
zla'

```

The only thing that's left is correctly handling multiples of (octal) 10. In that case, we'll have a result starting with `Kuzla'`, which we want to start with `Ku` instead. So we simply remove all occurrences of `zla'`.

# Answer
> 4 votes
### Java (1.8) - Vruenat'fobo (~~486~~ 340 bytes)

Just when I thought I couldn't possibly golf this any more, I found another 33 bytes! Very pleased! Biggest savings were from switching to char arrays (shorter to upper/lowercase), and reusing the input string array for the words.

Discovering loads of golfing tricks, down to under 400! In theory I could still reduce this more, as I said a function would be ok in the rules, whereas this is a full program.

**Updated** Using Martin Büttner's approach, I refactored to use regex instead. Managed to save another 10 bytes! Thanks Martin.

```
interface F{static void main(String[]n){String t="",o,a=n[0];n="Kuzla,Ponara,Boqkel,Colopee,Vruenat,Foham,Stikty,Kricola".split(",");int i=0,l=a.length()-1;char f=a.charAt(l);o=n[f-48]+(l>0?"'":"");while(i<l)t+=n[a.charAt(i++)-48];o+=t.replaceAll("(?<=.*[iou])[a-z]+","").toLowerCase();if(f==48)o=o.replace("zla'","");System.out.print(o);}}

```

### Ungolfed

```
interface Flapus {
static void main(String[] names) {
    String temp="",out, a = names[0];
    names = "Kuzla,Ponara,Boqkel,Colopee,Vruenat,Foham,Stikty,Kricola".split(",");
    int i=0, last = a.length()-1;
    char lastchar = a.charAt(last);

    out=names[lastchar-48]+(last>0?"'":"");
    while(i<last) {
        temp+=names[a.charAt(i++)-48];
    }
    out+=temp.replaceAll("(?<=.*[iou])[a-z]+", "").toLowerCase();
    if (lastchar==48) {
        out=out.replace("zla'","");
    }
    System.out.print(out);
}
}

```

# Answer
> 4 votes
# JavaScript (ES6), 171

```
n=>(x='Kuzla Ponara Boqkel Colopee Vruenat Foham Stikty Kricola ku po bo co vru fo sti kri'.split` `,r=x[d=+(n=[...n]).pop()],n.map(d=>r+=x[+d+8],n[0]?r=d?r+"'":'Ku':0),r)

```

**Test**

```
F=n=>(
  x='Kuzla Ponara Boqkel Colopee Vruenat Foham Stikty Kricola ku po bo co vru fo sti kri'.split` `,
  r=x[d=+(n=[...n]).pop()],
  n.map(d=>r+=x[+d+8],n[0]?r=d?r+"'":'Ku':0),
  r
)

console.log=x=>O.textContent+=x+'\n'

o=''
for(i=0;i<999;i++)
  o+=i.toString(8) +':'+ F(i.toString(8))+(i%8!=7?' ':'\n')
console.log(o)
```

```
#O { font-size:12px }
```

```
<pre id=O></pre>
```

# Answer
> 3 votes
## Python (3.5) ~~225~~ ~~222~~ ~~217~~ 202 bytes

A working solution with list comprehension in python

```
s=input()
d="Kuzla,Ponara,Boqkel,Colopee,Vruenat,Foham,Stikty,Kricola".split(',')
r=d[int(s[-1])]+"'"if s[-1]!='0'else'Ku'
d=[i[:2+(i[2]in'ui')].lower()for i in d]
for i in s[:-1]:r+=d[int(i)]
print(r)

```

## Explanation

```
d="Kuzla,Ponara,Boqkel,Colopee,Vruenat,Foham,Stikty,Kricola".split(',')

```

Win 3 bytes with the split version (previous version: `d="Kuzla","Ponara",...`)

```
r=d[int(s[-1])]+"'"if s[-1]!='0'else'Ku'

```

Initialisation of the result in function of the last digit

```
d=[i[:2+(i[2]in'ui')].lower()for i in d]

```

Change the d list to keep first 2 or 3 characters and put in lower case

```
for i in s[:-1]:r+=d[int(i)]

```

Cat the string

# Answer
> 2 votes
# Javascript ES6, ~~231~~ ~~228~~ ~~225~~ ~~222~~ 204 bytes

```
a=[...prompt(c="Kuzla,Ponara,Boqkel,Colopee,Vruenat,Foham,Stikty,Kricola".split`,`)];b=c[a.pop()];a.length?b=b==c[0]?"Ku":b+"'":0;for(;a.length;)b+=c[a.shift()].match(/.+?[iou]/)[0].toLowerCase();alert(b)

```

Saved a bunch of bytes thanks to Neil.

# Answer
> 2 votes
## F#, ~~364~~ ~~288~~ 250 bytes (Kubofo)

```
let M="Ku-Ponara-Boqkel-Colopee-Vruenat-Foham-Stikty-Kricola".Split '-'
let m="Ku-Po-Bo-Co-Vru-Fo-Sti-Kri".Split '-'
let rec r a=function|0->a|i->r(m.[i%10].ToLower()::a)(i/10)
fun i->String.concat""<|M.[i%10]::((if(i%10)=0 then""else"'")::r[](i/10))

```

Returns a function that takes an integer and returns its Flapus equivalent. =D

# Answer
> 1 votes
## Python 3 - ~~181~~ 177 bytes (Ponara'bosti)

```
a='Ku Po Bo Co Vru Fo Sti Kri zla nara qkel lopee enat ham kty cola'.split()
*y,x=map(int,input())
u=x>0
v=y>[]
print(a[x]+a[x+8]*u**v+"'"*(u&v)+''.join(a[i].lower()for i in y))

```

Beware of the most amazing use of `pow` you will ever see in your entire life. `u**v` is equivalent on boolean context as `u|(not v)` which was previously golfed to the nice `~v+2|u` expression!

---
Tags: code-golf
---


title: Imposters at the Zoo

text:
# Question
Title: Imposters at the Zoo
You want to open a new zoo. It'll be amazing. But being the cheapskate that you are, you only want to afford three-letter animals (everyone knows that an animal's cost is proportional to the length of its name). There goes your dream of making people pay to see an `elephant`. But suddenly you have a brilliant idea. If you just place the animals correctly in the pen, you can create the optical illusion of an `elephant`! Here is a top-down view of your new "elephant compound":

```
elk
  eel
   pig
    hog
     ant

--------  (fence)
    ^
    | viewing direction

```

Haha, those gullible visitors!

Yes, this is how perception works.

## The Challenge

Given a non-empty word consisting only of lowercase English letters, determine if it can be formed from overlapping the following 30 three-letter animal words:

```
ant ape asp ass bat bee boa cat cod cow
dab dog eel elk emu fly fox gnu hog ide
jay kea kob koi olm owl pig rat ray yak

```

Yes, there are more than 30, but that's a nice round number.

You may optionally receive this list as input (in any reasonable list or string format, as long as it's not pre-processed). You'll probably want to do this, unless reading and processing this input list is *much* more expensive than hardcoding and compressing it in your language of choice. Note that even if you take the list as input you may assume that it will always be exactly this list, so if your code relies on the passed list being 30 elements long and not containing a word with `z`, that's fine.

Each word can be used multiple times. Animals cannot be cut off at the ends, only partially hidden by other animals. So `ox` is not a possible string, even though we have `fox`.

Output should be truthy if this is possible, and falsy otherwise.

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.

Your code should handle any of the test cases in a few seconds.

Standard rules apply.

## More Examples

* Any one- or two-letter word is obviously falsy.
* So is any three-letter word which is not in the above list.
* Even though we have `gnu` and `rat`, `gnat` is falsy since there's no way to arrange them such that you only see two letters of each (we don't want to cut animals into thirds).

Some truthy examples:

```
pigment

    ant
  bee
 olm
pig

```

```
antioxidant

   fox
 koi  ide
ant     ant

```

## Test Cases

Most of the test cases were taken from running a reference implementation against a dictionary. The last few "words" were generated randomly and are just there to ensure that submissions are sufficiently efficient.

Truthy:

```
ant
owl
bass
pride
bobcat
peafowl
elephant
hedgehogs
crocodile
antidemocrat
aspidoganoidei
biodegradability
angioelephantiasis
propreantepenultimate
acategnukeaidabeleenaspcodcoidyakwakoasshogattkjaypigkobolcodidaskearaywelkwboaxbeeuflapaspoapemaassaaspeewoglmabiemuwjadogacagnuepigjaycownbatjaemuifoxkeaeekekeagratsseeluejdoghogaolmgpigbeaeelemulasphogjaydabemukgnunueifoasdoglrayyadogpewlayroassasslgnuaspyyakkbokeaodxilopgnuasppigkobelratelkolmakob
koigdgaspslycoyakehrdabowbatdkkeapogkobelrowlyarpidepetlfoxeboaiderbeefoxbgnuapeocowgiecowlkoieeltbategspemuideatdogbeeecatgeaoccattbbeassgnasolkeaflyelkaognubeeabrratoccolmobodoglyelraywelkoxantowleedrayflypeappigogatraoyakccpiganaaspkobabjaspkointantybjbeeanolmuijaylratojaynueidflyjarayabatmmpigtfly
eolmantjkobeeaorayogaowldfoxayeassapibatmflylyraelaspsseolmbelkkaoantlmufodasgnueantaidenthyakcodoxuepigodggnuantatlcatnuuelkpemucbapeeoiahdogplkowletbatdrayarayoaelkgrayodcatgkantewkobeljaybeeyfkobtbdabadoghbatfoxtflygaspdeidogtowlkeaolmyraelfleelejayehogowlccatoxeabiemkobpigolmdkobrcidekyakabboyidep

```

Falsy:

```
a
ox
ram
bear
koala
antelope
albatross
zookeeper
salamander
caterpillar
hippopotamus
koigdgaspslycoyakehrdabowbatdkkeapogkobelrowlyarpidepetlfoxeboaiderbeefoxbgnuapeocowgiecowlkoieeltbategspemuideatdogbeezcatgeaoccattbbeassgnasolkeaflyelkaognubeeabrratoccolmobodoglyelraywelkoxantowleedrayflypeappigogatraoyakccpiganaaspkobabjaspkointantybjbeeanolmuijaylratojaynueidflyjarayabatmmpigtfly
koigdgaspslycoyakehrdabowbatdkkeapogkobelrowlyarpidepetlfoxeboaiderbeefoxbgnuapeocowgiecowlkoieeltbategspemuideatdogbeeecatgeaoccattbbeassgnasolkeaflxelkaognubeeabrratoccolmobodoglyelraywelkoxantowleedrayflypeappigogatraoyakccpiganaaspkobabjaspkointantybjbeeanolmuijaylratojaynueidflyjarayabatmmpigtfly
beyeodpgspeclxlkbkaylldnceepkocbdmymsaogsowpbawbauaioluaaagaetdoaoialeoxaagspoelegflpylptylnolnatrjabaorkdteeydloiebbptatdtfdfgoodtbkoafmounbduaffcrfelcnawmxaskgaoenaattbaobgbgabnhkesbgaaaaotafkiiieatworginaeowaehuddegooaalowaoososaksahoimkulbtoadyyelkcmkacbuostadppcuglbnmotedfgfkoleldonknemomnmoutykg

```

# Answer
# Japt, ~~51~~ ~~48~~ ~~45~~ ~~36~~ ~~33~~ 19 bytes

*Saved 9 bytes thanks to @PeterTaylor*

```
;!UeVrE"[$& ]" S² x

```

Test it online!

Takes input as the string to test, followed by the list of three-letter words, delimited with `|`. Note: this doesn't work in the latest version of the interpreter, so please use the link instead of copy-pasting the code.

### How it works

The basic idea is to take the input string and repeatedly replace any of the 30 words in it with two filler chars. I use a space as the filler char. Also, we want to replace the `ant` in `elephant`, the `a` in `ela`, the `nt` in `e   nt`, etc. So what we want to do is to change the 30-word string to a regex that matches any of these combinations:

```
ant|ape|asp|...
Becomes:
[a ][n ][t ]|[a ][p ][e ]|[a ][s ][p ]|...

```

We can do this pretty easily:

```
;VrE"[$& ]"
          // Implicit: V = "ant|ape|asp|..."
;         // Set the vars A-J to various values. E is set to "[a-z]".
VrE       // Take V and replace each lowercase letter with:
"[$& ]"   //  "[" + the char + " ]".

```

However, this has the undesired effect of also matching three spaces, which has no effect on the result and thus ends the recursive replacement. We can get around this by replacing the match with two spaces instead of three:

```
Ue    S²  // Take U, and recursively replace matches of the regex with " ".repeat(2).

```

Here's a basic demonstration of how and why this works (using `.` in place of a space):

```
First match at the end:
eleant
ele..   (ant)
el..    (eel)
...     (elk)
..      (...)
true

First match at the beginning:
antmua
..mua   (ant)
...a    (emu)
..a     (...)
..      (boa)
true

First match in the middle:
cantay
c..ay   (ant)
..ay    (cat)
...     (jay)
..      (...)
true

```

For truthy test-cases, this leaves us with a string of all spaces. For falsy test-cases, we have some letters left in the mix. This can be translated to true/false like so:

```
     x   // Trim all spaces off the ends of the resulting string.
!        // Take the logical NOT of the result.
         // Empty string -> true; non-empty string -> false.

```

And that's about it! A bonus of this method is that even the largest test cases finish in under 5 milliseconds. (Tested here)
> 7 votes

# Answer
# GNU grep, 62 + 1 = 63 bytes

```
^(((.+)(?=.*!\3))*(...)(?=.*\4!)((.+)(?=.*\6!))*([^qvz]\B)?)+

```

This requires the `P` option. The input is expected to be the animal to be synthesized, followed by a space, followed by the list of 3-letter animals opened, closed, and delimited by exclamation marks. Example usage (assuming the program is saved as `zoo`):

```
> grep -Pf zoo
hippopotamus !ant!ape!asp!ass!bat!bee!boa!cat!cod!cow!dab!dog!eel!elk!emu!fly!fox!gnu!hog!ide!jay!kea!kob!koi!olm!owl!pig!rat!ray!yak!

```

For a true input, the input line is echoed back. For a false input, there is no output.

Thanks to Martin for spotting a bug and alerting me to the existence of `\B` for word non-boundary.
> 3 votes

# Answer
## ES6, ~~122~~ ~~121~~ ~~119~~ 104 bytes

I had worked out how to do this as far as ETHproduction's answer but couldn't think of how to handle the `,,,`* problem, so naturally when I saw Peter Taylor's comment it all became clear. Then ETHproductions managed to find a better way to handle the problem which helpfully saves 15 bytes.

Input is the target word and an array of animal words.

```
(s,a)=>[...s].map(_=>s=s.replace(RegExp(a.map(a=>a.replace(/./g,"[&$&]")).join`|`),'&&'))&&!/\w/.test(s)

```

Edit: Saved ~~1 byte~~ 3 bytes thanks to @ETHproductions.

\*Except I used &s because it looks nicer in my `replace`.
> 2 votes

# Answer
# JS ES6, 77 bytes

```
s=>/^(((.+)(?=.*!\3))*(...)(?=.*\4!)((.+)(?=.*\6!))*([^qvz][^\b])?)+/.test(s)

```

(this is anonymous fn)

Input is the same as the above grep example input
> 0 votes

---
Tags: code-golf, string, decision-problem
---


# Question
Title: The Death Of Low-Resolution Pixel Art (Or, Draw That Death)
> This is an *Irregular Webcomic!* themed task.\*

**Death** is a rather extensive orginization, and, although Head Death has had no trouble telling his employees apart, certain other entities connected to the orginization have had trouble keeping track of them all.

Thus, your task here is to, given the title of one of the various Deaths, generate the corresponding 32x32 pixel image of that Death.

Furthermore, as Head Death is rather bureaucratic (and a little bit stingy), the shortest program (after a few bonuses have been taken into account) will be the one chosen for official use.

Input must be case-insensitive. Additionally, the prefixes `Death Of`, `Death By`, and `The Death Of` should be treated as equivalent.

The output image may be saved to a file (in any lossless bitmap image format) or displayed on the screen.

The following are the **EXACT** RGB values to be used:

```
White 255 255 255
Black 0 0 0
Dark Gray 125 125 125
Bone Gray 170 170 170
Purple 60 0 140
Brown 120 40 0
Blue 0 80 200
Green 0 100 0
Neon Green 100 255 0
Red 0 255 0

```

(Note that no one Death uses all of those colors, and the only color which is common to all of them is bone gray)

Each output image shown here is shown first at actual size and then at 3x close-up.

# You are required to support the following Deaths:

**The Death of Insanely Overpowered Fireballs**

**The Death of Choking On A Giant Frog**

**Head Death**

**The Death of Being Wrestled To Death By Steve**

**The Death of Inhaling Hatmaking Chemicals**

**Charon**

(Note that Charon's exact role in the organization is unknown)

# You are not required to support the following Deaths, but may do so for various bonuses

**Death by Having Your Pelvis Crushed** (-8% bonus)

**The Death of Being Ground By A Mars Rover Rock Abrasion Tool** (-10% bonus)

**The Death of Drowning in a Reactor Pool** (-10% bonus)

**The Death of Being Impaled By A Javelin** (-8% bonus)

**The Death of Being Stabbed By A Cutlass** (-9% bonus)

**The Death of Bad Pizza Deliveries** (-7% bonus)

(Probably the only Death not to wear a cape. Don't ask me why.)

If you add include all of them, the final multiplier is `0.92*0.9*0.9*0.92*0.91*0.93≈0.58`.

# Additional Bonus

If you use an RGBA format and replace the white background with transparency, save an extra 12%.

> `*` *Irregular Webcomic!* is ©2002-Present David Morgan-Mar. CC BY-NC-SA.

# Answer
> 7 votes
# JavaScript (ES6), ~~714~~ ~~677.97~~ ~~651.76~~ ~~634.36~~ ~~545.76~~ 1063 - (8% * 10% * 10% * 8% * 9% * 7% * 12%) = 542.75

```
e=>(e=e.slice(-4,-2),c=document.createElement("canvas"),c.width=c.height=32,t=(r="000")=>(o=c.getContext("2d")).fillStyle="#"+r,r=(r,t,l=1,e=1)=>o.fillRect(r,t,l,e),u=12,i="7d7d7d",t(),r(l=13,8,3),(n=!/ea|te|ca|ri|Po/.test(e))&&(r(l,6,3,5),r(u,7,5,3)),"ca"==e&&(r(l,3,3,3),r(u,6,5)),"ri"!=e&&(t("ea"==e?"3C008C":/te|Po/.test(e)?"006400":""),r(10,l,9,15+("ea"==e)),r(11,u,7),r(u,11,5)),"te"==e&&(t("782800"),r(u,6,5),r(l,5),r(15,5)),"ri"==e&&(t("f00"),r(l,5,3,2),r(16,6)),t("aaa"),r(l,7,3),r(l,9,3),r(m=14,8),r(m,u,1,u),r(u,u,5),r(l,m,3),r(l,16,3),r(l,18,3),r(l,20,3),r(l,24,3),r(u,25),r(16,25),r(11,26,1,6),r(17,26,1,6),r(17,l,1,8),n||r(m,10,1,2),/al|ar|sh|el|To/.test(e)?(r(8,u,4),t(),r(7,9,1,23),"al"==e&&(r(3,9,4,2),r(2,10,1,2)),"sh"==e&&r(2,8,6,4),"el"==e&&(r(6,6,3,4),r(7,4,1,2),r(5,8,5)),"To"==e&&(r(6,8,3,23),r(4,m,2,3),r(3,m),r(l,9,3),t("fff"),r(6,9),r(5,15),t("0050c8"),r(l,7,3,2),r(m,9))):"la"==e?(r(11,u),r(10,l),r(9,15,1,2),t(i),r(9,17,1,12),r(8,17),r(7,18),r(8,19)):r(11,l,1,8),"Po"==e&&(t(i),r(l,10,3),t("64ff00"),r(u,7,5,3),r(l,6,3)),c.toDataURL())

```

Generates a data-url to a png of the image, and covers all of the bonuses.

EDIT: Just realized the bonus that a transparent background knocks off another 12%, which also reduces my byte count!

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


# Question
Title: Output all valid classful public unicast IPv4 addresses
IPv4 addresses are 32 bits wide, and thus the size of the address space is 232, or 4,294,967,296. However, this is only a theoretical upper-bound. It is not an accurate representation of all the addresses that may actually be used on the public internet.

For the purposes of this challenge, it is assumed that all addressing is classful. In reality, classful subdivision of address space has been superseded by CIDR (Classless Inter-Domain Routing and VLSM (Variable Length Subnet Masking), but this is ignored for this challenge.

According to the classful address scheme, there are 3 classes:

* Class A - `0.0.0.0` to `127.255.255.255` with `/8` netmask length
* Class B - `128.0.0.0` to `191.255.255.255` with `/16` netmask length
* Class C - `192.0.0.0` to `223.255.255.255`  with `/24` netmask length

Classes D (multicast) and E (reserved) are also defined, but these are not used for public unicast addresses.

Each class is subdivided into networks according to the netmask for that class.

Thus `3.0.0.0` is an example of a Class A network. The netmask length for Class A is 8, so the full address space for this network is `3.0.0.0` to `3.255.255.255`. However, the first address (`3.0.0.0`) is reserved as the network address and the last address (`3.255.255.255`) is reserved as the broadcast address for that network. Thus the actual range of usable addresses is `3.0.0.1` to `3.255.255.254` which is 224 \- 2 (= 16,777,214) total addresses.

Similarly, `200.20.30.0` is an example of a Class C network. The netmask length for Class C is 24, so the full address space for this network is `200.20.30.0` to `200.20.30.255`. Removing the network and broadcast addresses leaves the actual range of usable addresses is `200.20.30.1` to `200.20.30.254` which is 28 \- 2 (= 254) total addresses.

There are further limitations on address ranges that may be used for public unicast. According to RFC 6890, the disallowed ranges are:

* `0.0.0.0/8` \- Local networking
* `10.0.0.0/8` \- Private-Use
* `100.64.0.0/10` \- Shared Address Space
* `127.0.0.0/8` \- Loopback
* `169.254.0.0/16` \- Link Local
* `172.16.0.0/12`\- Private-Use
* `192.0.0.0/24` \- IETF Protocol Assignments
* `192.0.2.0/24` \- Reserved for use in documentation
* `192.88.99.0/24` \- 6to4 Relay Anycast
* `192.168.0.0/16` \- Private-Use
* `198.18.0.0/15` \- Benchmarking
* `198.51.100.0/24` \- Reserved for use in documentation
* `203.0.113.0/24` \- Reserved for use in documentation

Note that the above list uses VLSR netmasks to efficiently specify a range. In all but one cases, the given mask length has specificity is less than or equal to the normal classful mask length for the start of the range. Thus each of these VLSR ranges is equivalent to one or more classful networks. E.g. `172.16.0.0/12` is equivalent to the Class B networks `172.16.0.0` to `172.31.0.0` or the address range `172.16.0.0` to `172.31.255.255`.

The exception to this rule is the `100.64.0.0/10` VLSR range, which is more specific than the containing `100.0.0.0` Class A range. Thus `100.0.0.0` will be handled like other Class A ranges with the exception that it has a 4,194,304-address hole in the middle. The valid addresses in this Class A range will be `100.0.0.0` to `100.63.255.255` and `100.128.0.0` to `100.255.255.254`, a total of 224 \- 222 \- 2 (= 12,582,910) total addresses.

The goal of this challenge is to output all Class A, B and C unicast IPv4 addresses that may be validly assigned to a public internet host (i.e. excluding those detailed above).

* No input will be given and should not be expected.
* Output may be in any form convenient for your language, e.g. array, list, delimited string. Addresses must be output in standard dotted decimal format.
* Output order does not matter.
* Builtins that specifically give the required ranges of addresses are disallowed. Similarly any methods to dynamically inspect a BGP (or other protocol) routing table for the public internet are disallowed.

The numerically lowest address will be `1.0.0.1` and the numerically highest will be `223.255.255.254`.

---

This challenge is similar to Print out all IPv6 addresses, but because of the restrictions should require non-trivially different implementation.

# Answer
> 2 votes
## PowerShell, ~~648~~ ~~641~~ 625 bytes

```
for([uint64]$a=16MB;$a-lt2GB-16mb;$a++){if(($a%16mb)*(($a+1)%16mb)*($a-lt160MB-or$a-gt176MB)*($a-lt1604MB-or$a-ge1608MB)){([ipaddress]$a).IPAddressToString}}
for($a=2GB;$a-lt3GB;$a++){if(($a%64kb)*(($a+1)%64kb)*($a-lt2785152kb-or$a-gt2720mb)*($a-lt2753mb-or$a-gt2754mb)){([ipaddress]$a).IPAddressToString}}
for($a=3221225728;$a-lt3.5GB;$a++){if(($a%256)*(($a+1)%256)*(($a-lt3221225984-or$a-gt3221226240))*(($a-lt3227017984-or$a-gt3151385kb))*(($a-lt3156480kb-or$a-gt3156544kb))*(($a-lt3245184kb-or$a-gt3245312kb))*(($a-lt3247321kb-or$a-gt3325256959))*(($a-lt3405803776-or$a-gt3405804032))){([ipaddress]$a).IPAddressToString}}

```

Edit 1 -- I've golfed out all remaining powers-of-two operators, which saved an additional 7 bytes.
Edit 2 -- Moved the `[uint64]` cast to the first declaration of `$a` which eliminated the other two re-casts which saved 16 bytes.

Three lines, Class A / Class B / Class C. Left as separate lines for readability. ;-)

Two key points for understanding what's going on:

* PowerShell has powers-of-two operators `KB, MB, GB`. For example, `4KB` will return `4096` as an int. We leverage that in multiple locations to shave dozens of bytes.
* The .NET `[ipaddress]` class will try to parse a numerical value as an IP address by taking the number's binary representation. We use that constructor with the `IPAddressToString` argument for output.

By coupling those two things, we're able to just treat the IP addresses as numbers and loop through them with a `for()` loop. For example, the first loop for Class A subnets goes from `16MB` to `2GB-16MB`, or from `16777216` to `2130706432`. The binary representation of `16777216` is `1000000000000000000000000` or `00000001.00000000.00000000.00000000` if we split it into 8-bit chunks so we can easily see that corresponds to `1.0.0.0` in dotted-decimal notation. Similarly, `2130706432` can be written as `01111111000000000000000000000000` or `01111111.00000000.00000000.00000000` or `127.0.0.0`. Each integer, or power-of-two integer, used here can be rewritten as an IP address in this fashion.

So, for each loop iteration, we construct an `if()` statement to weed out the excluded addresses, by multiplying the individual statements together. Since the first statement in each `if` is an integer (thanks to the modulo testing), the remaining Boolean values are converted to either `0` or `1` for false/true. If any one of the statements are false, the whole multiplication will turn to `0` and thus be false. Thus, only if all the statements are true, will we output the result of the parsing.

### Slightly Ungolfed:

```
# Class A
for($a=16MB;$a-lt2GB-16mb;$a++){
  $b=($a%16mb)                     # x.0.0.0
  $b*=(($a+1)%16mb)                # x.255.255.255
  $b*=($a-lt160MB-or$a-gt176MB)    # 10.0.0.0/8
  $b*=($a-lt1604MB-or$a-ge1608MB)  # 100.64.0.0/10
  if($b){([ipaddress]::Parse($a)).IPAddressToString}
}

# Class B
for($a=2GB;$a-lt3GB;$a++){
  $b=($a%64kb)                           # x.y.0.0
  $b*=(($a+1)%64kb)                      # x.y.255.255
  $b*=(($a-lt2785152kb-or$a-gt2720mb))  # 169.254.0.0/16
  $b*=(($a-lt2753mb-or$a-gt2754mb))      # 172.16.0.0/12
  if($b){([ipaddress]::Parse($a)).IPAddressToString}
}

# Class C
for($a=3221225728;$a-lt3.5GB;$a++){
  $b=($a%256)                               # x.y.z.0
  $b*=(($a+1)%256)                          # x.y.z.255
  $b*=(($a-lt3221225984-or$a-gt3221226240)) # 192.0.2.0/24
  $b*=(($a-lt3227017984-or$a-gt3151385kb)) # 192.88.99.0/24
  $b*=(($a-lt3156480kb-or$a-gt3156544kb)) # 192.168.0.0/16
  $b*=(($a-lt3245184kb-or$a-gt3245312kb)) # 198.18.0.0/15
  $b*=(($a-lt3247321kb-or$a-gt3325256959)) # 198.51.100.0/24
  $b*=(($a-lt3405803776-or$a-gt3405804032)) # 203.0.113.0/24
  if($b){([ipaddress]::Parse($a)).IPAddressToString}
}

```

# Answer
> 1 votes
## Batch, ~~1930~~ ~~1884~~ ~~1848~~ 1830 bytes

```
@echo off
for /l %%a in (1,1,9)do call:a1 %%a
for /l %%a in (11,1,99)do call:a1 %%a
for /l %%b in (0,1,63)do call:a2 100 %%b
for /l %%b in (128,1,255)do call:a2 100 %%b
for /l %%a in (101,1,126)do call:a1 %%a
for /l %%a in (128,1,168)do call:b1 %%a
for /l %%b in (0,1,253)do call:b2 169 %%b
call:b2 169 255
call:b1 170
call:b1 171
for /l %%b in (0,1,15)do call:b2 172 %%b
for /l %%b in (32,1,255)do call:b2 172 %%b
for /l %%a in (173,1,191)do call:b1 %%a
call:c3 192 0 1
for /l %%c in (3,1,255)do call:c3 192 0 %%c
for /l %%b in (1,1,87)do call:c2 192 %%b
for /l %%c in (0,1,98)do call:c3 192 88 %%c
for /l %%c in (100,1,255)do call:c3 192 88 %%c
for /l %%b in (89,1,167)do call:c2 192 %%b
for /l %%b in (169,1,255)do call:c2 192 %%b
for /l %%a in (193,1,197)do call:c1 %%a
for /l %%b in (0,1,17)do call:c2 198 %%b
for /l %%b in (20,1,50)do call:c2 198 %%b
for /l %%c in (0,1,99)do call:c3 198 51 %%c
for /l %%c in (101,1,255)do call:c3 198 51 %%c
for /l %%b in (52,1,255)do call:c2 198 %%b
for /l %%a in (199,1,202)do call:c1 %%a
for /l %%c in (0,1,112)do call:c3 203 0 %%c
for /l %%c in (114,1,255)do call:c3 203 0 %%c
for /l %%b in (1,1,255)do call:c2 203 %%b
for /l %%a in (204,1,223)do call:c1 %%a
exit/b
:a1
for /l %%b in (0,1,255)do call:a2 %1 %%b
exit/b
:a2
for /l %%c in (0,1,255)do call:a3 %1 %2 %%c
exit/b
:a3
for /l %%d in (0,1,255)do if not %2%3%%d==000 if not %2%3%%d==255255255 echo %1.%2.%3.%%d
exit/b
:b1
for /l %%b in (0,1,255)do call:b2 %1 %%b
exit/b
:b2
for /l %%c in (0,1,255)do call:b3 %1 %2 %%c
exit/b
:b3
for /l %%d in (0,1,255)do if not %3%%d==00 if not %3%%d==255255 echo %1.%2.%3.%%d
exit/b
:c1
for /l %%b in (0,1,255)do call:c2 %1 %%b
exit/b
:c2
for /l %%c in (0,1,255)do call:c3 %1 %2 %%c
exit/b
:c3
for /l %%d in (1,1,254)do echo %1.%2.%3.%%d

```

Edit: Saved ~~46~~ 82 bytes by removing unnecessary spaces. Saved 18 bytes by using `exit/b` instead of `goto:eof`.

---
Tags: code-golf, kolmogorov-complexity, internet, networking
---


title: "You must construct additional pylons!"

text:
# Question
Title: "You must construct additional pylons!"
## Introduction

In the strategy game Starcraft 2, there are three "races" to choose from: Terran, Zerg, and Protoss. In this challenge we will be focusing on the Protoss and the iconic phrase "You must construct additional pylons!" This message is stated when you run out of supply to build your army. So, to help out the Starcraft community, you must write a program or function that tells players exactly how many pylons they need.

## The Challenge

You will be given an input of a string consisting of a single integer `N` and space-separated list of units. `N` will always be zero or positive, and the list of units will always have one or more valid units. `N` represents the amount of pylons the player currently has. Your job is to calculate if the amount of pylons that the player has is enough to build the units. Your program or function must output/return a truthy value if there is enough supply, or if there is not enough supply you must output `You must construct ZZZ additional pylons` where `ZZZ` is the amount of pylons needed to build the units. Note that `pylon(s)` must be plural when needed and unplural when not (`...1 additional pylon!`, `...2 additional pylons!`).

## Protoss Units and Supply Cost

Here is a list of all units and their corresponding supply cost. Pylons provide an additional 8 supply.

```
Unit            Supply Cost

Probe           1
Zealot          2
Sentry          2
Stalker         2
HighTemplar     2
DarkTemplar     2
Immortal        4
Colossus        6
Archon          4
Observer        1
WarpPrism       2
Phoenix         2
MothershipCore  2
VoidRay         4
Oracle          3
Tempest         4
Carrier         6
Mothership      8

```

## Examples WITHOUT Bonuses

```
Input:
   2 Probe Probe Probe Probe Stalker Zealot Carrier Probe Zealot
Output:
   You must construct 1 additional pylon!
Why?
   Adding up the supply costs for all of the units gives 17. The current 2 pylons provide 16 supply, so one more is needed to provide enough for 17.

Input:
   5 Mothership Carrier Probe Tempest HighTemplar
Output:
   true
Why?
   Adding up the units gets 21. The current 5 pylons provide 40 supply, which is plenty enough.

Input:
  0 Mothership Colossus Zealot
Output:
  You must construct 2 additional pylons!
Why?
  Adding the units gets 16. There is no pylons so 2 need to be built to provide enough supply.

```

## Bonuses

1. Any experienced Starcraft 2 player would know that you need a mothership core before to transform it into a mothership. Also, you can only have one mothership at a time (whether it is an actual mothership or a mothership core). If neither of these conditions are true, output any falsy value. If your program can check to see that only one mothership is active at a time, and that a mothership core is built *before* the actual mothership, take **20%** off your byte count.
2. Little may you know, but nexuses (protoss command centers) actually provide supply too! If your program can add 11 to the maximum supply every time it encounters a nexus in the unit list, take **10%** off your byte count. Note that it does not matter where the Nexus is in the build order, so `0 Probe Nexus` would still return `true`.

## Examples WITH Bonuses

```
Input (Bonus 1):
  3 Mothership Zealot
Output:
  false
Why?
  According to the first bonus, a mothership core has to be built before a mothership.

Input (Bonus 1):
  3 MothershipCore Mothership MothershipCore
Output:
  false
Why?
  According to the first bonus, only one mothership can be built and here there is two (MothershipCore -> Mothership and a second MothershipCore).

Input (Bonus 2):
  0 Probe Nexus Probe
Output:
  true
Why?
  According to the second bonus, nexuses add 11 to the maximum supply, allowing both probes to be built.

Input (Both Bonuses):
  0 Nexus MothershipCore Mothership Carrier
Output:
  You must construct 1 additional pylon.
Why?
  There are no pylons, but the nexus provides 11 supply. The motherships take up 2 and 8, respectively and the carrier takes up 6. You need one more pylon to have enough to provide for all 16 supply.

```

## TL;DR

Input a string consisting of an integer and space-separated unit names (from the table above). Output a truthy value if you can build all of the units with the supply provided by the `N` pylons (the integer in input). Output `You must construct ZZZ additional pylon(s)` if more pylons are needed, where `ZZZ` is the amount of pylons needed. Make sure to make pylons plural if necessary.

This is , so shortest code in bytes (or your language's counting method) wins!

## Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
# Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

---

```
var QUESTION_ID=69011,OVERRIDE_USER=36670;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?([\d\.]+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
> 4 votes
# Ruby, 263 - 30% = 184 bytes

```
v=c=k=0
l,a={PeOr:1,ZtSySrHrDrWmPxMe:2,Oe:3,VyIlAnTt:4,CsCr:6,Mp:8,Ns:-11},ARGV.shift
ARGV.map{|u|k+=l[l.keys.grep(/#{q=u[0]+u[-1]}/)[0]];c+=1if q=="Me";v=!0if c!=1&&q=~/M/}
n=k/8.0-a.to_i
p v ?n<0||"You must construct #{n.ceil} additional pylon#{'s'if n>1}!":nil

```

### Usage

`ruby sc.rb 0 Probe Nexus`

# Answer
> 7 votes
# Python 3, 207\*.9 == 186.3 bytes.

Implements the nexus bonus.
Saved 26 bytes thanks to DSM.
Saved 2 bytes thanks to Tim Pederick

```
x,*l=input().split()
d=-((int(x)*8-sum((('vexuobcl'+2*'clsuie'+4*'Ratahoiesuhihi').count(q[-3:-1])*(1-12*(q[0]>'w'))or 2)for q in l))//8)
print((1,"You must construct %s additional pylon"%d+'s!'[d<2:])[d>0])

```

# Answer
> 4 votes
## JavaScript, ~~274~~ ~~265 bytes (no bonuses)~~ 281 - 10% = 252.9 bytes

```
s=>(c=eval(s[a="replace"](" ","-(")[a](/ /g,"+")[a](/\w+/g,m=>m[b="match"](/^(Pr|Ob)/g)?1:m[b](/^([ZSHDWP]|M\w+C)/g)?2:m[b](/^O/g)?3:m[b](/^[IAVT]/g)?4:m[b](/^N/g)?-11:m[b](/^C/g)?6:+m!=m?8:m*8)+")"))>0?true:`You must construct ${Math.ceil(-c/8)} additional pylon${c/8<-1?"s":""}!`

```

This appears to be pretty lengthy...

Demo + explanation:

```
p = s => (c = eval(
  s[a = "replace"](" ", "-(")         //replace the first space (after the number of pylons) with "-" and open the bracket
   [a](/ /g, "+")                       //replace all the remaining spaces with "+"
   [a](/\w+/g, m =>                     //replace any sequence of characters with...
    m[b = "match"](/^(Pr|Ob)/g) ? 1 :   //with 1, if matches "Probe" or "Observer"
    m[b](/^([ZSHDWP]|M\w+C)/g) ? 2 :    //with 2, if it matches bunch of the units with cost 2. "Probe" didn't match already, so it's safe to catch "Phoenix" by only the first letter.
    m[b](/^O/g) ? 3 :                   //with 3, if match is "Oracle"
    m[b](/^[IAVT]/g) ? 4 :              //with 4, if matches "Immortal", "Archon", "VoidRay" or "Tempest"
    m[b](/^C/g) ? 6 :                   //with 6, if it's "Carrier" or "Colossus"
    m[b](/^N/g) ? -11 :                 //don't forget nexuses!
    +m != m ? 8 : m * 8                 //and if's not a number, then it's "Mothership", so with 8. If it's number, it can only be the number of pylons, replace it with itself multiplied by 8.
  ) + ")"                             //close the opened bracket
)) > 0 ? true : `You must construct ${Math.ceil(-c/8)} additional pylon${c/8<-1?"s":""}!`

document.write(
  p("2 Probe Probe Probe Probe Stalker Zealot Carrier Probe Zealot") + "<br>" +
  p("5 Mothership Carrier Probe Tempest HighTemplar") + "<br>" +
  p("0 Mothership Colossus Zealot") + "<br>" +
  p("0 Probe Nexus Probe")
)
```

# Answer
> 4 votes
## Python 3, 293 − 30% = 205.1 bytes

Implements **both** bonuses. Prints 1 as its truthy value, and either 0 or an empty string as its falsey value.

```
s='5N 8O5P bDbHeM7P6S7S9W6Z 6O 6A8I7T7V . 7C8C . aM'.split()
m=M=n=o=0
p,*u=input().split()
for v in u:
 S=0
 while'%x'%len(v)+v[0]not in s[S]:S+=1
 n+=S or-11;M+=S>7;m+='pC'in v;o+=m>1or M>1or m<1<=M
q=int(p)+n//-8
print([1,'You must construct %d additional pylon'%-q+'s!'[q>-2:]][q<0]*(o<1))

```

Credit to Dom Hastings' solution for helping me shave off a good few bytes with a "poor man's `ceil`" of my own, and Morgan Thrapp's for the idea underlying `'s!'[q>-2:]`, which saved me six bytes—not to mention pointing out, in the comments, how to save another byte on that bit.

---

### Explanations

The string in line 1 encodes all of the units and their supply requirements. Each unit is represented as two characters: a hexadecimal digit giving the length of the unit's name, and the first character of the name (e.g. `8O` is the Observer; `aM` is the Mothership). The supply requirement is the index of the encoded unit within the sequence `s`, formed by splitting the string on the spaces. Full stops mark unused amounts of supply (no unit needs 5 or 7 supply), and as a special case, the Nexus (`5N`) is at index 0.

Line 2 initialises values: `m` is the number of mothership cores, `M` is the number of motherships, `n` is the total supply cost, and `o` indicates whether or not the mothership build conditions have been violated. Line 3 takes the input, putting the number of pylons into `p` and the list of units into `u`.

Within the loop that starts at line 4, `S` is an index into `s` and, thus, also the amount of supply needed for the current unit, `v`. In line 6, the `while` statement steps through `s` until the unit is found. (`'%x'%len(v)` turns the length of the unit's name into a hex digit.)

Line 7 updates the total supply cost `n` (note the special case, `-11`, if `S` is zero). It then increments the counts of motherships `M` (identified by the supply cost being over 7) and mothership cores `m` (identified by the substring `pC` in the unit's name). Then, if either of these is greater than 1, or if `M` is at least one while `m` is still zero, the flag `o` is set. (Actually, it's incremented, but later on we only care if it's zero or non-zero.)

The pylon deficit `q` is calculated, a little oddly, in line 8. Naively, it should be `n // 8 - int(p)` (i.e. one eighth of the supply cost, minus any pylons we already have). But that would round down, when we need to round up. Integer division (`//`) rounds towards negative infinity, though, so we just work everything in negatives: `int(p) - -(n // -8)`, which simplifies to the form actually used.

Lastly, the output. If we're just one pylon short, `q` will be -1, hence the test `q>-2` (which slices the `s` out of the string `s!` if true, and keeps it otherwise). If there's no pylon deficit, `q` will be zero or positive, hence `q<0` to select between the truthy value 1 or the output string. Lastly, if the flag `o` isn't zero, multiplying either result (1 or a string) by Boolean `False` (handled as numeric 0) will give a falsey value (0 or the empty string).

# Answer
> 3 votes
# C++11, 732-30% = 512.4 bytes

Uses Dom Hastings's poor man's `ceil` and Martin Büttner suggestions of shorting the dictionary.

```
#include <iostream>
#include <map>
#include <string>
#include <cctype>
using namespace std;
map<int,int>a ={{536,1},{655,2},{677,2},{758,2},{1173,2},{1175,2},{869,4},{891,6},{635,4},{872,1},{997,2},{763,2},{1516,2},{766,4},{630,3},{770,4},{744,6},{1091,8},{563,-11}};
int main(){string b,c;int d,e,l,j,k=0,m=0,n=0,v=0;cin>>d;getline(cin,b);
while(b.size()){e=0;auto z=b.find(" ");c=b.substr(0,z);b.erase(0,((z==string::npos)?z:z+1));
for(int i=0;i<c.size();i++){e+=tolower(c[i]);}
if(e==1516){m++;}else if(e==1091){((m>1)?v=1:v=0);}
if((l=k-(d*8)>0)&&(m==n==1)){j=(int)(((float)l/8)+0.99);cout<<"You must construct "<<j<<" additional pylon"<<((j==1)?"!":"s!")<<endl;}
else{cout<<((m==n==1&&!v)?"True":"False")<<endl;}}

```

# Answer
> 2 votes
# Python 2, ~~442~~ ~~359~~ ~~464~~ ~~332~~ ~~314~~ 306 - 10% = 275.4

```
a,*l=input().split(' ');p=int(a)*8;for i in l:p-={"Ne":-11,"Pr":1,"Ze":2,"Se":2,"St":2,"Hi":2,"Da":2,"Im":4,"Co":6,"Ar":4,"Ob":1,"Wa":2,"Ph":2,"MoC":2,"Vo":4,"Or":3,"Te":4,"Ca":6,"Mo":8}[i[:2]+("C"if i[-4:]=="Core")]
e=int(.9+p/8)+1;print[1,"You must construct "+`e`+" additional pylon"+"s!"[e>1:]][p>=0]

```

# Answer
> 1 votes
# Lua, 418 - 10% = 376,2 bytes

```
function p(i)i=i:gsub("(%w+)",function(w)q=tonumber(w)*8;return""end,1);n=0;i:gsub("(%w+)",function(w)m=w.match;n=n+(m(w,"^Pr.*")and 1 or m(w,"^Ob.*")and 1 or m(w,"^[ZSHDWP]")and 2 or m(w,"^M.*C")and 2 or m(w,"^O")and 3 or m(w,"^[IAVT]")and 4 or m(w,"^C")and 6 or m(w,"^N")and -11 or 8)end)if n>q then a=math.ceil((n-q)/8);print("You must construct "..a.." additional pylon"..(a>1 and"s"or"")..".")else print(1)end end

```

Implements the Nexus bonus.

First time I've posted something here. Was writing Lua scripts for a game, stumbled across this and felt like contributing, hah.

Note: This Lua function assumes that the base library has been loaded, and that the host application defines an appropriate `print` function that accepts any non-nil value. I'm exploiting Lua's `string.gsub` to the best of my ability, as well as its `and` and `or` operators.

Here's the pretty version:

```
function pylons(i)
    -- Replace the first word, the number, with a space, while also storing it as a number * 8
    i = i:gsub("(%w+)", function(w)
        q = tonumber(w) * 8
        return ""
    end, 1)
    n = 0
    -- the function passed to gsub gets every word in the string,  and then I misuse Lua's and/or
    -- operator order to assign supply values to string.match calls that do not return nil
    i:gsub("(%w+)", function(w)
        m = w.match
        n = n + (m(w,"^Pr.*") and 1 or
        m(w,"^Ob.*") and 1 or
        m(w,"^[ZSHDWP]") and 2 or
        m(w,"^M.*C") and 2 or
        m(w,"^O") and 3 or
        m(w,"^[IAVT]") and 4 or
        m(w,"^C") and 6 or
        m(w,"^N") and -11 or 8)
    end)
    if n>q then
        a = math.ceil((n-q)/8)
        print("You must construct "..a.." additional pylon"..(a>1 and"s"or"")..".")
    else
        print(1)
    end
end

pylons("5 Nexus Probe Observer Zealot Sentry Stalker HighTemplar DarkTemplar WarpPrism Phoenix MothershipCore Oracle Immortal Archon VoidRay Tempest Colossus Carrier Mothership")
pylons("2 Probe Probe Probe Probe Stalker Zealot Carrier Probe Zealot")
pylons("5 Mothership Carrier Probe Tempest HighTemplar")
pylons("0 Mothership Colossus Zealot")

```

# Answer
> 0 votes
## Perl, 212 bytes code + 3 for `-p` \- 10% = 193.5 bytes

I'm sure I can reduce this some more, not happy about the full `for$s(...){...}` block but I'm done for now!

```
$x=$_*8;s/^\d+ //;map{for$s(Pr,Ob,Or,C,V,I,A,T,Z,S,H,D,W,Ph,'.+C',N,'.+p$'){$x-=(1,1,3,6,(4)x4,(2)x7,-11,8)[$i++%17]*/^$s/}}/\w+/g;$x=int$x/-8+.9;$s=1<$x&&'s';$_=$x>0?"You must construct $x additional pylon$s!":1

```

### Interesting snippets

* Poor mans `ceil`: `int$n+.9` \- I tried to use `0|` but got what looks like overflow!
* List duplication: `(9)x9` yields `(9,9,9,9,9,9,9,9,9,9)`

### Usage:

```
perl -p pylons.pl <<< '3 Mothership Zealot'
1

```

Thanks to Tim Pederick for helping to save an extra byte!

# Answer
> 0 votes
# JavaScript (ES6), 228-10% = 206

```
s=>(s.replace(/\w+/g,x=>t+=~~{Ns:-11,Pe:1,Zt:2,Sy:2,Sr:2,Hr:2,Dr:2,Il:4,Cs:6,An:4,Or:1,Wm:2,Px:2,Me:2,Vy:4,Oe:3,Tt:4,Cr:6,Mp:8}[x[0]+x.slice(-1)]-8*~~x,t=7),t=t/8|0,t<=0||`You must construct ${t} additional pylon${t>1?'s':''}!`)

```

**Test**

```
F=s=>(
  t=7,
  s.replace(/\w+/g,
   x=>t+=~~{Ns:-11,Pe:1,Zt:2,Sy:2,Sr:2,Hr:2,Dr:2,Il:4,Cs:6,An:4,Or:1,Wm:2,Px:2,Me:2,Vy:4,Oe:3,Tt:4,Cr:6,Mp:8}[x[0]+x.slice(-1)]-8*~~x),
  t=t/8|0,
  t<=0||`You must construct ${t} additional pylon${t>1?'s':''}!`
)

console.log=x=>O.textContent+=x+'\n';

;['2 Probe Probe Probe Probe Stalker Zealot Carrier Probe Zealot',
'5 Mothership Carrier Probe Tempest HighTemplar',
'0 Mothership Colossus Zealot','0 Probe Nexus Probe'
].forEach(t=>console.log(t+'\n'+F(t)))
```

```
<pre id=O></pre>
```

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