# Question
Title: Find the largest number n positions away from n
A sequel to this question.

# Task

Given an array of positive integers, find the **largest element k** for which:

> There exists *some* positive integer distance **n**, so that the element in the array located **n** places to the left *or* right from **k** equals **n**.

The array is guaranteed to contain at least one element satisfying this condition.

The shortest code (in bytes) wins. You may choose whichever I/O format you like.

# Example

Given the input

```
[4, 6, 7, 9, 3, 6, 5, 7, 2]

```

The eligible values are:

* The `4`, as there is a `7` located 7 positions to its right
* The first `6`, as there is a `3` located 3 positions to its right
* The `3`, as there is a `4` located 4 positions to its left
* The `5`, as there is a `2` located 2 positions to its right
* The second `7`, as there is a `3` located 3 positions to its left.

Of these values, the largest is `7`.

# Test cases

```
[1, 13] → 13
[2, 9, 8, 3, 72, 2] → 8
[5, 28, 14, 5, 6, 3, 4, 7] → 14
[1, 3, 5, 15, 4, 1, 2, 6, 7, 7] → 7
[5, 1, 3, 5, 2, 5, 5, 8, 5, 1, 5, 1, 2, 3] → 5
[5, 12, 2, 5, 4, 7, 3, 3, 6, 2, 10, 5, 5, 5, 4, 1, 8, 5] → 10

```

# Answer
# Jelly, 9 bytes

```
Jạþ`=ḅa¹Ṁ

```

Try it online! or verify all test cases.

### How it works

```
Jạþ`=ḅa¹Ṁ  Main link. Argument: A (array)

J          Indices; yield [1, ..., len(A)].
   `       Use the previous return value as left and right argument:
 ạþ        Absolute difference table; take the absolute value of the difference
           of each pair of indices, yielding a 2D array.
    =      Compare each absolute difference with the corresponding item of A.
     ḅ     Base; convert each Boolean list from base i to integer, where i is the
           corresponding item of A. The value of i is not important; we only care
           if the list contains a 1, which will result in a non-zero integer.
       ¹   Identity; yield A.
      a    Logical AND; replace non-zero values with the corresponding items of A.
        Ṁ  Take the maximum.

```
> 3 votes

# Answer
# 05AB1E, 21 bytes

```
vyN+Ny-})¹gL<Ãv¹yè})Z

```

**Explanation**

```
v      }               # for each num in input
 yN+                   # push index + num
    Ny-                # push index - num
        )              # wrap stack in a list
         ¹gL<Ã         # remove indices outside the range of input
              v¹yè})   # get list of elements in input at the remaining indices
                    Z  # get max

```

Try it online!
> 8 votes

# Answer
## Haskell, ~~61~~ ~~57~~ 55 bytes

```
f x=maximum[a|(n,a)<-x,(i,b)<-x,b==abs(n-i)]
f.zip[0..]

```

Usage example: `(f.zip[0..]) [5,28,14,5,6,3,4,7]` -\> `14`.

(More or less) a direct implementation of the definition: for each index `n` of the input list `x` keep `a := x!!n` if there's an index `i` where `b := x!!i` equals `abs(n-i)`. Find the maximum.

Edit: @xnor saved two bytes. Thanks!
> 7 votes

# Answer
# Jelly, 10 bytes

```
,N+JFfJị¹Ṁ

```

Try it online! or verify all test cases.

### How it works

```
,N+JFfJị¹Ṁ  Main link. Argument: A (array)

,N          Pair A with -A (element-wise negative).
   J        Yield the indices of A [1, ..., len(A)].
  +         Add the elements of A (and their negatives) with the corr. indices.
    F       Flatten the resulting 2D array.
     fJ     Filter indices; remove invalid indices (not in [1, ..., len(A)]) from
            the generated array. The result is the list of all indices of eligible
            elements of A.
       ị¹   Retrieve the corresponding elements of A.
         Ṁ  Take the maximum.

```
> 6 votes

# Answer
# Python 3, ~~85~~ ~~80~~ 72 Bytes

```
lambda l,e=enumerate:max(i for p,i in e(l)for s,j in e(l)if j==abs(s-p))

```

Edit: -8 Bytes thanks to @Dennis
> 5 votes

# Answer
# EXCEL: ~~32~~ 30 bytes

`=MAX(IF(A:A-ROW(A:A)<0,A:A,0))`

I still cannot believe I got it to be this short...

**How to use:**
paste this into ANY cell EXCEPT the cells of column A. After pasting, while still editing, press `control`+`shift`+`enter` to correctly enter it.
put your values into column A, 1 value per cell (as per CSV entry).

If you want to find out how this works, I've posted an additional tip in my Tips for golfing in Excel question.
> 5 votes

# Answer
## JavaScript (ES6), 61 bytes

```
a=>Math.max(...a.filter((_,i)=>a.some((e,j)=>e==i-j|e==j-i)))

```
> 4 votes

# Answer
# Perl, 45 bytes

Includes +2 for `-ap`

Give numbers on a line on STDIN:

```
largest.pl <<< "5 12 2 5 4 7 3 3 6 2 10 5 5 5 4 1 8 5"

```

`largest.pl`:

```
#!/usr/bin/perl -ap
($_)=sort{$b-$a}map@F[$^P=$n-$_,$n+++$_],@F

```

One more byte can be gained by replacing `^P` by the literal control character, but that leads to a warning on STDERR on recent perls.

Assumes `largest number + array length < 2^32`
> 4 votes

# Answer
# Pyth, ~~19~~ 17 bytes

*Thanks to @Pietu1998 for -2 bytes*

```
eS@LQ@UQs.e,-kb+b

```

A program that takes input of a list on STDIN and prints the result.

Try it online

**How it works**

```
eS@LQ@UQs.e,-kb+b  Program. Input: Q
         .e        Map over Q (implicit input fill) with elements as b and indices as k:
            -kb     k-b
               +b   k+b (Implicit fill with k)
           ,        2-element list of those (possible indices)
        s          Flatten that
      UQ           Yield [0, 1, 2, 3..., len(Q)-1]
     @             Filter the flattened list by presence in the above, removing invalid
                   indices
  @LQ              Index into Q at those indices
 S                 Sort that
e                  Yield the last element of that, giving the maximum
                   Implicitly print

```
> 3 votes

# Answer
# MATL, 13 Bytes

```
ttn:tYTq=a)X>

```

Input must be a column vector. I.e., input is semicolon-separated like \[1;2;3\], or comma separated with a transpose tick at the end like \[1,2,3\]'.

Try it online!

All test cases: (A), (B), (C), (D), (E), (F)

*Thanks to Suever for suggestions in the MATL chatroom to save 2 characters.*

**Explanation:**

The overall strategy is the same as my Octave/MATLAB answer, where the basic concept is explained: https://codegolf.stackexchange.com/a/94161/42247

The specific code in this MATL answer is built up as follows:

The core of the method is the construction of the Toeplitz matrix whose ij'th entry is abs(i-j). We first construct the Toeplitz matrix with entries abs(i-1)+1 with MATL's toeplitz command YT as follows:

```
n:tYT % Equivalent to @(v)toeplitz(1:length(v))

```

To see how this works, let us call the input vector to this code snippet 'v'. The 'n' finds the length of v, then ':' constructs the vector 1:length(v). Next the 't' makes another copy of 1:length(v) on the stack; this extra copy is needed due to a well-known bug in the YT function in MATL (the MATL equivalent of toeplitz()), wherein it expects two copies of the input instead of 1. Then YT takes the two copies of this vector 1:length(v) off the stack, and makes the abs(i-j)+1 Toeplitz matrix from them.

Now we need to subtract 1 from this matrix to get the Toeplitz matrix with entries abs(i-j), and find the ij locations where this abs(i-j) Toeplitz matrix is equal to the matrix of all column vectors containing column-copies of the input vector v. This is done as follows:

```
t n:tYT q=
% t [code] q= is equivalent to @(v) [code](v)-1 == v

```

The first 't' makes an extra copy of the input and stores it on the stack. The 'n:tYT' makes the toeplitz matrix as described earlier and outputs it into the stack. Then 'q' subtracts 1 from the Toeplitz matrix, and '=' does the elementwise equality comparison between the abs(i-j) matrix and the vector whose columns are copies of the input. Note that by comparing a column vector to a matrix, we are implicitly taking advantage of MATLAB/MATL's operator broadcasting rules (the column vector in the comparison gets copied to make a matrix without issuing any commands).

Finally, we need to find the row indices i where there is a column j such that the ij'th entry in the matrix difference constructed above equals 1, then get the value of the input vector corresponding to these indices, then take the maximum. This in the following three steps:

1) Find the indices for any row that contains a nonzero:

```
tn:tYTq= a
% [code] a is equivalent to @(v) any([code](v))

```

2) Extract the elements of the input vector corresponding to those indices:

```
t tn:tYTq= a ) X>
% t [code] ) is equivalent to @(v) v([code](v)]

```

3) Find and return the maximum element:

```
t tn:tYTq= a ) X>
% [code] X> is equivalent to @(v) max(v).

```
> 3 votes

# Answer
## Ruby, 66 bytes

```
->a{i=-1;a.map{|e|i+=1;[a[j=i+e]||0,a[0>(k=i-e)?j:k]||0].max}.max}

```
> 2 votes

# Answer
# Octave / MATLAB, 40 Bytes

```
@(v)max(v(any(toeplitz(1:nnz(v))-v==1)))

```

Input must be a column vector.

*Thanks to Luis Mendo for suggestions saving 3 bytes (see comment)*

*Thanks to Suever for suggestions saving 4 more bytes (replacing ~~(sum()) with any())*

**Explanation:**

Given an input vector v, this problem is equivalent to finding all solutions i,j of the following discrete equation,

```
abs(i-j) = v(i),   i,j both in 1..k,

```

where abs() is the absolute value function. Each v(i) for which this equation is solved is one of the candidate solutions which we can maximize over.

As a discrete function of i and j, all possibilities for the left hand side can be arranged in the toeplitz matrix that looks something like this:

```
[0, 1, 2, 3, 4]
[1, 0, 1, 2, 3]
[2, 1, 0, 1, 2]    <--- abs(i-j)
[3, 2, 1, 0, 1]
[4, 3, 2, 1, 0]

```

And since the right hand side doesn't depend on i, all possibilities for it can be arranged into a matrix where the columns are all copies of the input,

```
[v(1), v(1), v(1), v(1), v(1)]
[v(2), v(2), v(2), v(2), v(2)]
[v(3), v(3), v(3), v(3), v(3)]   <--- v(i)
[v(4), v(4), v(4), v(4), v(4)]
[v(5), v(5), v(5), v(5), v(5)]

```

To find all solutions to the equation, we subtract these two matrices and find the locations where there is a zero. The rows where there is a zero correspond to the desired indices i's where there is a j such that abs(i-j) = v(i).

Other tricks:

* It takes less characters to construct the absolute value function plus one, abs(i-j)+1, then check for locations where the difference is 1, rather than construct the true (unshifted) absolute value function.
* Uses automatic operator broadcasting to implicitly make column copies of v
* Gets the length of the input via nnz() instead of length(), which works since the inputs are said to be positive in the problem statement.
> 2 votes

# Answer
# Python, 58 bytes

Based on Tony S.'s Ruby answer. This answer works in Python 2 and 3. Golfing suggestions welcome.

```
lambda n:max([n[i+v]for i,v in enumerate(n)if i+v<len(n)])

```

**Ungolfing**

```
def f(array):
    result = []
    for index, value in enumerate(array):
        if index + value < len(array):
            result.append(array[index + value])
    return max(result)

```
> 2 votes

# Answer
# Mathematica, 69 bytes

```
Max@MapIndexed[{If[#2[[1]]>#,a[[#2-#]],{}],a[[#2+#]]~Check~{}}&,a=#]&

```

Anonymous function. Takes a list of integers as input and returns an integer as output. Ignore any messages generated.
> 1 votes

# Answer
# Scala, 94 bytes

```
a=>a.zipWithIndex.filter(p=>a.zipWithIndex.exists(x=>x._1==Math.abs(p._2-x._2))).unzip._1.max

```
> 1 votes

# Answer
# PHP, 128 Bytes

```
<?foreach(($i=$_GET[i])as$k=>$v){$k-$v<0?:!($i[$k-$v]>$m)?:$m=$i[$k-$v];if($k+$v<count($i))if($i[$k+$v]>$m)$m=$i[$k+$v];}echo$m;

```
> 1 votes

# Answer
# Java 7, ~~125~~ 123 bytes

```
int c(int[]a){int r=0,i=0,l=a.length,x;for(;i<l;r=l>(x=i+a[i])?a[x]>r?a[x]:r:r,r=(x=i-a[i++])>0?a[x]>r?a[x]:r:r);return r;}

```

2 bytes saved thanks to *@mrco*.

**Ungolfed (sort of) & test code:**

Try it here.

```
class M{
  static int c(int[] a){
    int r = 0,
        i = 0,
        l = a.length,
        x;
    for(; i < l; r = l > (x = i + a[i])
                      ? a[x] > r
                         ? a[x]
                         : r
                      : r,
                 r = (x = i - a[i++]) > 0
                      ? a[x] > r
                         ? a[x]
                         : r
                      : r);
    return r;
  }

  public static void main(String[] a){
    System.out.println(c(new int[]{ 1, 13 }));
    System.out.println(c(new int[]{ 2, 9, 8, 3, 72, 2 }));
    System.out.println(c(new int[]{ 5, 28, 14, 5, 6, 3, 4, 7 }));
    System.out.println(c(new int[]{ 1, 3, 5, 15, 4, 1, 2, 6, 7, 7 }));
    System.out.println(c(new int[]{ 5, 1, 3, 5, 2, 5, 5, 8, 5, 1, 5, 1, 2, 3 }));
    System.out.println(c(new int[]{ 5, 12, 2, 5, 4, 7, 3, 3, 6, 2, 10, 5, 5, 5, 4, 1, 8, 5 }));
  }
}

```

**Output:**

```
13
8
14
7
5
10

```
> 1 votes

# Answer
# JavaScript (ES6),  ~~56 54~~  53 bytes

```
l=>l.map((n,i)=>m=Math.min(m,~l[i+n],~l[i-n]),m=0)|~m

```

Try it online!
> 1 votes

# Answer
# Ruby 56 bytes

My smallest ruby solution.

```
->n{x=[];i=0;n.map{|v|x<<n[v+i]&&v+i<n.size;i+=1};x.max}

```

Pretty easy to test in rails console

```
a = ->n{x=[];i=0;n.map{|v|x<<n[v+i]&&v+i<n.size;i+=1};x.max}
a[[1, 13]
=> 13
a[[2, 9, 8, 3, 72, 2]]
=> 8
a[[5, 12, 2, 5, 4, 7, 3, 3, 6, 2, 10, 5, 5, 5, 4, 1, 8, 5]]
=> 10

```

This started at 63 bytes, thanks for the suggestions to help trim it down!
> 1 votes

# Answer
# Java, 118 bytes

```
int f(int[]a){int t=0,i,j,z=0,l=a.length;while(t<l*l){i=t/l;j=t++%l;z=a[i]>z&&((i<j?j-i:i-j)==a[j])?a[i]:z;}return z;}

```
> 1 votes

# Answer
# Actually, 17 bytes

This answer is an Actually port of my Python answer. Golfing suggestions welcome. Try it online!

```
;╗ñ♂Σ⌠╜l>⌡░⌠╜E⌡MM

```

**Ungolfing**

```
         Implicit input L.
;╗       Duplicate L and save a copy of L to register 0.
ñ        enumerate() the other copy of L.
♂Σ       sum() all the pairs of [index, value of n]. Call this list Z.
⌠...⌡░   Push values of Z where the following function returns a truthy value. Variable v_i.
  ╜        Push L from register 0.
  l        Push len(L).
  >        Check if len(L) > v_i.
⌠...⌡M   Map the following function over Z_filtered. Variable i.
  ╜        Push L from register 0.
  E        Take the ith index of L.
M        max() the result of the map.
         Implicit return.

```
> 1 votes

# Answer
# T-SQL(sqlserver 2016), 132 bytes

**Golfed:**

```
;WITH C as(SELECT value*1v,row_number()over(order by 1/0)n FROM STRING_SPLIT(@,','))SELECT max(c.v)FROM C,C D WHERE abs(D.n-C.n)=D.v

```

**Ungolfed:**

```
DECLARE @ varchar(max)='2, 9, 8, 3, 72, 2'

;WITH C as
(
  SELECT
    value*1v,
    row_number()over(order by 1/0)n
  FROM
    STRING_SPLIT(@,',')
)
SELECT
  max(c.v)
FROM
  C,C D
WHERE
  abs(D.n-C.n)=D.v

```

**Fiddle**
> 0 votes

# Answer
**Clojure, 68 bytes**

```
#(apply max(map(fn[i](get % i 0))(flatten(map-indexed(juxt - +)%))))

```

For example `(map-indexed (juxt - +) [3 4 1 2])` is `([-3 3] [-3 5] [1 3] [1 5])` (index `+/-` its value), these are used to look-up values from the original vector (out-of-range defaulting to `0`) and the max value is found. Still feels a bit verbose but at least I got to use `juxt` :)
> 0 votes

---
Tags: code-golf, number, array
---


title: Help PPCG Claus Deliver his Presents!

text:
# Question
Title: Help PPCG Claus Deliver his Presents!
# Help PPCG Claus Deliver his Presents

# Overview

PPCG Claus is running hella late delivering his gifts because nowadays we have so many odd little kiddos out there. This makes it much harder for PPCG Claus to get all the presents to the correct place. Your challenge is to help him delvier his presents correctly.

# The Complexity

Given a list of capitalized first names representing the kids he's supposed to deliver to and a list of presents represented by numbers, you must figure out how to distribute the presents among said children. Of course there's a catch though....

Nowadays kids are getting picky, if the kiddo is an odd fellow (first initial is ASCII-code odd) he wants an odd gift! If he's an even fellow (first initial is ASCII-code even) he obviously must be given an even one! Any child divisible by 3, however, is a naughty, naughty lad, so PPCG Claus must completely ignore them to make them behave next year. To consider his route a success he must deliver all presents to all children who deserve them and must not give any one child too many presents. If any child gets 3+ more presents than his or her peers, he risks becoming a naughty child next year, and that's just not right! Also, if any ***good*** child were to receive a present when another ***good*** child didn't, that also would turn that child evil.

# Example

The kids are as follows:

`Kids = ["Amy", "Betty", "Clyde", "Dave", "Francine"] = [A,B,C,D,F] = [65,66,67,68,70]`

* Betty is the bane of humanity, clearly in cahoots with the number 3.
* Amy and Clyde have been weirdos since birth and would hate to receive even presents.
* Dave and Francine are normal, even, kids; they should only receive even presents!

The presents are as follows:

`Presents = [1,2,3,4,5,6,7,8,9,10,11,12,13,14]`

One possible output would be:

```
[
    ['Amy',[1,3,5]],
    ['Betty',[]],
    ['Clyde',[7,9,11,13]],
    ['Dave',[2,4,6,8]],
    ['Francine',[10,12,14]]
]

```

# Exception Scenarios

However, just because PPCG Claus is ready and willing, doesn't mean PPCG Claus can. Here's a list of exception scenarios where you must break the bad news to PPCG Claus with a message of:

`PPCGmas is cancelled!`

The following scenarios will result in Christmas being cancelled:

* There are no children.
    + `[],[1,2,3]` \- Wellp, they ded.
* There are no good children.
    + `["Betty"],[1,2,3]` \- Seriously, screw Betty.
* There are no presents, or less presents than good children.
    + `["Amy","Charles"],[]` \- One or more would receive no presents.
    + `["Amy","Charles"],[1]` \- One or more would receive no presents.
* There are not odd/even presents to satisfy all good children.
    + `["Amy","Dave"],[2,4,6]` \- Amy is screwed over.

Here's a list of scenarios that shouldn't affect PPCGmas:

* Leftover Presents (All children should receive the maximal amount of presents).
    + `["Amy","Dave"],[2,4,6,8,10,12,14,7,9] = [["Amy",[7,9]],["Dave",[2,4,6,8]]]`

# Main Rules Reiterated

1. Good children are either even or odd, based on their first initial.
2. Bad children have a first initial wholly divisible by 3.
3. All good children must receive at least one present.
4. No good child is to receive greater than 2 presents more than any other good child.
5. If there are to be leftover presents you must maximally distribute them, without violating 4.
6. Bad children must receive no presents at all.
7. **If ANY of these is violated, you must output** `PPCGmas is cancelled!`**, exactly.**

# I/O Format Requirements

* The 1st input must be an array/list/comma-delimited string of full names, not just the first initial.
* The 2nd input must be a array/list/comma-delimited string of positive integers.
* The output may be any denotation of how you distributed the presents that makes sense; or `PPCGmas is Cancelled!`.

# Winning Criterion:

TL;DR: Betty is a jerk, don't compete.

# Answer
# APL, 171 bytes

```
{D←{⍵=1:⊂⍺⋄0~⍨¨↓⍵↑⍉↑⍺⊂⍨1=⍵|⍳⍴⍺}⋄e←⍺~o←⍺/⍨2|⍺⋄(0=≢G)∨0∊≢¨P←P↑⍨¨(2+⌊/R)⌊R←≢¨P←(o D≢O),e D≢E←G~O←G/⍨2|⎕A⍳⊃¨G←⍵/⍨×3|⊃∘⎕UCS¨⍵:'PPCGmas is cancelled!'⋄(O,E,B),[⍟4]P,(≢B←⍵~G)↑⊂⍬}

```

This takes the presents as the left argument, the children as the right argument, and returns a matrix where the first column contains the names of the children and the second column contains the presents they get.

Testcases:

```
      P←{D←{⍵=1:⊂⍺⋄0~⍨¨↓⍵↑⍉↑⍺⊂⍨1=⍵|⍳⍴⍺}⋄e←⍺~o←⍺/⍨2|⍺⋄(0=≢G)∨0∊≢¨P←P↑⍨¨(2+⌊/R)⌊R←≢¨P←(o D≢O),e D≢E←G~O←G/⍨2|⎕A⍳⊃¨G←⍵/⍨×3|⊃∘⎕UCS¨⍵:'PPCGmas is cancelled!'⋄(O,E,B),[⍟4]P,(≢B←⍵~G)↑⊂⍬}
      (⍳14) P 'Amy' 'Betty' 'Clyde' 'Dave' 'Francine'
┌────────┬─────────┐
│Amy     │1 5 9 13 │
├────────┼─────────┤
│Clyde   │3 7 11   │
├────────┼─────────┤
│Dave    │2 6 10 14│
├────────┼─────────┤
│Francine│4 8 12   │
├────────┼─────────┤
│Betty   │         │
└────────┴─────────┘
      1 2 3 P ⍬
PPCGmas is cancelled!
      1 2 3 P ⊂'Betty'
PPCGmas is cancelled!
      ⍬ P 'Amy' 'Charles'
PPCGmas is cancelled!
      (,1) P 'Amy' 'Charles'
PPCGmas is cancelled!
      2 4 6 P 'Amy' 'Dave'
PPCGmas is cancelled!
      2 4 6 8 10 12 14 7 9 P 'Amy' 'Dave'
┌────┬───────┐
│Amy │7 9    │
├────┼───────┤
│Dave│2 4 6 8│
└────┴───────┘

```

Ungolfed version here.
> 4 votes

# Answer
## JavaScript (ES6), ~~525~~ ~~492~~ ~~454~~ 453 bytes

-71 bytes thanks to @Guedes -1 bit thanks to @Jake Cobb

```
P=(K,p)=>{y='charCodeAt';n=(C)=>C[y](0)%3>0;N=(C)=>C[y](0)%3<1;E=(C)=>C[y](0)%2>0;O=(C)=>C[y](0)%2<1;f=(U)=>U%2<1;F=(U)=>U%2;M=(U,C)=>C%s==S;s=S=0;a=new Array();G='filter';e=p[G](f);o=p[G](F);J=K[G](n);r=J[G](O);L='length';i=J[G](E);s=r[L];for(S=0;S<r[L];S++){a.push([r[S],e[G](M)]);}s=i[L];for(S=0;S<i[L];S++){a.push([i[S],o[G](M)]);}K=K[G](N);for(S=0;S<K[L];S++){a.push(K[S],[]);}return(e[L]<r[L]||o[L]<i[L]||(r[L]+i[L])<1)?"PPCGmas is Cancelled!":a;}

```

Try it online !

Non-golfed version

Can be more golfed I think. I just did a litteral translation of the non-golfed version.

This is now shorter than the sum of the CharCode composing "santa" (115 + 97 + 110 + 116 + 97 = 535). Yeay
> 4 votes

# Answer
## Python 2, ~~334~~ ~~355~~ 354 bytes

```
k,p=input()
z=zip
l=len
e=[];o=[];g=[];b=[];q=[];r=[]
for x in k:[g,b][ord(x[0])%3<1]+=x,
for x in g:[e,o][ord(x[0])&1]+=x,
for x in p:[q,r][x&1]+=x,
v=l(e)
w=l(o)
t=v and l(q)/v
u=w and l(r)/w
if u:t=min(t,u+2)
if t:u=min(u,t+2)
if l(g)*(t or v<1)*(u or w<1)<1:exit('PPCGmas is cancelled!')
print z(e,z(*[iter(q)]*t))+z(o,z(*[iter(r)]*u))+z(b,[()]*l(b))

```

Lost 21 bytes to handle case of only-even or only-odd children.

Saved 1 byte thanks to @TuukkaX.
> 4 votes

# Answer
# Javascript (ES6), ~~218~~ 216 Bytes

```
(a,b)=>{c={};a.forEach(d=>c[d]=[]);e=f=0;while(!e){e=g=1;a.forEach(h=>(j=h.charCodeAt())%3?(k=b.findIndex(l=>l%2==j%2))<0?g=0:c[h][f+1]?0:e=0&c[h].push(b.splice(k,1)[0]):0);f+=!e&g}return f?c:"PPCGmas is cancelled!"}

```

The output (if it's not the error string) is an object whose keys are the children's names; the value is the array of presents that child receives.

Saved two bytes when I realized I had a pair of redundant parentheses.

Ungolfed version:

```
(names, gifts) => {

  // Initialize result. Set every child's gift array to empty
  var result = {};
  names.forEach(name =>
    result[name] = [];
  );

  // Initialize external loop values
  var done = false;
  var leastNumberOfPresentsAmongGoodChildren = 0;

  // Give the gifts
  while (!done) {

    // Initialize internal loop values
    done = true;
    var everyGoodChildGotGift = true;

    // Try to give at most one gift to every good child
    names.forEach(name => {
      var nameCode = name.charCodeAt(0);

      // Ignore bad children
      if ((nameCode % 3) != 0) {

        // Try to find an appropriate gift
        var giftIndex = gifts.findIndex(gift => (gift % 2) == (nameCode % 2));

        // If there is no gift, set the flag
        if (giftIndex < 0)
          everyGoodChildGotGift = false;

        // Make sure we don't give too many gifts
        else if (result[name].length < leastNumberOfPresentsAmongGoodChildren + 2) {

          // Remove the gift from the gifts array (we can't give it again)
          var giftToGive = gifts.splice(giftIndex, 1)[0];

          // Give the gift to the child
          result[name].push(giftToGive);

          // If at least one child got a gift, try to give more gifts
          done = false;
        }
      }
    }); // end forEach

    // If we're done, that means we couldn't give a gift to any good child
    if (done)
      everyGoodChildGotGift = false;

    // If every good child got a gift, then increase the count
    if (everyGoodChildGotGift)
      leastNumberOfPresentsAmongGoodChildren++;

  } // end while

  // If every good child gets at least one gift, return who gets what
  if (leastNumberOfPresentsAmongGoodChildren != 0)
    return result;
  else
    return "PPCGMas is cancelled!"; // IT'S ALL YOUR FAULT, BETTY. YOU'VE RUINED PPCGMAS.
}

```
> 2 votes

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


# Question
Title: The negative order integer challenge, but it's Prime Time!
*Im talking about this question, take a look at it if you are a bit confused.*

# Main Task

Your task is to output concatenated integers, in decreasing order, but increasing the maximum integer everytime you hit `1` *(for this question, 1 will be considered a prime number)*. While this doesn't sound any different from the first question, here comes the tricky part: All outputted numbers **may only be primes**. These will be strung together into a single string without spaces or newlines. Your input will also be a **prime number**.

Example:

```
1
21
321
5321
75321
1175321
Valid output:
1213215321753211175321
```

## Input

Your code may only take one input: the highest prime to be printed. This input can come from anywhere (graphical, STDIN). You are **assured** that the input is a prime number.

## Output

You will have to output the resulting number. You can get this number by keep counting down, only count the number if it's a prime, then connect all results together to one number. The last number "row" (e.g. `7, 5, 3, 2, 1`) has to be printed fully. The output could be anything (numbers, strings, graphical), as long as it's readable. The same Regex pattern for checking your test cases applies:

```
^(\D*(\d)+\D*|)$

```

If your output doesn't match with this pattern, your code is invalid.

## Rules

* The input is assured to be prime, do not include error handling, unless you want/need to.
* The output may only be a full-connected number, therefore not split up by anything, not even newlines.
* Your algorithm shouldn't check for the first instance of `N` appearing (for instance, the `17` in `1175321`), but rather for the first instance of `N` as the actual number.
* Your input is assured to be positive, do not add handling unless you want/need to.

## Test cases

```
Input: -2, 0
Output: Any, or none (number isn't positive)

Input: 9
Output: Any, or none (number isn't prime)

Input: 1
Output: 1

Input: 7
Output: 121321532175321

Input: 23
Output: 1213215321753211175321131175321171311753211917131175321231917131175321
```

# Winner

This is , so the author of the code with the least length in bytes wins!

# Answer
# Jelly, 9 bytes

```
ÆR1;;\UFV

```

Try it online!

### How it works

```
ÆR1;;\UFV  Main link. Argument: n

ÆR         Prime range; yield all primes up to n.
  1;       Prepend the "prime" 1.
    ;\     Cumulative concatenation; yield all prefixes of the prime range.
      U    Upend; reverse each prefix.
       F   Flatten the resulting 2D array.
        V  Eval. This casts the integer array to string first, thus concatenating
           the integers.

```
> 5 votes

# Answer
# Processing, 161 bytes

```
int p(int n){for(int k=1;++k<=sqrt(n);)if(n%k<1)return 0;return 1;}void t(int n){for(int i=1,j;i<=n;i++){if(p(i)<1)continue;for(j=i;j>0;j--)print(p(j)<1?"":j);}}

```

One function does the primality checking, the other does the printing. Call it by `t(7)`

### Ungolfed

The first function does the primality checking. It returns an `int` instead of a `boolean` since this way more bytes are saved. (`int` instead of `boolean`, `0` instead of `false`, `1` instead of `true`)

```
int Q103891p(int n){
  for(int k=1;++k<=sqrt(n);)
    if(n%k<1)return 0;
  return 1;
}

```

The second function prints out the string. It iterates through every number, if it is not a prime, skip to the next iteration. If it is a prime, it continues down to the printing inside another `for`-loop. Again, if the number is prime, then we print it, otherwise not.

```
void Q103891(int n){
  for(int i=1,j;i<=n;i++){
    if(p(i)<1)continue;
    for(j=i;j>0;j--)
      print(p(j)<1?"":j);
  }
}

```
> 5 votes

# Answer
# Jelly, 12 bytes

```
ÆR;@1
ÇÇ€UVV

```

Try it online!

If it hadn't been for `1`s at all, my code would have just been `ÆRÆRUVV` for 7 bytes.

Enhanced explanation:

```
ÇÇ€UVV Main link. Arguments: z.
Ç      Run link1 on z.
 Ç€    Run link1 on z's elements.
   U   Reverse z's elements.
    V  Flatten z.
     V Concatenate z's elements.

ÆR;@1 Link 1. Arguments: z.
ÆR    Range of primes [2..z].
    1 Integer: 1.
  ;@  Concatenate x to y.

```

The Irish guy (called Dennis?) somehow outgolfed me lol.
> 5 votes

# Answer
# 05AB1E, 19 bytes

```
LDpÏX¸ì€Lí˜ÐXQsp+ÏJ

```

Try it online!

**Explanation**

```
L                     # range [1 ... input]
 DpÏ                  # keep only primes
    X¸ì               # prepend a 1
       €L             # map: range [1 ... n]
         í            # reverse each sublist
          ˜           # flatten list to 1D
           Ð          # triplicate
            XQ        # check elements in one copy for equality with 1
              sp      # check elements in one copy for primality
                +     # add the above lists giving a list with true values at indices
                      # comtaining 1 or a prime
                 Ï    # keep only those elements of the unmodified copy of the list
                  J   # join

```
> 4 votes

# Answer
# Brachylog, 17 bytes

```
y:{e1|e#p}f@[rcw\

```

Try it online!

Can't seem to get shorter than that...

### Explanation

```
y                      The list [0, ..., Input]
 :{      }f            Find all...
   e1                     ...elements that are 1 (there is 1)...
     |                    ...or...
      e#p                 ...elements that are prime...
           @[          Take a prefix of the result
             rc        Reverse it and concatenate it into a number
               w       Write to STDOUT
                  \    Backtrack: try another prefix

```
> 2 votes

# Answer
# GameMaker Language, 169 bytes

Main function (68 bytes)

```
b=""for(i=1;i<=argument0;i++){c=i while(j)b+=string(p(c--))}return b

```

Function p (46 bytes)

```
for(a=0;a<argument0;a++)while q(++b){}return b

```

Function q (55 bytes)

```
n=argument0 for(i=2;i<n;i++)if!(n mod i)p=1return p|n=1

```
> 2 votes

# Answer
# MATL, 15 bytes

```
Zq"1@ZqP]1v!VXz

```

Try it online!

```
Zq      % Implicit input. Push array of primes up to that value
"       % For each prime in that array
  1     %   Push 1
  @     %   Push current prime
  Zq    %   Push array of primes up to that
  P     %   Reverse
]       % End
1       % Push 1
&h      % Concatenate all stack horizontally
V       % Convert to string
Xz      % Remove spaces. Implicit display

```
> 1 votes

# Answer
# Perl 6, 41 bytes

```
{[~] flat [\R,] 1,|grep *.is-prime,2..$_}

```

(Try it online.)

### Explanation:

* `1, |grep(*.is-prime, 2..$_)`: Sequence of 1 and primes... `(1 2 3 5)`
* `[,] ...`: Reduce ("fold") over comma operator... `(1 2 3 5)`
* `[\,] ...`: With intermediate results (triangular reduce)... `((1) (1 2) (1 2 3) (1 2 3 5))`
* `[\R,] ...`: Apply reversing meta-operator to the comma... `((1) (2 1) (3 2 1) (5 3 2 1))`
* `[~] flat ...`: Remove list nesting, and fold over string concat operator... `1213215321`

(This is based on my answer for the previous challenge.)
> 1 votes

# Answer
# Mathematica, 61 bytes

```
ToString/@(1<>Prime@Range[Range@PrimePi@#,0,-1]/.Prime@0->1)&

```

Unnamed function taking an integer argument and returning a string. (If the input is not a prime, it just "rounds it down" to the nearest prime; if the input is nonpositive, it pretends it's 1.)

This implementation uses the nasty trick from Martin Ender's answer to the similar previous challenge (who says this old dog can't learn new tricks?): abusing `<>` to flatten a nested list of integers.

The nested list in question starts by generating a similar nested list as in that answer, with the appropriate length (given by `PrimePi@#`, the number of primes up to and including the input); then `Prime` is applied to every element. For example, for the input `5` which is the 3rd prime, the code `Range[Range@PrimePi@#,0,-1]` yields `{{1,0},{2,1,0},{3,2,1,0}}`, and applying `Prime` to each element yields `{{2,Prime[0]},{3,2,Prime[0]},{5,3,2,Prime[0]}}` since the 1st, 2nd, and 3rd primes are 2, 3, and 5, respectively. I feel proud that I managed to add even more errors to Martin Ender's approach—Mathematica complains every time it writes `Prime[0]`.

`Prime[0]` isn't a thing, but that's okay: `/.Prime@0->1` turns them all into `1`s. And we also want a `1` on the front, so we replace the `""` from Martin Ender's answer with simply `1`, which actually saves a byte.
> 1 votes

# Answer
# PHP, 72 bytes

```
for(;$n<$argv[1];print$s=$n.$s)for($i=2;$i>1;)for($i=++$n;--$i&&$n%$i;);

```

Run wit `-r`

**breakdown**

```
for(;$n<$argv[1];               // loop $n up to argument:
    print$s=$n.$s)                  // 2. prepend $n to $s, print $s
    for($i=2;$i>1;)                 // 1. find next prime: break if $i<2
        for($i=++$n;--$i&&$n%$i;);      // if $n is prime, $i is 1 after loop (0 for $n=1)

```
> 0 votes

# Answer
# Pyth - 12 bytes

```
jkf!tPTs}R1S

```

Test Suite.
> 0 votes

---
Tags: code-golf, sequence, primes
---


title: The Primitive and Basic Numbers

text:
# Question
Title: The Primitive and Basic Numbers
Your task is to generate the "Primitive and Basic" numbers, which are made like so:

Start with **110**. Take the digits of its base-1 representation (**110 = 11**) and interpret them as base-2 digits. This gives **12 = 110**. Now, add the second prime number – **310** – to the result. This will give you **410**, which is our first "Primitive and Basic" (**PB**) number, or **PB(1)** (you can now see where I got the name from).

Next, take **410 = 1002** and interpret the digits of its base-2 representation as base-3 digits. This gives **1003 = 910**. Add the third prime number – **510** – to the result, which gives **1410**. That's the second **PB** number, or **PB(2)**.

You can see where this is going: take **1410 = 1123** and interpret the digits of its base-3 representation as base-4 digits. This gives **1124 = 2210**. Add the fourth prime number – **710** – to the result, which gives **2910**.

This continues on and on forever.

In general, **PB(n)** is equal to **PB(n-1)**, converted to base **n** and from base **n+1** to integer, plus the **(n+1)**th prime.

The first few terms of this sequence are:

```
4, 14, 29, 52, 87, 132, 185...

```

You must write a function or program that creates these numbers. It must take a positive integer **n** as input, and return **PB(n)**.

## I/O:

```
1 -> 4
5 -> 87

```

## Rules and specs:

* Your program must be able to handle all **PB** numbers below **231-1**.
* Standard loopholes apply.
* The input may be 0-indexed or 1-indexed, whichever you prefer.
* The input is guaranteed to be a valid index.
* The output must be in base 10.

This is , so shortest code in bytes wins!

*Unfortunately, there isn't an OEIS sequence for this. You can propose to OEIS to add this sequence in if you want.*

# Answer
# Ruby, 126 bytes

```
require("prime")
->n{o=4
(2..n).map{|i|j=i+1
r=[]
(r.unshift o%i;o/=i)while o>0
o=r.inject{|s,k|s*j+k}+Prime.first(j)[-1]}
o}

```
> 1 votes

# Answer
# Jelly, 13 bytes

```
’ß1¹?bḅ‘+‘ÆN$

```

Try it online!

### How it works

```
’ß1¹?bḅ‘+‘ÆN$  Main link. Argument: n

’              Decrement; yield n-1.
   ¹?          If n-1 is non-zero:
 ß               Recursively call the main link with argument n-1.
               Else:
  1              Yield 1.
     b         Convert the result to base n.
      ḅ‘       Convert from base n+1 to integer.
         ‘ÆN$  Increment n and yield the (n+1)-th prime.
        +      Add the results to both sides.

```
> 1 votes

# Answer
# Mathematica, 66 bytes

```
Fold[IntegerDigits[#,#2-1]~FromDigits~#2+Prime@#2&,4,2~Range~#+1]&

```

Unnamed function taking a single (1-indexed) integer argument and returning an integer.

`Fold[...,4,2~Range~#+1]` iterates a function of two arguments, with the first argument beginning at `4` and thereafter set to the output of the previous iteration, while the second argument iterates over the set {3,4,...,`#`+1} (where `#` is the original integer argument).

The function in question is `IntegerDigits[#,#2-1]~FromDigits~#2+Prime@#2`. First, `IntegerDigits[#,#2-1]` converts the first argument into a list of its digits when written in the previous base; then, `...~FromDigits~#2` converts that list of digits back into an integer, assuming the digits are now in the current base. Finally, the `#2`th prime is added to the result.
> 0 votes

# Answer
# Perl 6, 95 bytes

```
{my $b=1;(4,{grep(*.is-prime,2..*)[++$b]+.polymod($b xx*).&{sum $_ Z*($b+1 X**0..*)}}...*)[$_]}

```

Zero-based indexed.

### Explanation:

Since the language's built-in `.base` and `.parse-base` methods are string-based, they only work up to base 36. So in order to fulfill the task requirement that large inputs must be supported, the base conversion is done as follows:

* `.polymod($b xx *)`: Convert the current number to a list representing its digits in base `$b`.
* `sum $_ Z* ($b+1 X** 0..*)`: Interpret the resulting digits as a number in base `$b+1`.
> 0 votes

---
Tags: code-golf, sequence, primes, base-conversion
---


# Question
Title: Count how many characters are in the program's source
Write a program that counts and prints the number of characters in it's own source code to standard output.

The number must be generated from counting the characters.

This Ruby solution would not be allowed:

```
puts 6

```

because it is not calculated. Spaces, tabs, new lines, etc **should be counted**.

The program must be smallest possible in any programming language.

# Answer
# Bash, 10

Pretty boring, but:

* Prints the code size in bytes, and nothing else.
* Filename may contain spaces.

Make sure that the file doesn't have a new line at the end! If it does, it will output `11`.

```
wc -c<"$0"

```

If the file doesn't have spaces in its name, you can get 8 characters:

```
wc -c<$0

```
> 10 votes

# Answer
# CJam / GolfScript - 11

CJam:

```
{`"_~"+,}_~

```

GolfScript:

```
{`".~"+,}.~

```

This actually generates its own source code (like a quine) and then calculates the string length.
> 8 votes

# Answer
# PYG (9, and actually calculated)

Calculates the length of the source code (`Q`) with the builtin string length checker `len`, and prints (`P`) the result:

```
P(len(Q))

```
> 6 votes

# Answer
# Ruby, ~~30 22 20~~ 18

```
p IO.read($0)=~/$/

```
> 3 votes

# Answer
# perl, 9 bytes

No trailing newline.

```
print-s$0

```

Running it looks like this:

```
$ echo -n 'print-s$0' >/tmp/foo.pl
$ perl /tmp/foo.pl ; echo
9

```
> 3 votes

# Answer
# BASH (builtins only) - 18

```
$ cat bash ; echo # no final newline in file
a=`<$0`
echo ${#a}
$ ls -l bash
-rwxr-xr-x 1 yeti yeti 18 18. Mai 07:11 bash
$ ./bash
18

```
> 2 votes

# Answer
# Python 31

Save the file as `'l'`

```
print len(file.read(file('l')))

```

Outputs `34`
> 1 votes

# Answer
## Fortran 78

```
character*78::a;open(unit=9,file='c.f90');read(9,'(a78)')a;print*,len(a);end

```

File IO isn't the best in Fortran, so we have to waste space opening the file & then reading from it. Had I not specified the `a78` (78 characters), then it would stop at the comma next to `file` (silly list-directed IO).
> 1 votes

# Answer
# HTML + Javascript (jQuery): 48

Save this script as `script.html` and open it with a browser.

```
<script>alert($('body').html().length)</script>

```
> 1 votes

# Answer
# Rebol, 40

```
print length? read system/options/script

```
> 1 votes

# Answer
# VIM - 43

Add this in your `.vimrc` file :

```
:echo strlen(join(readfile(".vimrc")),"\n")

```

But it will only work if you are in your home when executing vim.

More generic solution `vim ~/.vimrc` (**46 chars**) :

```
:echo strlen(join(readfile(bufname("%")),"\n"))

```
> 1 votes

# Answer
# PHP - 22

```
<?=filesize(__FILE__);

```
> 1 votes

# Answer
# Python 3, ~~28~~ 27 bytes

I got 2̶8̶ 27 characters, plus file name and extension (4 in this case for 'f.py') The minimum value for this is 3̶2̶ 31, if there was a 1 letter file name and the `.py` exension:

```
print(len(open("f.py").read()))

```

EDIT: The bite count is actually 27 rather than 28, thanks @mbomb007 for pointing that out
> 1 votes

# Answer
## JavaScript 78

```
<script id="s">
function f(){document.write(document.getElementById("s").innerHTML.length);}
</script>

```
> 0 votes

# Answer
# J - 16 char

J can `read($0)` itself too, you know! Not all that well, but...

```
echo#1!:1]1{ARGV

```

A more natural solution in the interpreter REPL, in which we do the normal quine thing and then take the length, costs **24 chars**:

```
#(,2#{:),~'#(,2#{:),~'''

```

`,~` appends the string to itself, `(,2#{:)` appends two copies of the trailing single quote, and `#` takes the length.
> 0 votes

# Answer
# Extended BrainFuck: 12

```
,(>+<,)>55+.

```

Usage:

```
beef ebf.bf < cnt.ebf > cnt.bf
beef cnt.bf < ent.ebf

```

Output:

```
C

```

Which is 12 in hex. If you add a linefeed in the file it will output a `D` for 13 so it's definitely counting the characters in the source.
> 0 votes

# Answer
**Hy** (38 characters):

```
(defmain [n] (print (.read (open n))))

```
> 0 votes

# Answer
# dc - 8

Not sure if this is allowed, but calculates the length of the macro(the part in the square brackets and adds 4(which is the length of the part outside the macro)).

```
[Z4+p]dx

```
> 0 votes

# Answer
## Lua: 42

```
print(string.len(io.open('l',"r"):read()))

```

Pretty straight-forward, you must save the file as `l` and call it as `lua l`.
> 0 votes

# Answer
# K,13

```
1@$#,/0:.z.f;

```

/

```
$ q a.k -q
13

```
> 0 votes

# Answer
# Python 3: 33 or 37

```
print(len(open(__file__).read()))
print(len(open(__file__,'b').read()))

```

First if you only count the characters, second if you want to count the number of bytes.
> 0 votes

# Answer
## JavaScript (Node.js) - 60

```
console.log(require('fs').readFileSync(__filename).length);

```
> 0 votes

# Answer
# Java, 157 characters

Since nobody has done Java yet...

```
public class A{public static void main(String[]a) throws Exception{System.out.print(new java.util.Scanner(new java.io.File("A.java")).nextLine().length());}}

```
> 0 votes

# Answer
## PHP - 44

Save this as `c`

```
<?$f=fopen("c","r");echo strlen(fgets($f));

```
> 0 votes

# Answer
## JavaScript

**42 - ES5**

```
(function a(){alert((a+"()()").length)})()

```

**37 - ES6**

```
(a=x=>{alert((a+"(a=)()").length)})()

```
> 0 votes

# Answer
# Javascript (pure - no HTML nor JQuery) 41 bytes

```
function f() {alert((f+"f()").length)}f()

```
> 0 votes

# Answer
# Dyalog APL, 8 bytes

The niladic function `f`:

```
≢∊⎕NR'f'

```

Notice that this prints 10 because APL counts (and stores) the function header (name + newline). However, PPCG practice is not to count this header. The entire program can be displayed with

```
      ↑⎕NR'f'

```

Giving:

```
f
≢∊⎕NR'f'

```

---

`⎕NR'f'` the **N**ested (i.e. a list of character lists) **R**epresentation of `f`

**ϵ**nlist (flatten)

tally
> 0 votes

# Answer
# RProgN, 3 bytes.

```
Q L

```

Simply, Q is the function that pushes the source code to the stack, and L is the function that gets the length of the string on top of the stack. The stack is then implicitly printed.

Try it online!
> 0 votes

# Answer
## awk, 13 bytes

```
$0=length($0)

```

Write it to a program file `program.awk` and

```
$ awk -f program.awk program.awk
13

```
> 0 votes

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


title: Wrap a seasonal present

text:
# Question
Title: Wrap a seasonal present
### Task

**Given a wrapper element and a non-jagged 3D array, wrap the array top, bottom, and all-around.** You must handle both character and numeric data, but the wrapper and the present will have the same data type.

---

### Character example

For character data, you may chose to handle either 3D arrays of single characters or 2D arrays of strings:

Given the 2 layer, 2 row, 4 column character array

```
[[["Y","o","u","r"],
  ["g","i","f","t"]],

  [["g","o","e","s"],
  ["h","e","r","e"]]]

```

and the character `"."`, answer the 4 layer, 4 row, 6 column character array

```
[[[".",".",".",".",".","."],
  [".",".",".",".",".","."],
  [".",".",".",".",".","."],
  [".",".",".",".",".","."]],

 [[".",".",".",".",".","."],
  [".","Y","o","u","r","."],
  [".","g","i","f","t","."],
  [".",".",".",".",".","."]],

 [[".",".",".",".",".","."],
  [".","g","o","e","s","."],
  [".","h","e","r","e","."],
  [".",".",".",".",".","."]],

 [[".",".",".",".",".","."],
  [".",".",".",".",".","."],
  [".",".",".",".",".","."],
  [".",".",".",".",".","."]]]

```

or given the 2 row, 2 column array of 4-character strings

```
[["Your",
  "gift"],

 ["goes",
  "here"]]

```

and the character `"."`, answer the 4 row, 4 column array of 6-character strings

```
[["......",
  "......",
  "......",
  "......"],

 ["......",
  ".Your.",
  ".gift.",
  "......"],

 ["......",
  ".goes.",
  ".here.",
  "......"],

 ["......",
  "......",
  "......",
  "......"]]

```

---

### Numeric example

Given the 2 layer, 2 row, 2 column numeric array

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

 [[5,6],
  [7,8]]]`

```

and the number `0`, answer the 4 layer, 4 row, 4 column numeric array

```
[[[0,0,0,0],
   [0,0,0,0],
   [0,0,0,0],
   [0,0,0,0]],

  [[0,0,0,0],
   [0,1,2,0],
   [0,3,4,0],
   [0,0,0,0]],

  [[0,0,0,0],
   [0,5,6,0],
   [0,7,8,0],
   [0,0,0,0]],

  [[0,0,0,0],
   [0,0,0,0],
   [0,0,0,0],
   [0,0,0,0]]]

```

# Answer
# Dyalog APL, ~~31~~ ~~19~~ ~~13~~ 12 bytes

Almost a transliteration (31 bytes) of @Zgarb's solution.

An anonymous function. Left argument is wrapping, right argument is gift.

```
⊣h⍤1⊣h⍤2(h←⍪⍪⊣)

```

`⊣h⍤1` *h* applied, with the anonymous function's left argument, to the columns of

`⊣h⍤2` *h* applied, with the anonymous function's left argument, to the rows of

`h←` *h* applied to the major cells i.e. the layers of the anonymous function's arguments, where *h* is

the left argument prepended to the right argument

prepended to

the left argument

In other words, *h* is a function which surrounds its right argument (the gift) with its left argument (the wrapper). *h* is then applied to the gift's layers, then the rows of that, and finally the columns of that.

TryAPL online!

---

This Dyalog APL version 16.0 solution (19 bytes – courtesy of @ngn) handles any number of dimensions:

```
{⍵@(1+⍳⍴⍵)⊢⍺⍴⍨2+⍴⍵}

```

the gift

`@(` placed at

`1+` one plus

all the indices of

`⍴⍵` the shape of the gift

`)⊢` in the array consisting of

`⍺⍴⍨` the wrapper reshaped to the shape

`2+` two added to

`⍴⍵` the shape of the gift

In other words, we create an array entirely of wrapper elements, which in every dimension is two elements larger than the gift, then we place the gift into that array (thus replacing the wrapping elements in those positions) at an offset of one from the edges, i.e. in the center.

---

My own invention (-1 thanks to @ngn):

```
(⌽2 3 1⍉,)⍣6

```

This applies an anonymous function-train 6 times, each time with the wrapper as left argument, and the result of the previous application as right argument (although the first time around it will be the unmodified gift):

`(` an anonymous function-train

reverse columns of

`2 3 1⍉` the rows-to-layers, columns-to-rows, layers-to-columns transposition of

`,` the wrapper followed by the gift

`)⍣6` applied six times

In other words, we add a layer of wrapper on the top of the array, then warp it so that the next side gets rotated into the top layer position, ready for another round of wrapping. This is repeated six times, with the final warping repositioning all axes to the original order.

TryAPL online!
> 4 votes

# Answer
# , ~~16~~ 15 bytes

```
[h"2[h"1 h=.,,[

```

This is an anonymous verb. Try it online!

Thanks to Adám for 1 byte!

## Explanation

```
[h"2[h"1 h=.,,[  Wrapper is x, present is y.
            ,    Prepend x to y
             ,   then append
              [  x.
                 This gives x y x, and the wrapper automatically spreads to form 2D slices.
         h=.     Save the above operation (not its result) to h.
    [h"1         Apply h to x and every 2D slice of the previous result.
[h"2             Apply h to x and every 1D slice of the result of that.

```
> 8 votes

# Answer
## JavaScript (ES6), 97 bytes

```
(a,e)=>[c=[,,...b=a[0]].fill(d=[,,...b[0]].fill(e)),...a.map(a=>[d,...a.map(a=>[e,...a,e]),d]),c]

```

Where `a` is the three-dimensional array and `e` is the wrapper. Automatically converts a two-dimensional array of strings to a three-dimensional array of characters. Alternative version for when `a` is a two-dimensional array of strings and `e` is a character and you want to return a two-dimensional array of strings:

```
(a,e)=>[c=[,,...a[0]].fill(d=e.repeat(a[0][0].length+2)),...a.map(b=>[c,...b.map(s=>e+s+e),d]),c]

```
> 4 votes

# Answer
# Python, ~~106~~ ~~104~~ 126 bytes

```
def w(g,c):x=len(g[0][0])+2;k=[[c*x]*(len(g[0])+2)];return k+[[c*x,*[c+"".join(str(k)for k in j)+c for j in i],c*x]for i in g]+k

```

Called as `w(gift, wrapping character)`. Can use the string and the array notation. Try it online!
> 3 votes

# Answer
# Octave, ~~23~~ 27 bytes

```
@(a,p)padarray(a,[1 1 1],p)

```

array: `a`
padval: `p`

It can be called as :

```
(@(a,p)padarray(a,[1 1 1],p))([1 2;3 4],40)

```

try (paste!)it on Octave Online

note: previous answer assumed default padval
> 3 votes

# Answer
# Perl 6, 86 bytes

```
->\a,\w{my @z=[[w xx a[0;0]+2]xx a[0]+2]xx a+2;@z[1..a;1..a[0];1..a[0;0]]=a[*;*;*];@z}

```

A lambda that takes the 3D array and wrapping character as arguments.

* It first creates a 3D output array of the correct size, filled with the wrapping character.
* Then it uses the array slice syntax to assign the values of the original array into the correct slots of the new array, in one fell swoop.
> 3 votes

# Answer
# 05AB1E, ~~34~~ ~~33~~ 31 bytes

```
vy¬gÌ²s×S©svy².ø¼}®)ˆ}¾F®})¯s.ø

```

Try it online! (string) or Try it online! (numerical)
> 1 votes

# Answer
## Ruby, 89 bytes

```
->a,b{(w=[[z=b*2+a[0][0].tr('^|',b)]*(2+a[0].size)])+a.map{|x|[z]+x.map{|y|b+y+b}+[z]}+w}

```

Have I ever told you I'm only here to learn ruby? :-)
> 1 votes

---
Tags: code-golf, array, 3d
---


title: Crash IRB (interactive Ruby)

text:
# Question
Title: Crash IRB (interactive Ruby)
Ruby comes with a built-in REPL, which is quite handy.

Your challenge is to crash it in the least amount of code!

The definition of "crash" is "make it exit in an **unintended** way." This means `exit`, `quit`, `abort`, `irb_exit`, `irb_quit`, et. al. are not valid answers.

Furthermore, you may **not** cause any side-effect to any other part of the system. For example, ``rm -rf /`` is not valid either.

Any version 1.9.3 or above is valid. If your code only works on a specific version of Ruby, you may specify that in the answer.

The final restriction is that you may not rely on any gems.

This is , so the shortest code that crashes IRB will win!

# Answer
> 6 votes
## 5 characters

```
ENV=0

```

(inspired by @daniero's answer)

# Answer
> 17 votes
# 16 characters

```
String=0
String=0

```

Not the shortest, but I think it's funny that it doesn't crash until the second line. Generates roughly 20 lines of text before IRB exits. For some reason it cannot be shortened to for instance `2.times{String=0}`.

---

**edit**

Of all the answers so far, this is the only one that has worked for me (and it works in all versions I could get my hands on), and I've tested all of them in these versions:

On whatever kind of Linux I get when `ssh`'ing into my university:
```
ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-linux]
ruby 1.8.5 (2006-08-25) [x86_64-linux]

```
Mac OS X Mavericks default:
```
ruby 2.0.0p247 (2013-06-27 revision 41674) [universal.x86_64-darwin13]

```
Installed through Homebrew on OS X:
```
ruby 1.9.3p448 (2013-06-27 revision 41675) [x86_64-darwin12.4.0]

```

---

**edit 2**

# 7 characters

Combining my first version (and/or @Howard's answer, for maximum cross reference) with @chinese perl goth's answer:

```
STDIN=0

```

# Answer
> 10 votes
# 12 chars

ruby is not exactly my cup of tea, but I've just found out that irb acts funny when I close the stdin :)

```
$stdin.close

```

tested on irb 0.9.6(09/06/30) and ruby 1.9.3p194

# Answer
> 7 votes
# ~~10~~ 9 chars

A shorter variant on @daniero's answer:

```
String=1
-

```

This works at least in the default OS X Mavericks Ruby (2.0.0).

The answer basically relies on the fact that the Ruby `Token` function does a `case` on the input token. One of the cases checks against `String`, which has been redefined by the first line. This case fails, so the case falls through to the default, which assumes the object has an `ancestors` accessor (which it does not).

Because the "bug" is in the tokenizer, the first line won't fail because the line only takes effect after the parsing is finished. Thus, it only affects subsequent lines. Subsequent lines must contain some kind of operator in order to see the failure.

# Answer
> 6 votes
**5 characters**

```
$>=$<

```

Sets stdout to stdin which throws an error trying to open stdin for writing and crashes irb.

# Answer
> 5 votes
# 22 characters

```
def method_missing;end

```

Apparently it messes with some irb internals. (To fix it, add `self.` after `def`.)

# Answer
> 4 votes
# 12 characters

```
def send;end

```

As far as I know, there are four methods in the Object class which show this kind of behaviour:

```
send
method_missing
respond_to?
respond_to_missing?

```

# Answer
> 4 votes
# 5 Characters

```
IRB=0

```

Nothing disturbs IRB quite like redefining IRB.

# Answer
> 2 votes
# ~~12~~ 10 characters

```
exec"exec"

```

I don't know if this counts, because of the `exec`

# Answer
> 2 votes
# 8 characters

Similar to chinese perl goth's answer:

```
$>.close

```

`$>` is an alias for STDOUT.

# Answer
> 0 votes
# 26 + 1 = 27 characters

This isn't very golfy, but I was amused to discover it by accident and thought others might enjoy it.

```
class Fixnum;def +;end end

```

I added +1 to the score because you have to press Enter a second time after entering the above (but not +2 because no one else counted Enter).

---
Tags: code-golf, ruby
---


title: Positional Awareness

text:
# Question
Title: Positional Awareness
# Positional Awareness

Your task is to generate a program that, for every permutation of its characters (which includes the original program), outputs the positions of every character relative to the original program.

If your program is

```
Derp

```

you must output

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

```

(or some equivalent). This is because `D` is in the `0`th position, `e` is in the `1`st, r the `2`nd, and `p` the `3`rd.

Let's take another program which is the original program, but with its characters permuted:

```
epDr

```

You must output

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

```

because `e` is in the `1`st position of the original program, `p` is in the `3`rd position, `D` the `0`th, and `r` the `2`nd.

If the original program has two repeating characters:

```
abcda -> [0, 1, 2, 3, 4]

```

Then for the permutation, the `0` and the `4` in the array must be in ascending order:

```
baadc -> [1, 0, 4, 3, 2] (0 first, then 4)

```

# Rules:

* Your program must contain at least two unique characters.
* At most `floor(n/2)` characters are to be the same.

```
 aabb (acceptable)
 aaaabc (not acceptable, only floor(6/2) = 3 a's allowed)

```
* Your program's output can be either an array (or something similar) containing all the characters' positions in order, or a string with any delimiter, so these are perfectly fine:

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

```

# Answer
> 20 votes
# Actually, 2 bytes

```
10

```

Try it online!

This prints

```
0
1

```

while the (only) other permutation

```
01

```

prints

```
1
0

```

### How it works

In Actually, consecutive digits are parsed separately, so `10` pushes **1** on the stack, then **0** on top of it.

When the program finishes, the stack is printed top to bottom, so it prints **0** first, then a linefeed, then **1**.

The derranged program `01` does the same, in the opposite order.

# Answer
> 7 votes
# Jelly, 2 bytes

```
;J

```

Try it online!

Outputs: `[0, 1]`

Other permutation `J;` outputs: `[1, 0]`

### How it works:

```
;J
;          Concats 0 with...
 J         [1...len(z)], here just [1]

J;
J          [1...len(z)], here just [1]
 ;         ...Concatted with 0

```

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


title: D&D Skill Challenges

text:
# Question
Title: D&D Skill Challenges
In *Dungeons & Dragons*, almost everything is decided by rolling a die. Typically, if the roll is greater than or equal to a specified value, your attempt at doing whatever you wanted to do succeeds, and fails otherwise. Most commonly, a 20-sided die (aka d20) is used to roll.

Other times, the skill challenge system is used. It is similar to the simple system described above, but success is determined by whether or not the player(s) succeed individual rolls a certain number of times before failing a certain number of times. For example, the player(s) may be trying to pick multiple locks on a door with a limited number of lockpicks. Individual successful rolls represent successfully picking one of the locks, and individual failing rolls represent breaking a lockpick. Overall success would mean successfully picking all of the locks before breaking all of the lockpicks.

Furthermore, certain rolls can be critical rolls. On a d20, rolling a 1 is a critical failure, resulting in immediately failing the entire challenge (in the above example, the player(s) might accidentally alert a guard). Rolling a 20 is a critical success, resulting in immediately succeeding the entire challenge (in the above example, the player(s) might find a set of keys to the locks, removing the need to pick them). In the case of a critical roll, the challenge is immediately over and the outcome decided, regardless of the previous number of successes and failures.

In this challenge, you will be given a difficulty, the number of successes needed, and the number of failures at which the challenge is failed. You must simulate a player attempting the challenge, and output the result.

### Input

3 integers, representing the value that must be met or exceeded to succeed at an individual roll, the number of successes needed to succeed at the challenge, and the number of failures at which the challenge is failed. The order and format of the inputs does not matter, as long as you specify what order you will be using. The difficulty will be between 1 and 20, inclusive, and the number of successes and failures will both be between 1 and 100, inclusive.

### Output

The results of each of the d20 rolls (integers, in order), and the overall result of the challenge (a truthy/falsey value). The format does not matter, as long as the individual results are in order, the overall result either comes before or after all of the individual rolls (you can't output the overall result in the middle of the rolls, for example), and you specify what output format you use and use it consistently.

### Examples (values in parentheses are for explanation and need not be included):

Input:

```
12 5 3 (difficulty successes failures)

```

Output:

```
15 (success, 1-0)
10 (failure, 1-1)
5  (failure, 1-2)
16 (success, 2-2)
12 (success, 3-2)
15 (success, 4-2)
19 (success, 5-2)
True (overall success)

```

Input:

```
15 2 3 (difficulty failures successes)

```

Output:

```
0  (overall failure)
15 (success, 1-0)
12 (failure, 1-1)
13 (failure, 1-2)

```

Input:

```
5 5 10 (successes failures difficulty)

```

Output:

```
11 (success, 1-0)
5  (failure, 1-1)
20 (critical success)
1  (overall success)

```

Input:

```
3 10 3 (failures difficulty successes)

```

Output:

```
12 (success, 1-0)
11 (success, 2-0)
1  (critical failure)
False (overall failure)

```

### Rules

* This is , so shortest code in bytes wins
* You must randomly choose an integer value between 1 and 20 (inclusive) for each roll. Each value should have an equal probability of being chosen (or as close to equal as possible).

# Answer
> 2 votes
# JavaScript, ~~83~~ ~~78~~ ~~76~~ 75 bytes

```
F=(d,f,s)=>!s||f&&(r=~(Math.random()*20))+""+F(d,~r&&f-(k=d>-r),r+20&&s-!k)

```

This code recursively counts down successes and failures as they happen. When either successes (`s`) or failures (`f`) have counted down to `0`, we finish with the `true` value `!s` when `s` is `0` or with the falsy value of `f` when `f` is `0`.

Output is of the regular-expression form `/^(-\d{1,2})+(0|true)$/` (or, more strictly, `/^(-[1-9]|-1[0-9]|-20)+(0|true)$/`). That is, the input has a leading hyphen, then roll values delineated by hyphens, and finally the ultimate outcome (`0` or `true`), which is not delineated from the final roll. However, this is still an unambiguous grammar because the utilmate outcome and final roll can always be distinguished: the last character of the output (either `0` or `e`) is always indicative of the outcome, and a final `0` is always read separately from the number(s) of the final roll.

Sample outputs for `F(11,3,4)`:

```
-3-14-12-16-16true  // normal success
-2-12-20true        // critical success
-20true             // first-roll critical success
-18-2-8-14-18-90    // normal failure
-18-12-10           // critical failure
-10                 // first-roll critical failure
-4-16-4-100         // normal failure where last roll is a 10

```

## Explanation:

This code works by rolling a *negative* d20 and (ab)using the negative signs as delimiters.

```
F=(d,f,s)=>    // define function F(difficulty, fails, successes)

!s||   // if zero more successes needed, return true
f &&   // if zero more failures needed, return 0

    (r=~(Math.random()*20)  // add negative d20 to output, store in `r`
    +""+                    // string concatenation
    F(                      // recursive call to F with changed fail/success
       d,                   //   pass along d
       ~r                   //   if r is -1, zero more fails needed
          &&f-              //   otherwise, reduce fails needed by
              (k=d>-r),     //   the boolean `d>-r` (and store in k)
       r+20                 //   if r is -20, zero more successes needed
           &&s-!k           //   otherwise, reduce successes needed by
                            //   the opposite of `k` (which indicates a fail)
      )
   ]

```

Number-minus-boolean expressions work because `true` and `false` are cast to `1` and `0` in a numeric context. In this case, `d>-r` will be `1` if the roll is a failure and `0` if it was a success.

# Answer
> 4 votes
## Python, 134 bytes

Thanks Pietu1998 for the bytes saved

```
from random import*
def g(a,b,c):
 s,z=[],[c,b]
 while z[0]*z[1]:d=randint(1,20);z[a<d]-=[1,z[a<d]][d in[1,20]];s+=[d]
 return[z[0]]+s

```

Pretty simple, can probably be golfed a bit more, but we needed something to kick this off. Try it online.

# Answer
> 3 votes
## Pip, 39 bytes

Someone said they wanted to see a solution in a golfing language.

```
Wc&b{Pd:1+RR20d<a?--c--bc*:d>1b*:d<20}c

```

I'm pretty sure this doesn't use any language features newer than the question. Takes input as command-line args in this order: difficulty, successes required, failures required. Outputs 0 for overall failure or nonzero for overall success. Try it online!

The approach is a fairly straightforward while-loop strategy, with a trick or two taken from other solutions. Here's a version with comments, whitespace, and some extra output:

```
; a,b,c are initialized to the cmdline args
; a = difficulty (roll >=a succeeds, roll <a fails)
; b = required successes to succeed the task
; c = required failures to fail the task
; d = single die roll

; Loop while c and b are both nonzero:
W c&b {
 ; d gets 1+randrange(20); output it
 O d:1+RR20
 ; If d<a, decrement req'd failures, else decrement req'd successes
 d<a ? --c --b
 ; Verbose output for the ungolfed version
 P " (" . (d=1|d=20 ? "critical " "") . (d<a ? "failure" "success") . ")"
 ; If d=1, req'd failures is * by 0 (becomes 0), else * by 1 (unchanged)
 c *: d>1
 ; If d=20, req'd successes is * by 0 (becomes 0), else * by 1 (unchanged)
 b *: d<20
}
; c, remaining failures, is the output: 0 if overall failure, nonzero if overall success
c . " (overall " . (c ? "success" "failure") . ")"

```

# Answer
> 2 votes
## Python 2, 123 121 bytes

```
from random import*
def f(a,b,c):
 while c*b:
    r=randint(1,20);print r;c-=r<a;b-=r>=a
    if r in[1,20]:return r>9
 return c

```

(This answer mixes spaces and tabs, so the first indentation level is a single space, while the second is a single tab.)

The function `f` takes the following arguments:

`a`, the threshold for an individual die roll to count as a success,

`b`, the number of successes needed for overall success,

`c`, the number of failures needed for overall failure.

On each die roll either `b` or `c` is decremented (but not both). As long as both are positive, it loops again, except in the case of critical failure or critical success.

Assuming no critical successes or failures, when the loop finishes either `b` or `c` will be zero, but not both. In that case the function just returns the current value of `c`, which is zero (Falsey) if we exhausted all of our failures, and positive (Truthy) if we succeeded.

As a bonus, the output tells you how many failures you had remaining, which is nice in case there's (say) more locks to pick later. (Unless it terminated at a critical failure or success, in which case the output will be a boolean instead of an int.)

# Answer
> 1 votes
# Ruby 2.2, 75 bytes

```
f=->(v,s,f){p(r=rand(20)+1)<2?f=0:r>19?s=0:r<v ?f-=1:s-=1while s*f>0
p s<1}

```

Basic iterative solution. Example run:

```
f[12, 5, 3]

```

Might output:

```
11
17
8
14
7
false

```

You can see it running on IDEONE here.

# Answer
> 0 votes
# VBA 180 Bytes

```
Sub P(d,s,f):k=1
Do While x<s And v<f:r=Int(20*Rnd()+1)
If r=20 Then x=s
If r=1 Then v=f
If r>=d Then: x=x+1: Else: v=v+1
Debug.Print r:Loop:If v>=f Then k=0
Debug.Print k:End Sub

```

Example Output

```
P 12,5,3
 18
 2
 19
 8
 11
 0

```

The last Digit of output will be a `0` for `False` or a `1` for `True` . Each Roll is separated by a newline. This uses VBA built in RNG `rnd()` which is know for being Not So Random , But this should fulfill the requirements as best as possible.

```
Sub P(d,s,f)
k=1
Do While x<s And v<f               'Keep Rolling while Current Successes and Failures are less then the Maximum Allowed
r=Int(20*Rnd()+1)                'Creates a Randomish Number between 1 and 20
If r=20 Then x=s                   'Checks for Crit Success
If r=1 Then v=f                    'Checks for Crit Failure
If r>=d Then: x=x+1: Else: v=v+1   'Increments Current Success or Fails
Debug.Print r                      'Prints (Could us MSGBOX, it is shorter)
Loop
If v>=f Then k=0                   'Checks & Changes Total Outcome to False
Debug.Print k                      'Prints (Could us MSGBOX, it is shorter)
End Sub

```

# Answer
> 0 votes
# SpecBAS - 165 bytes

```
1 INPUT d,s,f
2 DIM p(2)
3 DO
4 r=1+INT(RND*20): ?r
5 IF r IN [1,20] THEN EXIT
6 INC p((r>=d)+1)
7 LOOP UNTIL p(1)>=f OR p(2)>=s
8  ?IIF$(r=1 OR p(1)>=f,"fail","success")

```

Input should be entered in difficulty, successes, failures order.

The new release of SpecBAS now allows "?" instead of `PRINT` and removes the need for `LET` in front of variable assignments, so this was a nice way to try them out.

As arrays are 1-based by default, line 6 returns 0/1 if roll beats difficulty and adds 1 to update the right index.

# Answer
> 0 votes
# Perl 6,  ~~101~~  99 bytes

```
->$/ {(1..20).roll(*).map({$1*$2||last;$2-=$0>$_;$2=0 when 1;$1-=$_>=$0;$1=0 when 20;$_}).eager,$2}

```

```
# 101 bytes
->$/ {
  (1..20).roll(*).map({  # roll an infinite sequence, and map over them
    $1*$2||last;         # stop if either counter is 0
    $2-=$0>$_;           # decrement failure counter when a failure
    $2=0 when 1;         # set failure counter to 0  when a critical failure
    $1-=$_>=$0;          # decrement success counter when a success
    $1=0 when 20;        # set success counter to 0  when a critical success
    $_                   # the rolled value
  }).eager,$2            # the value of failure counter
}

```

Input is a mutable array containing difficulty, successes, failures

Output is a two element list, first element is a list of the rolled values, second element is the number of failures remaining.

Usage:

```
# give it a name for ease of use
my &code = {...}

for ^10 { say code [12, 5, 3] }

```

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

```

---
Tags: code-golf, game, random
---


title: Recamán's triangular fibonacci

text:
# Question
Title: Recamán's triangular fibonacci
This challenge is based upon three sequences, below are their formulae:

> > a1 = 0; for n \> 0, an = an-1 \- n
>
> if positive and not already in the sequence, otherwise
>
> > an = an-1 \+ n

> > an = (Φn – (–Φ)–n) / √5
>
> where Φ denotes the golden ratio, and
>
> > a1 = 0

> a1 = 0; an = n * (n+1) / 2

Your task is to take specified nth terms of each sequence and perform certain basic mathematical operations on them, namely addition, subtraction, multiplication, division, and the support of parentheses, nothing more is required.

Input is always in infix notation, and output formats are unrestricted.

Your code must be able to handle all real numbers from -10,000,000 to +10,000,000

Standard loopholes apply, and built-in functions for these sequences are not allowed.

Examples:

(These examples use an example output format of ***1R*** = *1st term of R*, ***3430T*** = *3430th term of T, and so on, however you are free to use whichever output format you desire.*)

Examples:

* (1R + 1F) * 3

= ( 0 + 0 ) * 3

= 0

* (1R * 1F) - 3

= ( 0 * 0 ) - 3

= - 3

* (1R + 2R) + (57R - 35R) / (51R - 41R) ) + (31F + 32F) - (54T)

= { \[ (0 + 1) + (30 - 113) \] / (33 - 38) } + (832040 + 1346269) - (1431)

= { \[ (0 + 1) + (-83) \] / (-5) } + (2178309) - (1431)

= \[ (1 - 83 ) / (-5) \] + (2178309) - (1431)

= (-82 / -5) + (2178309) - (1431)

= (16.4) + (2178309) - (1431)

= 2176894.4

# Answer
> 2 votes
## JavaScript (ES6), ~~164~~ ~~163~~ 148 bytes

Input format: `F(n), R(n), T(n)`

```
s=>eval(s.replace(/[FRT]/g,c=>`(F=n=>${c<'R'?'n>1?F(n-2)+F(n-1):n':c>'R'?'n*++n/2':'(N=>{for(l=[1];--n;)l[x=y+=++N>y|l[y-N]?N:-N]=1})(x=y=0)|x'})`))

```

### Example

This may take a few seconds to complete.

```
let f =

s=>eval(s.replace(/[FRT]/g,c=>`(F=n=>${c<'R'?'n>1?F(n-2)+F(n-1):n':c>'R'?'n*++n/2':'(N=>{for(l=[1];--n;)l[x=y+=++N>y|l[y-N]?N:-N]=1})(x=y=0)|x'})`))

console.log(f("((R(1) + R(2)) + (R(57) - R(35))) / (R(51) - R(41)) + (F(30) + F(31)) - (T(53))"));
```

# Answer
> 1 votes
# Perl, ~~201~~ ~~199~~ 169 + 1 = 170 bytes

Run with the `-n` flag.

Whitespace is provided for readability and is not part of the code.

```
sub R{
  $_=pop;
  %m=(@_=0,1);
  $m{push@_,$m{$a=$_[-1]-@_}||$a<0?$a+2*@_:$a}=1 for 2..$_;
  pop
}
sub F{
  @_=(0,1,@_);
  push@_,$_[-1]+$_[-2]for 3..pop;
  pop
}
sub T{
  ($_=pop)*$_++/2
}
say eval

```

Pretty straightforward. `R` calculates the nth Recaman number, `F` calculates the nth Fibonacci number, and `T` calculates the nth Triangular number. The script accepts input of an expression with terms such as `R(##)`, `T(##)`, and `F(##)`, and evaluates it.

I'm sure I can reduce the byte-count for `R`, but I'll have to spend more time thinking about it.

# Answer
> 1 votes
## Ruby, ~~135 132~~ 129 bytes

```
->s{R,F,T=->x{*y=r=0;(x-1).times{|i|r<<y;y=r-[z=y+~i]!=r||z<0?y-~i:z};y},->x{a,b=1,0;(x-1).times{a=b+b=a};b},->x{x*~-x/2};eval s}

```

Input format: string using the sequence names and subscript. Example:

```
( (1R + 2R) + (57R - 35R) / (51R - 41R) ) + (31F + 32F) - (54T)

```

becomes

```
"( (R[1] + R[2]) + (R[57] - R[35]) / (R[51] - R[41]) ) + (F[31] + F[32]) - (T[54])"

```

Sorry for adding the missing bracket to the example, it wouldn't work otherwise. :-)

### Explanation

The `eval`is using the definition of R, T, and F functions.

Fibonacci: my own entry in the Fibonacci contest: https://codegolf.stackexchange.com/a/103329/18535 changed to start from 0 instead of 1.

Recamán: inspired by Martin Ender's answer: https://codegolf.stackexchange.com/a/37640/18535 then golfed away a couple of bytes.

Triangular: starting from 0, instead of `n*(n+1)/2` I could use `n*(n-1)/2`

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


title: Snowman Bowling

text:
# Question
Title: Snowman Bowling
*(related/inspired by: Draw a bowling formation)*

A fun pastime in the winter months here is to perform snowman bowling, using a large ball (like a basketball) and tiny snowman figures. Let's recreate this in ASCII.

Each snowman consists of the following:

```
(.,.)
( : )

```

Here is the alignment of the ten snowman "pins"

```
(.,.) (.,.) (.,.) (.,.)
( : ) ( : ) ( : ) ( : )
   (.,.) (.,.) (.,.)
   ( : ) ( : ) ( : )
      (.,.) (.,.)
      ( : ) ( : )
         (.,.)
         ( : )

```

These "pins" are labeled from `1` to `10` as

```
7 8 9 10
 4 5 6
  2 3
   1

```

So far, so standard. However, unlike normal bowling, the snowman pins are merely flattened and not totally removed. This is done by someone needing to manually flatten the snow of any pins that were struck. A flattened snowman is represented by `_____` (five underscores), with whitespace above. Here is an example with the `1 3 5 6 9 10` pins flattened (meaning only the `2 4 7 8` pins remain):

```
(.,.) (.,.)
( : ) ( : ) _____ _____
   (.,.)
   ( : ) _____ _____
      (.,.)
      ( : ) _____

         _____

```

### Input

* A list of integers from `1` to `10` in any convenient format representing which pins were struck and thus need to be flattened.
* Each number will only appear at most once, and the numbers can be in any order (sorted, unsorted, sorted descending) -- your choice, whatever makes your code golfier.
* The input is guaranteed to have at least one integer.

### Output

The resulting ASCII art representation of the snowman pins, with the correct pins flattened.

### Rules

* Leading or trailing newlines or whitespace are all optional, so long as the characters themselves line up correctly.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an online testing environment so people can try out your code!
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

### Examples

```
1 3 5 6 9 10

(.,.) (.,.)
( : ) ( : ) _____ _____
   (.,.)
   ( : ) _____ _____
      (.,.)
      ( : ) _____

         _____

1 2 3

(.,.) (.,.) (.,.) (.,.)
( : ) ( : ) ( : ) ( : )
   (.,.) (.,.) (.,.)
   ( : ) ( : ) ( : )

      _____ _____

         _____

1 2 3 4 5 6 8 9 10

(.,.)
( : ) _____ _____ _____

   _____ _____ _____

      _____ _____

         _____

```

# Answer
# 05AB1E, ~~45~~ 44 bytes

```
TF"(.,.)( : )"„ _5×{«4ä2ä¹N>åè})4L£Rvyø»}».c

```

Try it online!

**Explanation**

```
TF                                           # for N in [0 ... 9] do:
  "(.,.)( : )"                               # push string
              „ _                            # push the string " _"
                 5×                          # repeat it 5 times
                   {                         # sort
                    «                        # concatenate the strings
                     4ä                      # split the string in 4 parts
                       2ä                    # split the list in 2 parts
                         ¹N>åè               # if index+1 is in the input, push the first part
                                             # else push the second part
                              }              # end loop
                               )             # wrap stack in a list
                                4L£          # split list in parts of size 1,2,3,4
                                   R         # reverse list
                                    v        # for each list in list of lists
                                     yø      # transpose the list
                                       »     # join by spaces and newlines
                                        }    # end loop
                                         »   # join by newlines
                                          .c # centralize

```
> 7 votes

# Answer
## Snowman 1.0.2, 157 bytes

```
(()("789:045600230001"4aG::48nSdU][:#:]eq]/nM;AsI[:"_____"wR["     "wR/aC;:"( : )"wR["(.,.)"wR/aC;bI;:"  "wRdUaC;bI\#**\;aMaZ:" "aJ1AfL;aM;aM1AfL"
"aJ1AfL*))

```

Try it online!

When I saw this challenge, I knew I just had to answer in the perfect language...

This is a subroutine that takes input as an array of numbers and outputs as a string via the current permavar.

Wrapped for "readability" / aesthetics:

```
(()("789:045600230001"4aG::48nSdU][:#:]eq]/nM;AsI[
:"_____"wR["     "wR/aC;:"( : )"wR["(.,.)"wR/aC;bI
;:"  "wRdUaC;bI\#**\;aMaZ:" "aJ1AfL;aM;aM1AfL"
"aJ1AfL*))

```

Slightly ungolfed / commented version:

```
}
1wR`
3wR`aC`
5wR`aC`
6wR`aC`
9wR`aC`
*

((
    )(
    "789:045600230001"  // pin layout data
    4aG                 // split into groups of 4; we need each row twice
    :                   // map over groups of 2 output lines
        :               // map over pins (or whitespace)
            48nS        // subtract ascii '0'
            dU][        // duplicate the pin; we need it in the if{}
            :           // if (pin) {
                #:]eq]/nM;AsI[:"_____"wR["     "wR/aC;:"( : )"wR["(.,.)"wR/aC;bI
            ;:          // } else {
                "  "wRdUaC
            ;bI         // }
            \#**\       // maneuver the permavars around to discard pin
        ;aM
        aZ:" "aJ1AfL;aM
    ;aM
    1AfL                // flatten (simulate a flatmap)
    "
"aJ                     // join on newline
    1AfL                // flatten again into a single string
    *
))

#sP

```
> 46 votes

# Answer
# stacked, noncompeting, 118 bytes

I added `deepmap` and a few other things after this challenge, along with tons of bugfixes. Try it here!

```
@a((7 8 9 10)(4 5 6)(2 3)(1)){e:('(.,.)
( : )' '
_'5 hrep)a e has#'  'hcat
}deepmap{e i:'
 'i 3*hrep e,$hcat#/!LF+}map

```

## Ungolfed

```
{ a :
  ((7 8 9 10) (4 5 6) (2 3) (1))
  { e :
    (
      '(.,.)' LF '( : )' + +
      ' ' LF '_' + + 5 hrep
    ) @possible
    a e has @ind
    possible ind get @res
    '  ' @padding
    res padding hcat return
  } deepmap
  { e i:
    ' ' LF ' ' + + i 3 * hrep
    e ,
    $hcat insert!
    LF +
  } map
} @:bowl

(1 2 3 4 6 10) bowl out

```

Output:

```
(.,.) (.,.) (.,.)
( : ) ( : ) ( : ) _____
         (.,.)
   _____ ( : ) _____

      _____ _____

         _____

```
> 10 votes

# Answer
# Python 2, ~~248~~ ~~243~~ ~~241~~ ~~226~~ ~~224~~ ~~223~~ ~~221~~ ~~210~~ ~~206~~ ~~200~~ 177 bytes

-5 with thanks to @Rod

-15 again thanks to Rod

-1 using space calculation again from Rod

Looks longer due to more lines and indents but surprisingly 11 bytes shorter.

I'm sure this will go under 200...

I was right but not without 23 bytes worth of serious hints from @Pietu1998. Many thanks!

```
i,z=input(),0;m=['']*10;n=m[:]
for x in range(11):m[x-1],n[x-1]=('(.,.)',' '*5,'( : )','_'*5)[x in i::2]
for y in 10,6,3,1:
 for q in m,n:print' '*3*z+' '.join(q[y-4+z:y])
 z+=1

```

Try it online!

Takes input as a list of integers. Way too big at 248 but it works.
> 7 votes

# Answer
# C# ~~233~~ ~~221~~ ~~213~~ 203 bytes

method takes an int array a as the list of fallen pins

```
string S(int[]a){string o="",x=o,y=o,z=o;for(int i=10;i>0;){var c=a.Contains(i);x=(c?"      ":"(.,.) ")+x;y=(c?"_____ ":"( : ) ")+y;if(i==7|i<5&i--!=3){o+=$"{z}{x}\n{z}{y}\n";x=y="";z+="   ";}}return o;}

```

wrapped

```
string S(int[]a){string o="",x=o,y=o,z=o;for(int i=10;i>0;)
{var c=a.Contains(i);x=(c?"      ":"(.,.) ")+x;y=(c?"_____ ":
"( : ) ")+y;if(i==7|i<5&i--!=3){o+=$"{z}{x}\n{z}{y}\n";x=y="";
z+="   ";}}return o;}

```

expanded

```
string S(int[] a)
{
    string o = "", x = o, y = o, z= o;
    for (int i = 10; i > 0;)
    {
        var c = a.Contains(i);
        x = (c ? "      " : "(.,.) ") + x;
        y = (c ? "_____ " : "( : ) ") + y;

        if (i==7|i<5&i--!=3)
        {
            o += $"{z}{x}\n{z}{y}\n";
            x = y = "";
            z += "   ";
        }
    }
    return o;
}

```

knocked off a few bytes by suggestions in comments from Ghost, raznagul and auhmaan.
> 6 votes

# Answer
## Batch, 262 bytes

```
@echo off
for /l %%i in (1,1,10)do set s%%i=( : )
for %%i in (%*)do set s%%i=_____
set l=call:l
%l%%s7%%s8%%s9%%s10%
%l%"   %s4%%s5%%s6%
%l%"      %s2%%s3%
%l%"         %s1%
exit/b
:l
set s=%~1
set s=%s:( : )=(.,.)%
echo(%s:_____=     %
echo(%~1

```

Note: Lines 2, 3 and 4 end in a space, and also outputs a trailing space on each line. These can be removed at a cost of 5 bytes. Works by creating variables s1...s10 as the bottom halves of the snowmen, then flattening the ones given as command-line arguments. The appropriate rows are printed twice, the first time with the bottom halves replaced with the top halves. This saves 18 bytes over using two sets of top and bottom half variables.
> 5 votes

# Answer
# JavaScript, ~~154~~ 149 bytes

```
f=
a=>`6 7 8 9
_3 4 5
__1 2
___0
`[r='replace'](/\d|_/g,m=>++m?~a.indexOf(m)?'_____':'( : )':'   ')[r](/.*\n?/g,m=>m[r](/ : |_/g,s=>s=='_'?' ':'.,.')+m)

I.oninput=()=>O.innerHTML=f(JSON.parse(`[${I.value.match(/\d+/g)}]`))
I.oninput()
```

```
<input id=I value="1 3 5 6 9 10"><pre id=O>
```
> 4 votes

# Answer
# Pyth, 63 bytes

```
j.ejm+**3k;j;db)_CcR[1 3 6).e:*T]btMQ@m*T]*5d,d\_kc2"(.,.)( : )

```

A program that takes input of a list of integers and prints the result.

Test suite

*\[Explanation coming later\]*
> 3 votes

# Answer
# Pyth, 51 bytes

The code contains some unprintables, so here is an `xxd` hexdump.

```
00000000: 6a6d 2e5b 3233 5f6a 3b6d 4063 323f 7d6b  jm.[23_j;m@c2?}k
00000010: 5172 2235 2035 5f22 392e 2220 3b5b 8db2  Qr"5 5_"9." ;[..
00000020: 1778 a822 6472 4673 4d50 4253 2d34 2f64  .x."drFsMPBS-4/d
00000030: 323b 38                                  2;8

```

Try it online.

### Without unprintables, 52 bytes

```
jm.[23_j;m@c2?}kQr"5 5_"9").,.() : ("drFsMPBS-4/d2;8

```

Try it online.
> 3 votes

# Answer
# Javascript ~~178~~ 169 bytes

Essentially a port from my C# answer.

Takes an int array as the list of flattened "pins";

```
f=a=>{o=x=y=z="";for(i=10;i>0;){c=a.includes(i);x=(c?"      ":"(.,.) ")+x;y=(c?"_____ ":"( : ) ")+y;if(i==7|i<5&i--!=3){o+=z+x+"\n"+z+y+"\n";x=y="";z+= "   ";}}return o}

```

Wrapped:

```
f=a=>{o=x=y=z="";for(i=10;i>0;){c=a.includes(i);
x=(c?"      ":"(.,.) ")+x;y=(c?"_____ ":"( : ) ")+y;
if(i==7|i<5&i--!=3){o+=z+x+"\n"+z+y+"\n";x=y="";
z+= "   ";}}return o}

```

Expanded & Explained:

```
// function f takes parameter a (an array of ints)
f = a => {

    // four strings:
    // o: output
    // x: top row of snowmen
    // y: bottom row of snowmen
    // z: padding to indent the snowmen
    o = x = y = z = "";

    // loop from 10 to 1 (the pins)
    // remove the "afterthought" decrement - we can do that later
    for (i = 10; i > 0;) {

        // set the boolean c to whether the current pin has been flattened
        c = a.includes(i);

        // prefix x and y with the appropriate "sprite"
        // using a ternary if on c
        x = (c ? "      " : "(.,.) ") + x;
        y = (c ? "_____ " : "( : ) ") + y;

        // determine if we've reached the end of a row (i equals 7, 4, 2 or 1)
        // use non shortcircuit operators to save bytes and ensure we hit the final i, because...
        // we also decrement i here
        // (we didn't do this in the for loop declaration to save a byte)
        if (i == 7 | i < 5 & i-- != 3) {

            // concatenate our rows x & y,
            // prefixing them with the padding z,
            // postfixing them with a newline
            o += z + x + "\n" + z + y + "\n";

            // reset x and y rows
            x = y = "";

            // increase our padding for next time
            z += "   ";
        }
    }

    // return our final string (no semicolon to save a byte)
    return o
}

```
> 2 votes

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


title: We Are Number One, but …

text:
# Question
Title: We Are Number One, but …
# Task

Your task is to write a program that will take input, and then output the lyrics to We Are Number One, changing specific words. The input will contain both the words to be changed, and the replacement word.

## Input

The input will be in the following format:

```
one, two\n
net, villain\n

```

(`\n` is a newline, it's not actually visible.) The input is assured to be this format, and the first word will always be a word the lyrics contains. But you can take input in whatever format you prefer the most.

## Output

Your output will be the entire We Are Number One lyrics, but with the words that are given in the input swapped.

Original lyrics:

```
Hey!
We are Number One
Hey!
We are Number One

Now listen closely
Here's a little lesson in trickery
This is going down in history
If you wanna be a Villain Number One
You have to chase a superhero on the run
Just follow my moves, and sneak around
Be careful not to make a sound
(Shh)
(CRUNCH)
(No, don't touch that!)

We are Number One
Hey!
We are Number One
We are Number One

Ha ha ha
Now look at this net, that I just found
When I say go, be ready to throw
Go!
(Throw it on him, not me!)
(Ugh, let's try something else)
Now watch and learn, here's the deal
He'll slip and slide on this banana peel!
(Ha ha ha, gasp! what are you doing!?)

`Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba
We are Number One
Hey!
Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba
We are Number One
Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba
We are Number One
Hey!
Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba
We are Number One
Hey!
Hey!`

```
Source

## Rules

* The first word per input is assured to be in the lyrics.
* Your code must be case-insensitve (`one` as input will replace `One`)
* Trailing newlines are allowed.
* The input may be lower and uppercase, and the resulting output must have the same casing as the provided input.
* The input **can** try to replace e.g. `one` with `one`. If you replace it or not, is your choice.
* "Words" are sequences of characters seperated by space or commas, not by anything else (e.g. Hyphens), therefore `Ba` is not a valid input, but `Ba-ba-biddly-ba-ba-ba-ba` is.

## Example case

Input:

```
one, three
net, villain

```

Output:

```
Hey!
We are Number three
Hey!
We are Number three

Now listen closely
Here's a little lesson in trickery
This is going down in history
If you wanna be a Villain Number three
You have to chase a superhero on the run
Just follow my moves, and sneak around
Be careful not to make a sound
(Shh)
(CRUNCH)
(No, don't touch that!)

We are Number three
Hey!
We are Number three
We are Number three

Ha ha ha
Now look at this villain, that I just found
When I say go, be ready to throw
Go!
(Throw it on him, not me!)
(Ugh, let's try something else)
Now watch and learn, here's the deal
He'll slip and slide on this banana peel!
(Ha ha ha, gasp! what are you doing!?)

`Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba
We are Number three
Hey!
Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba
We are Number three
Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba
We are Number three
Hey!
Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba
We are Number three
Hey!
Hey!`

```

# Winner

This is , so the author of the shortest code in bytes wins!

# Answer
# PHP, ~~661~~ 652 bytes

```
for($s=base64_decode(gzuncompress("eJy1ks1u2zAQhO98itXJNqA8Q4DkULsHF2jzgx7X4tpkvSINkorAt+9QaoECyaE9VNoDQa44M99qL7Uzr0KchI7TeJJEX4KY/cfbeI5xJvW5SKBBYxataE6yycTYL0WFVHKOgXygkvxwlVTNk/OZUJfow4VsnJdjbJaI08OZapxo5hCYTlClF6/K6PhD+zs6HL8JlUiD49za8nST5CRFgl5xQmkK5vOUC52jKpyOlcb4JrknDpZyEL4iU5yCNQ9CA+KdJ6UQS7t15Oty6XK8/ebczmwfvz4fH/dYHGMP32HTOqfBQY1LtwOQv4b3Ec49IxNqxRoj3EGgwQpS+kWEDvRjTdRsvTqAP1DmCpZ9g5WEbW32i0txNp9iZ7ZPbUm+NCzOj/2ScBT43T5fXI8JFQyspIqwo0APQxHNslt8zFwQsAFT4RR6cuuAG2ArrAi4UaWs/rZiVW9lnQCMnzjgpZuIwsnvgD1dON86mluihqEN3La/obtvFB/47oTy1mpdVr8KEfnuXZnuXz94D/9/K3bLf/AT6bEYSw"));$t=fgetcsv(STDIN);)$s=preg_replace("#\b$t[0]\b#i",$t[1],$s);echo$s;

```

`gzinflate` is 3 bytes shorter than `gzuncompress`, but `gzcompress` has the shorter output.

And: The other PHP answer replaces substrings, not words. I´d save 8 more bytes with that.

**breakdown**

```
for($s="text";                              // init text
    $t=fgetcsv(STDIN);)                     // loop through STDIN lines
    $s=preg_replace("#\b$t[0]\b#i",$t[1],$s);   // replace pairs
echo$s;                                     // output

```
> 1 votes

# Answer
## PHP, 666 bytes

I suppose this is a rather appropriate code size for a song about Villains...

```
<?$s=gzinflate(base64_decode("zVLNitswEL4b/A6TUxLwPkNh99BkDynsT5ceJ9YkUjPWBEle47fvjJVCoWyh0EPRYMme8cz3ox3Nq7Z5I8BEcBiHIyX4Eqltdh8l6jrIBBxyoQg9Syae7ZdE6wyoiVKYgClniRAilBT6CyWtefEhg8ZZQjyDk2nJ68cilt6fYJYRJowR4ajD4WtgRi35FcI3LfH4TlAEeo/Z6vJ4peQpCejI4gnSGNvmccwFTsKscIcZBnmn3AFGBzkSXpScjNG1zT1Br0RPI0OUYn0HvCxta37z7P1Wt4en18PDzk4H6RR+XFvx2HsdiWW1reL8jZwfKLxDZahxU1pEseooUy9S6ZZxsIfvld+C8c2rGXvIOKu6namXCN1sZIpPMrXNZ1EMmxd7gVBMKB+GbmE8kIHfvJ59p74VtbGkWdkPpDPVKeJM2wpmwqJ8TUMmTLEDX3030R0hG9k1M2QO1yo1B0fVFoV/xKgLrkRsaH4S7eCM+bqCyYiZInYPnN2S1aebrPd4d9QIzvG8nG6hXPHut/iDDf+g0f+EpTay5w8="));foreach($argv as$a){@list($a,$b)=explode(",",$a);$s=str_ireplace($a,$b,$s);}echo $s;

```

Usage: `php numberOne.php one,three net,villain`
> 12 votes

# Answer
# Python 2.6, 695 bytes

```
import re
import zlib,base64

a=input().split(', ')
t = zlib.decompress(base64.b64decode(b'eJzNks+KGzEMxu9+Cs0pCcw+w8LuoUkPKbT7hx6VsRK70VjB9uzgt68000KhWyj0UiKCsYW+7/tp9tQ690qAmeA4jSfK8CmR279/7dxRZuBYKiUYWApx095MmwKo97UyAVMpkiAmqDkOV8rNPYVYQOsiMV3Ay7w862UVfT2cockEM6aEcFJReInMqB2/SH/VjoBvBFVgCFisrUw3yoGygOrVQJCn5D5OpcJZmNXp2GCUNyo9YPJQEuFVI8mUvHsgGDTdeWJIUm3qiNdl6PK8/RLCzm0fPz8fH/d6OEqvvtPGOqchqBrWbqdA/prdezT3qJm0Vqwi6k4FDFai2i8icIBvayKz9RoU/AEKNmXZG6xM6JvZryHL7D5I57ZPdoRYDUuIY78kHEn9bp8vodcNVV1YzU3DjqR6uhTiQrvFx4xVAxowJsyph7Au2AB7QtaAG2YoHG8rVo6e1g2o8RMm/cGNiNXJz4A9XLDcOpgtkWGwhXv7Grp7o/iAdyet6D235fSjNCLe/VZ/gv7PU/4TG8sU+/sO/HItbg==')).decode('utf8')
for i in xrange(0,len(a),2):
    t = t.replace(a[i],a[i+1])
print t

```

**Output**

Hey! We are Number three Hey! We are Number three

```
Now listen closely
Here's a little lesson in trickery
This is going down in history
If you wanna be a Villain Number three
You have to chase a superhero on the run
Just follow my moves, and sneak around
Be careful not to make a sound
(Shh)
(CRUNCH)
(No, don't touch that!)

We are Number three
Hey!
We are Number three
We are Number three

Ha ha ha
Now look at this villian, that I just found
When I say go, be ready to throw
Go!
(Throw it on him, not me!)
(Ugh, let's try something else)
Now watch and learn, here's the deal
He'll slip and slide on this banana peel!
(Ha ha ha, gasp! what are you doing!?)

Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba
We are Number three
Hey!
Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba
We are Number three
Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba
We are Number three
Hey!
Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba
We are Number three
Hey!
Hey!

```
> 1 votes

# Answer
## Python 3.4, 666 bytes

```
import zlib,base64,sys,re;s=zlib.decompress(base64.b85decode(b'c%03W&uSwv494$%3e71AOrN399-8!!!fyYtM`f(UZZuY~Jste^D|@=Iuw5whQX+z}g}(3mX|_~4^Fn};U_XrqitrG~Y(Ks>W-l|aPniM?EQz>iZ=_WM)cc&7fGH&j-~;67hcm@u9-U91brK&=U}bL4dYMIEcSk5P!Hgjw98?sZJu_;@U(&y{!{Hl278o3++LopZMMqIU^|B*~Q!w{a%5W5BbvhOp<&9Dg7%Zefc-BZV1#4~y22FRI7=q+Fb;NTU+Md@xo!gl8?T@GZ?N$$a>D6~w)y`>fs)o7SD3H&?`v|AmqNdVXz>26pm8iG^<-W<l4qlf`)!2(u^gBpclxAOXMM7I@fb62o=1w}Zeym6Exq@+i>|4f>)baZ1<a*sv)|KU0H10^Mr)wcjv}rzO%o?#GW5O7EaLbA-VoS)HaK#LX{bd2m-qNxIHGaULKe!OFI{6c@hZCkt2XjqSIn<Tg`aN{ljpGeo9kjf)T-xcqG$UU9Q~$&M<tg99Mw?RqegpM6EsO')).decode('utf8');
for a in sys.argv[1:]:x,y=a.split(', ');s=re.sub(x,y,s,99,2);
print(s)

```

Edits:

* Used regex replace instead of replace so that it works case insensitive.
* Used command line to get the parameters instead of input.
> 1 votes

# Answer
# 05AB1E, 842 bytes

```
•®_Ç²îü!úïæ²|ˆ9¶iˆtˆEC}#©ÿ®cÖ:|®¥÷K*œÒÅ5œ1‚ÂlÊÎ¤Nç·’±Ðá×ÍÐý5WÝã¢®ìÖ$hVbPGwÎ·M;9O|‰¶ÉèëøËöç¡QÒµ5‚aC}.*gbJÇ¦>);&f€ZÛ}íóÉh\„Ú;Ts§ÞT¿QZëDò©®#ÑSHžûd¦Óéó”ó\ê§ø5|PšÍÖcyÐÁ:hŒ02¨ÄùSûíi¯—àR›ÿR{3Í)Ú×E<u¥°¼:—jth€ƒWÆªâþ=—vJ†ÀJûy6Áv\TÈÞåšöQë£Âb„ˆ@Ò6^#ˆL*ÁöªAWçàˆÌä£#«ùÁ°è;sq¯¸GšìááÐ©–ob¾§m^¹+ò"-Å£‘u·ãÿ?ù÷7Á^)8GÑ<oßÝ7Åjœq–[—'XuDÔÈìïÃ÷áÓ´‚ñ)©™à$ÝS¢¦(ð8M'§›¬§³N(En"H#«Ÿß½µ`Å´½axxq\òÝP@HÓ‘š£m—‹váøÃGàhT™ËUc·€ô~¥CEw6G¥Âã”ú¾&º™e,"AÂy±²ÅÜÚMâ2qtBaaª.^`òÍ–Ú$¦~z¢PÇR²”6â#”½Ì0ÂVêž]oÉ¦s¯Ž½Ç˜ûRG™¸§I?™µ¦½ÀÓþæ8i‚%‘L#]ÒXÓ†A“r*Å;E%c¾0H;ø<½yÎ=^ù_í<ÃòõŽŸq!ùßN÷wP0q1¹‰~Õ¿´zÿgI,¸$ž¬…ÃÊGÖ¢e¸ŒHFMcw,Î()¼ü»T×–r{&h·q²¬5¡ýWÑÈú¬«ñÚRóD›<üŽ‹Nê*¹f¦›þÆYÓ–hýÂ}§l<Ñò<Ýù†ïÓi#‹k€ö#[ûlù_=¡ç·FÜØ]¢n©l›ÜÍ,ÉˆØrôN5Ô¸¹NGúoÝ][{½ãÚ;S*ÌåÙC€\À=k½;qU,pT$Ÿ5uÕœ¼§/›Kàô™eéù‚.Úæ·vx¾Xugvš–ûî?øc}|/žr¡¶µt…’öà,2;ˆ«=ÆF5£ØÓ¯~À|ýÝÓß]nLÔ<ëïÂåkQ`µ3DxÐ‘!´‚Ù7AÏmi¦nvgã…ñ•121B"012345678"¶" ()!,-'?"«‡¹',¡vyN²',¡è.:}

```

Try it online!

Simplistic approach, didn't do anything but replace symbols with integers, convert from base-121 to base-214. Then I decompress it, re-replace the characters and perform replacement on the words. For testing I suggest replacing pronouns with other pronouns.
> 1 votes

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