text:
List all ordered partitions of n
The challenge is to list all ordered partitions (composition (combinatorics)) of a given positive integer n. These are the lists of numbers from 1 to n whose sum is n. For example, given input n = 4, the result should be:

4
  1, 3
  3, 1
  2, 2
  2, 1, 1
  1, 2, 1
  1, 1, 2
  1, 1, 1, 1

The result can be in any order, but must contain each ordered partition once. This means that for n = 4, [1, 1, 2], [1, 2, 1] and [2, 1, 1] must all be part of the result.
Here's my own JavaScript code which achieves this:
function range(n) {
    for (var range = [], i = 0; i < n; range.push(++i));
    return range;
}

function composition(n) {
    return n < 1 ? [[]] : range(n).map(function(i) {
        return composition(n - i).map(function(j) {
            return [i].concat(j);
        });
    }).reduce(function(a, b) {
        return a.concat(b);
    });
}

Golfed, ES6 (169 167 119 109 105 89 85 bytes):
n=>n?[].concat(...[...Array(n)].map((x,i)=>i+1).map(b=>m(n-b).map(a=>[b,...a]))):[[]]

Welcome to the site! You need to specify a winning criterion. Code-golf maybe? Also, does it have to be in that specific order? If so, how is the order defined in general? I think lexicographical order would be more meaningful; or better yet, allow any order. You may want to use the sandbox for future challenges before posting them here

This is not strictly a duplicate since this one requires to output all lists, even those that are the same up to the ordering, whereas the previous one requires that only one of those is printed.

@Fatalize Here [2 1 1] is different from [1 2 1], unlike there. I suspect the approaches may be significantly different

To those who closed as dupe: are you sure the difference indicated in comments is not relevant? I'm not voting to reopen, as I think the hammer would work in that direction too

I'd suggest not accepting an answer yet (even though you can change it at any time) because seeing the question accepted on the front page might make people think it's over and not participate.

The usual term for these ordered partitions is "compositions".

Some languages might be well-suited to the following "stars and bars" algorithm: starting with a string of n 1s, there are n-1 possible places to insert a separator character such as _, and thus 2^(n-1) possible choices of separator insertions. These correspond to the 2^(n-1) compositions of n. For example, the eight compositions of 4 in the OP correspond to the eight strings 1111, 1_111, 111_1, 11_11, 11_1_1, 1_11_1, 1_1_11, and 1_1_1_1.

Pyth, 7 6 bytes
7 byte solution:
Pyth has an integer partition builtin ./, so 5 of the 7 bytes is getting the orderings.
{s.pM./

Try it online!
Explanation:
     ./  Integer partition (sorted by default)
  .pM    get all the orderings of each of the partitions as a nested list of lists of orderings
 s       Flatten by one layer
{        Remove duplicates

6 byte solution:
If you have a list, ./ will compute with orderings; all that remains is to make the lists numbers again.
lMM./m

Try it online!
Explanation:
     m  Get lists by gathering a list of [0, 1,...input] (I could use U as well)

   ./   Partition with orderings
 MM     Map an operation across each of the orderings lists of elements
l       where that operation is the length of the sublists

Amazing. This is the smallest one I've seen so far!

Haskell, 37 bytes
f 0=[[]]
f n=[a:x|a<-[1..n],x<-f$n-a]

xnor saved two bytes.

It looks like the more straightforward f n=[a:x|a<-[1..n],x<-f$n-a] is shorter.

you don't need the zero check (given positive integer n ... numbers from 1 to n)

f 0=[[]] just happens to be a shorter base case than f 1=[[1]] :)

@xyLe_ It's used a recursive base case.

ah sure, you are right, my bad

Python, 56 bytes
f=lambda n:[x+[n-i]for i in range(n)for x in f(i)]or[[]]

A recursive solution: The ordered partitions of n are a partition of some smaller i with 0<=i<n, followed by the remainder n-i as the last element. For a base case, n=0 only has the empty partition.

Simple, small and yet still amazingly readable. That's what I love about Python.

Python 2, 61 bytes
f=lambda n,s='1,':1/n*[eval(s)]or f(n-1,'1+'+s)+f(n-1,'1,'+s)

This isn't the shortest, but I really like the method because it's so weird.
Recursively generates and evaluates 2**(n-1) strings, like
1+1+1+1,
1,1+1+1,
1+1,1+1,
1,1,1+1,
1+1+1,1,
1,1+1,1,
1+1,1,1,
1,1,1,1,

for n=4. These strings evaluate to tuples representing all the partitions. Between any two 1's is either a +, joining them into a single number, or a ,, splitting adjacent sections.

Best non-recursive version I could do was import re lambda n:map(lambda n:map(len,re.finall('10*',bin(n))),range(1<<n-1,1<<n))

An explanation with the code would really make it beautiful.

JavaScript (Firefox 30-57), 63 bytes
f=n=>n?[for(i of Array(n).keys())for(a of f(i))[n-i,...a]]:[[]]

Firefox 30+ sounds like a special browser for the more mature users of the internet.

Probably doesn't get shorter than this...

Any way this can be ungolfed for JavaScript in other browsers?

@Eternity I can port @xnor's other answer for you: f=n=>n<2?[[1]]:f(n-1).map(([n,...a])=>r.push([1+n,...a],[1,n,...a]),r=[])&&r.

Mathematica, 40 bytes
Join@@Permutations/@IntegerPartitions@#&

Mathematica's built-in for integer partitions doesn't give all ordered partitions, so we have to generate all possible permutations of each of them, and then flatten the result.

CJam, 17 14 bytes
ri"X)"m*{~]p}/

Try it online!
Explanation
I know I said that using the Cartesian product is longer, but I ended up finding a way to use it more efficiently. I think that both approaches are interesting in their own right, so I'm putting them in separate posts.
This is still based on the idea that, we can choose n times between appending a 1 to the current partition or to increment the last element of the current partition. In this solution, we do this by generating 2n-1 different programs which correspond to these different choices.
ri      e# Read input and convert to integer N.
        e# Decrement.
"X)"m*  e# Get all strings of length N which consist of 'X' and ')'. If
        e# we treat these strings as CJam code then 'X' pushes a 1 and ')'
        e# increments the top of the stack.
        e# Note that some of these strings will begin with an increment that
        e# doesn't have anything on the stack to work with. This will result in
        e# an error and terminate the program. Luckily, the programs are ordered
        e# such that all programs starting with 'X' are first in the list, so
        e# we get to print all the 2^(N-1) permutations before erroring out.
{       e# For each of these programs (well for the first half of them)...
  ~     e#   Evaluate the string as CJam code. This leaves the partition as
        e#   individual integers on the stack.
  ]p    e#   Wrap the stack in a list and pretty-print it.
}/

I looked at this and thought "That can't be right, it would give an error when it evaluates the first string which starts with )". So I added ed and tested. +1 for creative abuse of error.

Jelly, 7 6 bytes
-1 byte thanks to @Dennis (convert from unary ḅ1, rather than sum for each for each S€€)
1ẋŒṖḅ1

TryItOnline
How?
1ẋŒṖḅ1 - Main link: n          e.g. 4
1ẋ     - repeat 1 n times          [1,1,1,1]
  ŒṖ   - partitions of a list     [[[1],[1],[1],[1]], [[1],[1],[1,1]], [[1],[1,1],[1]],
                                   [[1],[1,1,1]],     [[1,1],[1],[1]], [[1,1],[1,1]],
                                   [[1,1,1],[1]],     [[1,1,1,1]]]
    ḅ1 - from base 1 (vectorises)  [[1,1,1,1],        [1,1,2],         [1,2,1],
                                   [1,3],             [2,1,1],         [2,2],
                                   [3,1],             [4]]

Pure Bash, 51
This is a port of @xnor's brilliant answer, using multiple levels of bash expansions to achieve the desired result:
a=$[10**($1-1)]
eval echo \$[${a//0/{+,']\ $[}1'}],

Ideone.

The first line is simply an arithmetic expansion to create a variable $a containing 1 followed by n-1 zeros.
The first expansion ${a//0/{+,']\ $[}1'} replaces each 0 in $a with copies of the string {+,']\ $[}1'.  Thus n=4 we get the string 1{+,']\ $[}1'{+,']\ $[}1'{+,']\ $[}1'
This is prefixed with $[ and postfixed with ], to give $[1{+,']\ $[}1'{+,']\ $[}1'{+,']\ $[}1]
This is a brace expansion that expands to $[1+1+1+1], $[1+1+1] 1, $[1+1] $[1+1], $[1+1] 1 1,...
This is finally arithmetically expanded to give the required result.

Careful use of quotes, backslash escaping and eval ensures that the expansions occur in the correct order.

Ruby, 61 bytes
f=->n{n<1?[[]]:(1..n).map{|i|f[n-i].map{|x|x<<i}}.flatten(1)}

ungolfed
f=->n{
  n < 1 ?
    [[]]
  :
    (1..n).map { |i|
      f[n-i].map { |x|
        x << i
      }
    }.flatten(1)
}

usage
p f[4]
# => [[1, 1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 3], [2, 1, 1], [2, 2], [3, 1], [4]]

Hiya! Could you add a little bit of explanation for people (like me) who aren't familiar with Ruby?

x<<i is shorter than [i]+x.

@TimmyD I added an ungolfed code and the usage.

@ m-chrzan Thanks for your advice! I edited that.

Any reason .flatten(1) isn't .flatten 1 ?

@Cyoce If we use .flatten 1, but .flatten(1), syntax error occurs, doesn't it?

@cia_rana that's weird. Not sure why that's invalid syntax.

@Cyoce Probably something to do with the ternary condition. Ruby's ternary parsing has given a lot of trouble in the past.

05AB1E, 14 12 bytes
Saved 2 bytes thanks to Adnan
>G¹LNãvyO¹Q—

Explanation
>G              # for N in range(1..input)
  ¹L            # range(1, input)
    Nã          # cartesian product with N (all combinations of length N)
      v         # for each resulting list
       yO¹Q—    # if it's sum equals the input print it

Try it online!
The corresponding solution is 2 bytes shorter in 2sable.
2sable, 10 bytes
>GLNãvyOQ—

Try it online!

You can use — instead of iy, :).

@Adnan: Thanks! Forgot about that one.

Brachylog, 20 bytes
~lL#++?,L:=f:{:0x}ad

Try it online!
Explanation
This is a situation where you would think declarative languages would do well, but because of the overloading of + and the difficutly in writing a summing predicate which propagates constraints properly, they do not.
~lL                     L is a list of length Input
  L#+                   L is a list of non-negative integers
  L  +?,                The sum of the elements of L results in the Input
        L:=f            Find all values for the elements of L which satisfy those constraints
            :{:0x}a     Remove all 0s from each sublist of the result of Findall
                   d    Remove all duplicate sublists

I think this would propagate a lot faster if you focus on positive integers, and let the length of L be between 1 and input.

@mat This is what I originally did but this is longer. Since + also works on a single integer, I need to force . to be a list with ##, and since + also works on list of lists, I need to impose that the elements of . are integers with :#$a.

So the key issue is the defaultyness of the data structures: When a variable appears as arguments of operations that vectorize, you cannot tell whether the variable stands for a single integer or a (possibly nested) list. This is a tough issue, and there may be an elegant way to solve this, starting from your original version and searching for suitable language constructs that could simplify this. Nice work in any case!

CJam, 19 bytes
Lari{_1af.+1@f+|}*p

Try it online!
Explanation
CJam doesn't have a useful combinatorics built-in for integer partitions. So we'll do this manually. To find all the ordered partitions of an integer n, we can look at a list of n ones and consider every possible way to insert separators. Then we'll sum the 1s in each section. Example for n = 3:
1 1 1 => 3
1 1|1 => 2|1
1|1 1 => 1|2
1|1|1 => 1|1|1

I tried using a Cartesian product to generate all of these separators, but that ended up at 21 bytes. Instead I went back to this old technique for generating power sets (this is based on an old answer of Dennis's but I can't find it right now). The idea is this: to generate all partitions we can start from an empty list. Then n times we can make a binary decision: either we append a 1 (corresponds to a separator in the above example) or we increment the last value of the list (corresponds to not having a separator). To generate all partitions, we simply perform both operations at each step and keep all possible outputs for the next step. It turns out that in CJam, prepending and incrementing the first element is shorter, but the principle remains the same:
La       e# Push [[]] onto the stack. The outer list will be the list of
         e# all possible partitions at the current iteration, and we initialise
         e# it to one empty partition (basically all partitions of 0).
ri       e# Read input and convert to integer N.
{        e# Repeat this N times...
  _      e#   Duplicate the list of partitions of i-1.
  1af.+  e#   Increment the first element in each of these. This is done
         e#   by performing a pairwise addition between the partition and [1].
         e#   There is the catch that in the first iteration this will turn
         e#   the empty array into [1], so it's equivalent to the next step.
  1@f+   e#   Pull up the other copy of the list of partitions of i-1 and
         e#   prepend a 1 to each of them.
  |      e#   Set union. This gets rid of the duplicate result from the first
         e#   iteration (in all other iterations this is equivalent to concatenating
         e#   the two lists).
         e#   Voilà, a list of all partitions of i.
}*
p        e# Pretty-print the result.

Julia, 113 Bytes
f(N)=unique(reduce(vcat,(map(x->[permutations(x)...],[vcat([1 for _=i+1:N],sum([1 for _=N-i:N-1])) for i=1:N]))))

Non-recursive solution
Explained:

[vcat([1 for _=i+1:N],sum([1 for _=N-i:N-1])) for i=1:N] build a set of lists that sum to N, whose permutations will resemble the solution (e.g. for N=4: [[1,1,1,1],[1,1,2],[1,3],[4]])
map(x->[permutations(x)...],) Calculate all permutations
reduce(vcat,) combine them into a list of lists
unique() filter duplicates

We require submissions to be full programs or functions, so in this case you'll have to take N as input. You can make a lambda function by prepending N-> at the cost of 3 bytes.

@AlexA. ah, sorry the f(N)= got lost at copying, I've had it in when counting bytes

T-SQL, 203 bytes
Golfed:
USE master
DECLARE @ INT=12

;WITH z as( SELECT top(@)cast(number+1as varchar(max))a FROM spt_values WHERE'P'=type),c as(SELECT a*1a,a b FROM z UNION ALL SELECT c.a+z.a,b+','+z.a FROM c,z WHERE c.a+z.a*1<=@)SELECT b FROM c WHERE a=@

Ungolfed:
USE master --needed to make sure it is executed from the correct database
DECLARE @ INT=12

;WITH z as
(
  SELECT top(@)cast(number+1as varchar(max))a
  FROM spt_values
  WHERE'P'=type
),c as
(
  SELECT a*1a,a b
  FROM z
  UNION ALL
  SELECT c.a+z.a,b+','+z.a
  FROM c,z
  WHERE c.a+z.a*1<=@
)
SELECT b
FROM c
WHERE a=@

Fiddle

Mathematica 10.0, 44 bytes
An attempt without using partition-related builtins. From each ordered partition of size k, two successor partitions of k + 1 are generated: one by prepending 1, and the other by incrementing the first value.
Nest[##&[{1,##},{#+1,##2}]&@@@#&,{{1}},#-1]&

A funnier, but sadly 2 bytes longer way of implementing the same idea:
#@{1}&/@Tuples[Prepend[1]@*MapAt[#+1&,1],#-1]&

@alephalpha No, that wouldn't help as then I'd have to change the MapAt index to -1.

Haskell, 41 bytes
f 1=[[1]]
f n=do a:b<-f$n-1;[1:a:b,a+1:b]

Not the shortest Haskell solution, but I like that it doesn't use [..] ranges. Instead, it recursively computes the partitions of n as the partitions of n-1 with either a new 1 at the start or the first value one higher. This makes explicit why there's 2^(n-1) of them.

Mathematica, 53 bytes
Doesn't beat Martin Ender's answer, which uses the built-in IntegerPartitions function (and built-ins are totally fine by me).  (Nor does it beat feersum's answer, which I didn't see until too late.) But I wanted to practice a golfed recursive function.
If[#<1,{{}},Join@@Table[#~Append~j&/@#0[#-j],{j,#}]]&

Recursively generates all compositions, by generating all possible final numbers j and then calling itself on #-j where # is the input.

You can save a few bytes by defining an operator using Array instead of Table and avoiding the Append by using a list and Apply: ±0={{}};±n_:=Join@@Array[{##,n-+##}&@@@±#&,n,0]

What does @@ do?

It replaces the "head" of an expression. For example, f@@g[a,b] evaluates to f[a,b]. Here we're using the fact that a list like { { {1,1,1}, {2,1} } , { {1,2} }, { {3} } } invisibly has head List; so Join@@{ { {1,1,1}, {2,1} } , { {1,2} }, { {3} } } evaluates to Join@@List[ { {1,1,1}, {2,1} } , { {1,2} }, { {3} } ] evaluates to Join[ { {1,1,1}, {2,1} } , { {1,2} }, { {3} } ] evaluates to { {1,1,1}, {2,1}, {1,2}, {3} }.

Retina, 32 bytes
Byte count assumes ISO 8859-1 encoding.
.+
$*
+%1`1
!$'¶$`,!
!+
$.&
A`^,

Try it online!
Explanation
This works similar to my CJam answer. We go through a list N ones and at each position we take both branches of the binary decision a) increment the last value or b) start a new value at 1.
Stage 1
.+
$*

Convert the input to unary.
Stage 2
+%1`1
!$'¶$`,!

The + tells Retina to execute this stage in a loop until the output stops changing. The % tells it to split the input into lines before applying the stage and join them back together afterwards. By putting the % after the +, Retina splits and rejoins after each iteration. One iteration of the stage makes one of those decisions I mentioned and thereby bifurcates the current set of partitions.
How it actually works is that it matches a 1 (but only the first one as indicated by the 1 in front of the backtick), and replaces it with ! (which we'll use as the unary digit of our output), followed by the remaining 1s on this row (this increments the last value). Then on another line (¶) it prints the prefix of the current line, followed by ,!, which inserts a separator and then starts the next value at 1.
Stage 3
!+
$.&

This converts the runs of ! to decimal integers by replacing them with their length.
Stage 4
A`^,

And finally, we notice that we've generated twice as many lines as we wanted, and half of them start with a , (those where we initially made the decision of splitting, even though there wasn't anything to split after yet). Therefore, we discard all lines that start with a ,.

Perl, 44 bytes
Includes +3 for -n (code uses $' and $0 so it can't be run as a -e commandline)
Give number to partition on STDIN:
partitions.pl <<< 4

partitions.pl
#!/usr/bin/perl -n
$_=$&-$_.",$_$'",do$0for/\d+/..$&-1;print

If you don't mind extra spaces at the end of a line and an extra newline this 42 byte solution works too (run as perl -M5.010 partitions.pl):
#!/usr/bin/perl -n
$_=$`-$_." $_ $'",do$0for/\s/..$_-1;say

MATL, 15 bytes
:"G:@Z^t!XsG=Y)

Try it online!
Explanation
Given input n, this computes the Cartesian power with increasing exponents k from 1 to n; and for each exponent k selects the tuples that have a sum equal to the input.
:       % Take input n implicitly and push range [1 2 ... n]
"       % For each k in that range
  G:    %   Push [1 2 ... n] again
  @     %   Push k
  Z^    %   Cartesian power. Gives 2D array, say A, with each k-tuple in a row.
  t     %   Duplicate
  !     %   Transpose
  Xs    %   Sum of each column. Gives a row vector
  G=    %   True for entries that equal the input
  Y)    %   Use as logical vector into the rows of array A
        % End implicitly
        % Display stack implicitly

PHP, 125 Bytes
for($i=$n=$argv[1];$i<=str_repeat(1,$n);$i++)if(array_sum($a=str_split($i))==$n&!strpos($i,"0"))$r[]=$a;echo json_encode($r);

-4 Bytes for print_r($r); instead of echo json_encode($r); for the output
a recursive solution with 250 Bytes
function f($n){global$a;foreach($a as$x)foreach(range(1,$n)as$y)$a[]=array_merge((array)$x,[$y]);if(--$n)f($n);}$a=range(1,$w=$argv[1]);f($w-1);foreach($a as$z)if(array_sum((array)$z)==$w)$c[join("-",(array)$z)]=$z;echo json_encode(array_values($c));

Lua 214 203 182 bytes
function g(m, l, n,c)for i=1,m do if i+n < m then l[#l+1]=i;g(m,l,n+i,c+1)elseif i+n == m then l[#l+1]=i;print(unpack(l))end end for k=c,#l do l[k]=nil end end g(io.read()*1,{},0,0)

Ungolved version.
function g(m, l, n,c)
    for i=1,m do
        if i+n < m then
            l[#l+1]=i
            g(m,l,n+i,c+1)
        elseif i+n == m then
            l[#l+1]=i
            print(unpack(l))
        end
    end
    for k=c,#l do
        l[k]=nil
    end
end
g(io.read()*1,{},0,0)

Found a stray whitespace and removed an unnecessary variable to safe 11 bytes.
as it turns out, table.insert() is byte inefficient

Prolog, 81 bytes + 6 bytes to call
L*L.
[H|T]*L:-H>1,M is H-1,[M,1|T]*L.
[H,K|T]*L:-H>1,M is H-1,N is K+1,[M,N|T]*L.

Try it online!
Call with [4]*L., repeat with ; until all solutions have been presented.
Alternatively, if repeatedly pressing ; is not okay (or should be added to the byte count), call with bagof(L,[4]*L,M). which adds 17 bytes for the call.

J, 30 26 bytes
#&1<@(+/;.1)~2#:@(+i.)@^<:

Works by splitting the list of unary n by using the binary values of 2n.
Try it online!
Explanation
#&1<@(+/;.1)~2#:@(+i.)@^<:  Input: n
                        <:  Decrement n
             2         ^    Compute 2^(n-1)
                 (   )@     Operate on that
                   i.         Make the range [0, 1, ..., 2^(n-1)-1]
                  +           Add 2^(n-1) to each in that range
              #:@           Convert each in that range to binary
#&1                         Make n copies of 1 (n in unary)
     (     )~               Operate over each row on RHS and unary n on LHS
        ;.1                   Chop unary n starting at each 1
      +/                        Reduce by addition on each chop
   <@                           Box the sums of each chop

Actually, 17 16 bytes
This answer is partially based on Luis Mendo's MATL answer. Golfing suggestions welcome. Try it online!
;╗R`╜R∙i`M`Σ╜=`░

Ungolfing
         Implicit input n.
;╗       Duplicate n and save a copy of n to register 0.
R        Take the range of [1..n].
`...`M   Map the following function over the range. Variable k.
  ╛R       Push n from register 0 and take the range [1..n] again.
  ∙        Take the k-th Cartesian power of the range.
  i        Flatten that product.
`...`░   Push values of the previous map where the following function returns a truthy value.
          Variable L.
  Σ        Push sum(L).
  ╜        Push n from register 0.
  =        Check if sum(L) == n.
         Implicit return.

Actually, 17 16 15 bytes
This is an interesting fork of Martin Ender's CJam answer (the one with the Cartesian product), with a difference in implementation that I thought was interesting. When one of Martin's strings start with an increment, the errors prevent that string from being evaluated. In Actually, the error is suppressed and the string is evaluated anyway. This ends up giving the compositions of every k in the range [1..n].
Rather than try to remove the extra compositions, I took the n-1th Cartesian power of "1u" appended a "1" to the beginning of each string. This trick gives only the compositions of n. It is, unfortunately, longer than Martin's answer.
Golfing suggestions welcome. Try it online!
D"1u"∙`1@Σ£ƒk`M

Ungolfing
         Implicit input n.
D        Decrement n.
"1u"∙    Take the (n-1)th Cartesian power of the string "1u".
          In Actually, 1 pushes 1 to the stack and u is increment.
`...`M   Map the following function over the Cartesian power. Variable s.
  1@       Push a 1 to be used later.
  Σ        Summing a list of chars joins the chars into one string.
  £ƒ       Turn s into a function and call it immediately on the 1 in the stack.
  k        Take the whole stack and wrap in a list. This is a composition of n.
         Implicit return.


text:
A Mouse with Dynamite
You're a mouse. Your mouse friends have all been captured, and are unconscious and trapped in a maze that has only one entrance/exit. You happen to have a perfect map of the maze, so you can plot a solution to rush in and carry them all to safety. However, the maze is guarded with a security system that will trigger an alert if a threshold of 1000 is reached, causing you to be captured and fail your rescue mission.
From your previous investigations of the maze, each square you step (i.e., each horizontal or vertical movement -- mice can't move diagonally) adds 1 to the security system's counter. However, if you're carrying a weight (either a block of dynamite or an unconscious mouse friend), it instead adds 2 since it detects the additional pressure. The entrance/exit square doesn't have this security system, and so doesn't add to the counter.
You have an unlimited supply of dynamite that you've brought to the entrance, so you can simply blow up all the walls to free your friends. But you need to be cautious with doing so, since each explosion adds 50 to the counter from the concussive pressure. Additionally, you can only carry one thing at a time, either one mouse or one block of dynamite. Since each block of dynamite can only detonate one wall space, this means that if there are multiple walls in a row, you need to make an empty-handed trip back to the entrance to grab more.
Worked-through example
Suppose our maze looks like the following:
######
#M# E#
######

I'll use c for the counter. We start at the Entrance, move one square left while carrying dynamite, c=2. We detonate the dynamite to explode the wall, c=52. We move two squares left, empty-handed, to get c=54, and we're now standing on the mouse's square. We pick our friend up, and move 3 squares back to the Exit, but the last square doesn't count since it doesn't have any sensors, so that's only 2 squares with something on our back. That means that when we reach the exit with the final mouse, c=58, which is less than 1000, and therefore the mission succeeds.
Challenge
Given an input maze, output whether you, the mouse hero, can successfully rescue all trapped mice within the constraints outlined above, or whether the mission is a failure.
Input

A 2D maze in any acceptable format (multiline string, array of strings, etc.).
For this challenge, I will be using # for both the interior and exterior walls, M for the mouse friends, and E for the entrance.
The entrance will never be immediately adjacent to an interior wall (there will always be at least one space in which to move freely).
You can substitute any printable ASCII characters you wish so long as it's consistent. This does allow you to use two different symbols for interior walls vs. exterior walls, so long as you maintain consistency (e.g., if you choose to use @ for interior walls instead, and leave # for exterior, every interior wall must be @ and every exterior wall #).
The maze will always be completely bounded by walls, but is not necessarily rectangular. If desired, you can assume that the maze is padded with spaces to make rectangular input (optional).
The maze may have sections that are unreachable without dynamite.
You cannot dynamite the exterior walls of the maze.

Output
A truthy/falsey value. Truthy for "Yes, the mouse can rescue every other mouse" or Falsey for "No, the alarm system will be tripped."
The Rules

Either a full program or a function are acceptable.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Examples
Truthy examples, separated by blank lines.
#####
#M E#
#####

######
#M# E#
######

########
#E  # M#
#   #  #
#   #  #
#      #
########

#############################
#    ##      #       #      #
#  M ## M    #       #      #
#    ##      #   M   #    E #
#M   ##      #       #      #
#############################

###############
#MMMMMMMMMMMMM#
#MMMMMMMMMMMMM#
#MMMMMMMMMMMMM#
#MMMMMMMMMM MM#
#MMMMMMMMMMMME#
###############

Falsey examples, separated by blank lines
#############################
#M   ##      ##      ##     #
#  M ## M    ##      ##     #
#    ##      ##  M   ##   E #
#M   ##      ##      ##     #
#############################
#############################
                     ########
                     ########
                     #   #  #
                     # M # M#
                     ########

              #####
              # M #
              #####
              #####
              #####
              #####
###################
# # # ##   ## # # #
#M#M#M## E ##M#M#M#
# # # ##   ## # # #
###################
#######
######
#####
####
# M#
####

###############
#MMMMMMMMMMMMM#
#MMMMMMMMMMMMM#
#MMMMMMMMMMMMM#
#MMMMMMMMMMMMM#
#MMMMMMMMMMMME#
###############

The mice were furious (mild spoiler)

You're a mouse. Oh, huh. TIL.

@AlexA. Sorry that you had to learn it from a stranger on the Internet. ;-)

I suspect most people would have a hard time solving this with regular code, let alone golfing it. It's a great challenge that I unfortunately don't currently have time to work on.

Is it acceptable to have a different char for the external walls (as they're not destrcutible) ?

May we assume the maze is space padded so all lines have the same length ?

@Tensibai Yes, that's fine, so long as every external wall is the same character and every internal wall is the same character. I'll explicitly add that into the challenge.

@TonHospel Yes. I had thought I had that in the challenge, but apparently it's not listed.

Can an explosion only blow up one wall? It isn't ever explicitly said.

Will the entrance ever be adjacent to an internal wall?

@DanTheMan Yes, only one wall per explosion. I'll explicitly add that. That's a fair assumption that there's no internal wall immediately next to the entrance, given how the examples are laid out. I'll explicitly add that.

Can you walk over a mouse and not pick him up ? In particular can you do that while carrying dynamite ?

@TonHospel Sure, I don't see why not.

@Moshe Katz, sure you don't have time. You just don't wanna save the Mäuse.

@msh210 :-P Just for that, I think I'll have to find some time.

Perl, 216 215 bytes
Includes +2 for -0p
Give input on STDIN. Use % for external walls, # for internal walls, 0 for empty spaces, 8 for mice and r for the starting position. The whole boards must be padded so it forms a rectangle. You can transform and run the examples as:
cat dynamite.txt | perl -p0e 's/.+/$a^=$&/egr;s//sprintf"%-*s",length$a,$&/eg;1while/\n/,s/^ *\K#|#(?= *$)|^ *.{@{-}}\K#|\A[^\n]*\K#|#(?=[^\n]*\n\z)|#(?=.{@{-}} *$)/%/sm;y/ EM/0x2/' | dynamite.pl

dynamite.pl:
#!/usr/bin/perl -0p
sub f{@a{@_}||=push@{$%+($&?$1?50:$&=~8?0:$&&"5"?2:1:0)},@_}f$_;for(@{$%}){f y/xr|/ytx/r;{f s/\pL\d/$&^(E&$&)x2/er}{f s/(q|s|y)#/$&^"\x01\x13"/er}my$o;{$\|=/x/>/2/;$o.="
"while s/.$/$o.=$&,""/meg}f$o}$%++>999|$\||redo}{

Replace the \xhh escapes for the claimed score.
The program can't realistically handle complex cases. In particular it can't handle any of the failure cases. This is because there are just too many different ways of blowing up the internal walls or picking up mice so the search becomes too wide and uses too much memory even though it's at least smart enough to never process the same state multiple times. The pressure limit has to be lowered to 100 or so for somewhat bearable runtimes and memory usage.
Explanation
I use the bit pattern of a character to represent the state of a field:
contains victim: 0000 0010
has hero:        0100 0000
carry dynamite   0000 0001
carry mouse      0000 0100
home             0000 1000
walkable         0001 0000 (not really needed but results in shorter regexes)
make printable   0010 0000
wall             0010 xxxx (bit patterns not very important,
permawall        0010 xxxx  just avoid letters and digits)

For example the hero (01000000) carrying dynamite (00000001) must be on a place he can walk (00010000) and we want all values to be printable ASCII (00100000). Taking the bitwise or of all these bitmasks gives 01110001 which is the ASCII code for q. In total this becomes::
p: hero                     r hero on victim
q: hero carrying dynamite   s hero carrying dynamite on victim
t: hero carrying mouse      v hero carrying mouse on victim

x : hero at home
y : hero at home carrying dynamite
| : hero at home carrying mouse

0: empty  without hero
8: home   without hero
2: victim without hero

%: permanent wall
#: normal wall

The program will only consider the hero moving to the right (the rotation explained later will take care of the other directions). The bitmasks were carefully chosen such that the hero is always represented by a letter and a place he can move to by a digit (except the hero at home carrying a victim, but again this is intentional so that the hero's only move will be to drop the victim). So a hero that can move forward is matched by /\pL\d/. The matched substring has to be modified so that the hero and what he is carrying is removed from the first character and added to the second one, which can be done with a bitwise xor with the same value for both characters. The xor value consists of the hero bit (01000000), the dynamite bit (00000001) and the carry mouse bit (00000100). Together they or to 01000101 which is ASCII E. So moving the hero becomes:
s/\pL\d/$&^(E&$&)x2/e

The hero can blow up a wall if he is standing right in front of it and is carrying dynamite (q, s or y). The hero will lose his dynamite (xor with 00000001) and the wall # will change to a passage 0 (xor with 00010011), so
s/(q|s|y)#/$&^"\x01\x13"/e

To handle the other directions the whole board is rotated (rotated board ends up in $o):
my$o;$o.="\n"while s/.$/$o.=$&,""/meg

Apart from moving the hero also has a number of other choices he can make:
When at home, pick up dynamite:                   x -> y
When on victim not carrying anything pick him up: r -> t
When at home carrying a victim, drop him off:     | -> x

This is done by
y/xr|/ytx/

The board is finished if the hero is at home carrying nothing (x) and there are no more victims to rescue (no 2). This can be conveniently tested using
/x/>/2/

Once the board is solved I want to remember this state and at the end print it. For that I carry the "is solved" flag in $\ and print that at the end of the program without printing $_, so
$\|=/x/>/2/  ...   }{

The states to be processed at pressure 0 are kept in @0, at pressure 1 on @1 etc. The current pressure is kept in $%. Using $n or something like it would be shorter but the code doesn't work if the variable isn't initialized to something because autovivification will otherwise change $n to an ARRAY reference.Looping over the states at a certain pressure is done using a for and not a map because with a for you can extend the array while it is still being looped over and will pick up the new elements. This is needed because the rotations and single field choices of the hero happen in 0 time and end up in the same pressure array. So the loop for a given pressure is done by
for(@{$%}){...}

This is repeated until the pressure reaches 1000 or a solution is found:
$%++>999|$\||redo

All that is left is adding newly discovered states to their respective pressure arrays. That will be done by subroutine f. We only want to add a state if it has not been seen yet. States that have been seen before are kept in %a so:
sub f{@a{@_}||=push@$n, @_}

$n represents the new pressure for a state. I will derive that from the state that the regex variables still have as a result of the hero's action leading to this call:
if $1 is set it was from s/(q|s|y)#/$&^"\x01\x13"/e which blows a wall -> 50
else if $& is set it was from s/\pL\d/$&^(E&$&)x2/e, so the hero moves.
    if $& contains 8 the hero went home -> 0
    else if the hero has carry bits (5) -> 2
    else                                   1
else ($& was not set) it was from y/xr|/ytx/r -> 0

This leads to the following formula for $n:
$%+($&?$1?50:$&=~8?0:$&&"5"?2:1:0)

All the substitutions get an r modifier so they return the changed state and leave the current state in $_ alone. f is then called on this changed state, so you get code like
f y/xr|/ytx/r;

Because the calculation of $n needs the regex variables they must default to unset in case the substitutions changes nothing (because the condition to trigger them is not fulfilled). I must also not pick up any regex variables from a previous loop. Therefore the substitutions are wrapped in {} blocks to save and restore the regex state. That's how you get statements like
{f s/\pL\d/$&^(E&$&)x2/er}

In particular the rotation is so wrapped so it calls f without regex variables and gets a pressure contribution of 0.
The only thing still to do is to prime @0 with the initial state at the start
f$_

This is in the main loop so it also tries to add $_ to later pressure arrays, but since the initial state will already be in %a nothing will happen.
Together all this basically finds the shortest solution using Dijkstra's algorithm. There is a potential problem though. The current code won't add a state if it is rediscovered with a lower pressure than the first discovery. I've not been able to construct a board that would trigger this, but have also been unable to prove it is impossible.

Ooo, intriguing. This is significantly shorter than I was expecting any answer to be. Can you add a little bit of explanation? I don't really grok Perl.

@TimmyD Ok, explanation added with enough details so that even a non perl programmer should get at least an impression of how it works

Very impressive!

Awesome golfing, that's really impressive... When I think I'm not that bad at golfing with Perl, I take a look at your golfings, and that feeling goes away pretty fast!

JavaScript, 863 834 785 781 bytes
Saved 29 bytes thanks to ETHproductions
Saved 53 bytes thanks to Jordan
L=[]
f=(S,r="",R="",p=0,s=S.replace(RegExp(r),R),l=`((.|\n){${s.split`
`[0].length}})`,q=p+1,o=p+2,n=p+50)=>s in L|p>999?1e3:!/M/.test(s,L[s]=0)&/E/.test(s)?p:Math.min(...[[/ E/,"me",q],[/ E/,"de",o],[/ME/,"ce",q],[/E /,"em",q],[/E /,"ed",o],[/EM/,"ec",q],[`E${l} `,"e$1m",q],[`E${l} `,"e$1d",o],[`E${l}M`,"e$1c",q],[` ${l}E`,"m$1e",q],[` ${l}E`,"d$1e",o],[`M${l}E`,"c$1e",q],[/ m/,"m ",q],[/m /," m",q],[`m${l} `," $1m",q],[` ${l}m`,"m$1 ",q],[/ (d|c)/,"$1 ",o],[/(d|c) /," $1",o],[`(d|c)${l} `," $2$1",o],[` ${l}(d|c)`,"$3$1 ",o],[/d#/,"m ",n],[/#d/," m",n],[`#${l}d`," $1m",n],[`d${l}#`,"m$1 ",n],[/mM/," c",q],[/Mm/,"c ",q],[`M${l}m`,"c$1 ",q],[`m${l}M`," $1c",q],[/[mc]e/," E",p],[/e[mc]/,"E ",p],[`e${l}[mc]`,"E$1 ",p],[`[mc]${l}e`," $1E",p]].map(a=>f(s,...a)))
F=s=>f(s)<1e3

Takes input as a multiline string.
This defines an anonymous function that uses a recursive function f to determine if you trip off the alarm before retrieving all the mice. f returns 1000 if the pressure is above 1000 (to avoid endless recursion), returns the pressure if there are no more mice to rescue and the mouse in the exit, and returns the minimum pressure of all possible moves from the current state otherwise. It uses an array L to keep track of already visited positions where L[pos]==0 if it is visited, and undefined if it isn't. This may not be necessary, but it prevents the mouse from doing useless moves and throwing recursion errors at the very least. (This does mean you should redefine L if you are testing this multiple times)
This uses the format in the question other than that it requires you to use a different character for the external walls. (Anything other than # MEmecd)
More readable version:
stateList = []
f=(s,regex="",replacement="",pressure=0,state=s.replace(regexp(regex),replacement),line=`((.|\n){${state.split("\n")[0].length}})`)=>{
    if (state in stateList || pressure > 999) return 1e3
    if (!/M/.test(state) && /E/.test(state)) return pressure

    stateList[state] = 0

    return [
        [/ E/,"me",pressure+1],
        [/ E/,"de",pressure+2],
        [/ME/,"ce",pressure+1],
        [/E /,"em",pressure+1],
        [/E /,"ed",pressure+2],
        [/EM/,"ec",pressure+1],
        [`E${line} `,"e$1m",pressure+1],
        [`E${line} `,"e$1d",pressure+2],
        [`E${line}M`,"e$1c",pressure+1],
        [` ${line}E`,"m$1e",pressure+1],
        [` ${line}E`,"d$1e",pressure+2],
        [`M${line}E`,"c$1e",pressure+1],
        [/ m/,"m ",pressure+1],
        [/m /," m",pressure+1],
        [`m${line} `," $1m",pressure+1],
        [` ${line}m`,"m$1 ",pressure+1],
        [/ ([dc])/,"$1 ",pressure+2],
        [/([dc]) /," $1",pressure+2],
        [`([dc])${line} `," $2$1",pressure+2],
        [` ${line}([dc])`,"$3$1 ",pressure+2],
        [/d#/,"m ",pressure+50],
        [/#d/," m",pressure+50],
        [`#${line}d`," $1m",pressure+50],
        [`d${line}#`,"m$1 ",pressure+50],
        [/mM/," c",pressure+1],
        [/Mm/,"c ",pressure+1],
        [`M${line}m`,"c$1 ",pressure+1],
        [`m${line}M`," $1c",pressure+1],
        [/[mc]e/," E",pressure],
        [/e[mc]/,"E ",pressure],
        [`e${line}[mc]`,"E$1 ",pressure],
        [`[mc]${line}e`," $1E",pressure]
    ].map(a=>f(state,...a)).reduce((a,b)=>a-b<0?a:b) //reduce used for support in more browsers.
}
s=>f(s)>1e3

Useless whitespaces at s in L|p > 999.

@TuukkaX Thanks for reminding me about that, the bytecount was for the version without the spaces already.

See if you can save bytes by wrapping the code in eval and replacing @ with $1 (not sure if this will work, but you write $1 a lot)

I think you could save a bunch by making f a one-liner: f=(...)=>s in L|p>999?1e3:!/M/.test(s,L[s]=0)&/E/.test(s)?p:Math.min(...

@Cyoce I use $1 18 times, and .replace("@","$1") is 18 bytes. I don't see a way to pull it off.

@DanTheMan oh well. I thought it was worth a shot

Can you replace the map with map(a=>f(s,...a)) or map(f.bind(0,s))? (I'm not at a computer so I can't test it just now.)

Also, you do p+1 so many times wouldn't it make sense to do q=p+1 the first time and use q thereafter? Same for p+2 and (I think) p+50.

@Jordan Thanks for the tips, they shaved off almost 50 bytes!

@DanTheMan In your last edit you took 49 off your score but only removed 10 bytes from your answer (and only from the "More readable version.)

Oh, and you can save a few bytes by changing ([dc]) to (d|c).

These JS solutions make me question whether I know JS a lot or not :D

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Create a pyramidal matrix
A pyramidal matrix is a square matrix where all numbers increase or decrease from the center point, like the two matrices below:
1  1  1  1  1
1  2  2  2  1
1  2  3  2  1
1  2  2  2  1
1  1  1  1  1

Or:
3  3  3  3  3
3  2  2  2  3
3  2  1  2  3
3  2  2  2  3
3  3  3  3  3

Given a non-zero integer n, create a pyramidal matrix where the numbers goes from 1 to n either in increasing order (if n<0), or decreasing order (if n>0) from the center. If n is even, then there will be 4 center numbers (see the examples).
As always:

Optional input and output format

Number of spaces, delimiter etc. is optional

Test cases:
1
1

-1
1

5
1  1  1  1  1  1  1  1  1
1  2  2  2  2  2  2  2  1
1  2  3  3  3  3  3  2  1
1  2  3  4  4  4  3  2  1
1  2  3  4  5  4  3  2  1
1  2  3  4  4  4  3  2  1
1  2  3  3  3  3  3  2  1
1  2  2  2  2  2  2  2  1
1  1  1  1  1  1  1  1  1

-5
5  5  5  5  5  5  5  5  5
5  4  4  4  4  4  4  4  5
5  4  3  3  3  3  3  4  5
5  4  3  2  2  2  3  4  5
5  4  3  2  1  2  3  4  5
5  4  3  2  2  2  3  4  5
5  4  3  3  3  3  3  4  5
5  4  4  4  4  4  4  4  5
5  5  5  5  5  5  5  5  5

2
1  1  1  1
1  2  2  1
1  2  2  1
1  1  1  1

-2
2  2  2  2
2  1  1  2
2  1  1  2
2  2  2  2

-4
4  4  4  4  4  4  4  4
4  3  3  3  3  3  3  4
4  3  2  2  2  2  3  4
4  3  2  1  1  2  3  4
4  3  2  1  1  2  3  4
4  3  2  2  2  2  3  4
4  3  3  3  3  3  3  4
4  4  4  4  4  4  4  4

Why is the even case different from the odd case? There is no reason why the matrices can't all follow the exact same pattern.

Because the input was supposed to be the length of the side wall, in which case there's a difference between odd and even. I decided to go for the maximum value instead, but kept the odd and even difference there. It might seem strange, and might not be a good explanation, but it's the explanation for why there's a difference. :-)

Can we assume -10 < n < 10?

It's ok if it doesn't look like a perfect square, as long as it it's one numerically speaking. If rows with many 10s are wider that those with few 10s then that's ok...

Jelly, 18 17 bytes
|1ŒḄfR«þ`
AÇạẋ¡CG

Try it online! or verify all test cases.
How it works
|1ŒḄfR«þ`  Helper link. Argument: k (positive integer)

|1         Take the bitwise OR with 1. This increments k if it is even.
  ŒḄ       Bounce; yield [1, 2, ..., k | 1, ..., 2, 1].
    fR     Filter range; remove elements not in [1, ..., k] from the array.
           This results in [1, 2, ..., k, ..., 2, 1] if k is odd and in
           [1, 2, ..., k, k, ..., 2, 1] if k is even.
        `  Pass the last return value as left and right argument to:
      «þ     Minimum table; take the minimum of each pair of elements in the
             generated array, returning a 2D array.

AÇạẋ¡CG      Main link. Argument: n

A            Take the absolute value of n.
 Ç           Call the helper link on the result.
     C       Complement; yield 1 - n.
    ¡        Conditional application:
   ẋ           If repeating the return value of Ç 1 - n times results in a non-
               empty array, i.e., if n < 1:
  ạ              Take the absolute differences of the generated integers and 1 - n.
      G      Grid; join columns by spaces, rows by linefeeds.

MATL, 26 24 bytes
oXyG|to-:"TTYaQ]G0<?G+q|

Try it online! Or verify all test cases (slightly modified code to serve as test suite).
Explanation
The code first builds the output array assuming positive input n. The array is initiallized as 1 for odd input or as the empty array for even input (this is created as an identity matrix with size equal to the parity of the input). Then the following is repeated n times for even input, and n-1 times for odd input: extend the array with a frame containing 0, and add 1 to all elements.
For example, the steps for input n are:

Initial array:
1

Extend with frame:
0 0 0
0 1 0
0 0 0

Add 1:
1 1 1
1 2 1
1 1 1

Extend with frame:
0 0 0 0 0
0 1 1 1 0
0 1 2 1 0
0 1 1 1 0
0 0 0 0 0

Add 1:
1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1

This gives the correct output for positive input. If the input is negative, the array needs to be modified by adding the input minus 1 and taking the absolute value:
    3 3 3 3 3
    3 2 2 2 3
    3 2 1 2 3
    3 2 2 2 3
    3 3 3 3 3

You can watch the array growing (modified code to show intermediate steps) at MATL Online! The interpreter is still a beta. If it doesn't work press "Run" again or reload the page.
Commented code
o        % Take input implicitly and push 0 if even or 1 if odd
Xy       % Identity matrix of that size. Gives either 1 or empty array
G|       % Absolute value of input
to-      % Subtract 1 if odd
:"       % For loop: repeat that many times
  TTYa   %   Add a frame of zeros in the two dimensions
  Q      %   Add 1 to all elements
]        % End for
G        % Push input again
0>       % is it negative?
?        % If so
  G      %   Push input again
  +      %   Add
  q      %   Subtract 1
  |      %   Absolute value
         % End if implicitly
         % Display implicitly

I see you reused the code from the animation question. Awesome! Funny part is, this code would also still win in that question, even though it's longer than your other version ;).

@carusocomputing Yes, it's similar: duplicate, display, pause 1 second, clear output :-)

Also, not sure why, but any input above 14 stops at 14. Cancel that, it's a limitation of the online console "Operation timed out".

@carusocomputing The error says "operation time out". I guess it just takes too long for the interpreter. Try reducing the pause to say .2 seconds

@carusocomputing Yes that's the timeout on the online interpreter. We currently limit jobs to 30 seconds. As Luis suggests, you can decrease the pause time

Python 2, 109 99 98
n=input()
r=range(1,abs(n)+1)
l=r+r[~n|-2::-1]
for j in l:print[abs((n<0)*~-n+min(i,j))for i in l]

Create list
l = [1,2,3,4,5,4,3,2,1]

and play with it a little.

edit: new way of creating list + thx Lynn for two bytes

If n is even, then there will be 4 center numbers

@Rod No there won't. What makes you think so?

this is one of the rules

@Rod Oh. Just few minutes ago. Edited.

It may be a new rule; but it was always there in the examples. ;)

It isn't new, just not highlighted :c

min(0,n-1) → (n<0)*~-n for one more!

I´m pertty certain that Lynn´s hint won´t work on every machine.

EXCEL: 126 bytes
=MAX(MIN(MIN(CELL("row",RC)-1,CELL("col",RC)-1),MIN(((ABS(R1C1)-1)*2+3)-CELL("row",RC),((ABS(R1C1)-1)*2+3)-CELL("col",RC))),0)
Try it online*
Note: this answer uses R1C1 Notation. If you're going to try this yourself. you need to turn that on in Excel options.
the formula given needs to be in every cell present beyond (2,2). Put your desired pyramid size into (1,1).
quick screen-cap of the formula in action:

Here is an Additional picture of some fun with conditional formatting!
*It takes a very long time to update, currently.

This doesn't handle the negative cases or the even cases properly.  Also you can shorten the code to =MAX(MIN(MIN(ROW()-1,COLUMN()-1),MIN(((ABS(A1)-1)*2+3)-ROW(),((ABS(A1)-1)*2+3)-COLUMN())),0) which is 92 bytes.  It still doesn't handle the cases though and formula can't be dragged across since the cell reference isn't locked.

More golfing same issues though. =MEDIAN(MIN(ROW()-1,COLUMN()-1),ABS(A1)*2+1-MAX(ROW(),COLUMN()),0)

@gtwebb thanks for telling me. I'll have to fix

-1. This doesn't work. It doesn't handle negative input. It doesn't handle even input. If you're putting in this formula in every applicable cell, you either need a Range or you need a heck of a lot more than 126 bytes.

Python 2.7: 123 122 120 Bytes
probs can still save a few bytes...
from numpy import*
n=input()
N=abs(n)
e=N*2-N%2
a=ones([e,e])
for i in range(N):a[i:e-i,i:e-i]=(i+1)*(n>0)or-n-i
print a
edit1: N=abs(n) to save 1 byte
edit2: (i+1)*(n>0)or-n-i to save 2 bytes

Haskell, 119 113 110 104 102 101 bytes
f x|(h,t)<-splitAt(mod x 2)$[x,x-1..1]++[1.. -x]=foldl(\m n->(n#)<$>(n<$m)#m)[[y]|y<-h]t
x#y=x:y++[x]

Returns the matrix as a list of lists of integers, for example: f 2 -> [[1,1,1,1],[1,2,2,1],[1,2,2,1],[1,1,1,1]].
How it works:
            [x,x-1..1]++[1.. -x]      -- make list from x down to 1 followed by
                                      -- 1 to (-x). One of the sublists will be
                                      -- empty. The resulting list contains the
                                      -- numbers of the pyramid from inside to out.
   (h,t)<-splitAt(mod x 2)            -- bind h to the first element if x is odd
                                      -- or to the empty list if x is even
                                      -- bind t to the rest (tail or full list)

foldl (     ) [[y]|y<-h] t            -- fold the following function into t with a
                                      -- starting value of [] if x is even or
                                      -- [[h]] if x is odd

   \m n ->                            -- the current matrix m with the next number
                                      -- n is transformed into a new matrix:

               (n#)<$>(n<$m)#m        -- prepend and append a n to
                                      -- m prepended and append by a line of n's

x#y=x:y++[x]                          -- helper function to prepend and append an
                                      -- element x to a list y

Perl, 175 bytes
Includes 1 bytes for -p.
($t,$v,$w)=($_,(abs)x2);$k=$_.$k for 1..$v;map{$r.=$_ for(@v=1..$_-1),$_ x(2*$v---$w%2),reverse@v;$r.=$/}1..$v;$_=$r.~~reverse$r;eval"y/1-$w/$k/"if$t<0;$w%2&&s/

.*//||s;

;

(There is a trailing newline that I don't know how to show with the markdown, but you need it).
Needs -p as well as -M5.010 or -E to run :
perl -pE '($t,$v,$w)=($_,(abs)x2);$k=$_.$k for 1..$v;map{$r.=$_ for(@v=1..$_-1),$_ x(2*$v---$w%2),reverse@v;$r.=$/}1..$v;$_=$r.~~reverse$r;eval"y/1-$w/$k/"if$t<0;$w%2&&s/

.*//||s;

;
' <<< 5

Damn, this is too long... I'll try some other approaches when I have some time.

Why do You use eval?

@Titus Because y/// doesn't interpolate, so is use the double quotes to interpolate $w and $k, then eval to execute y///.

Python 2, 109 bytes
n=input()
a=abs(n)
s=a*2-a%2
r=range(s)
for y in r:print[(min,max)[n<0](x+1,s-x,y+1,s-y)-(n<0)*s/2for x in r]

J, 29 26 bytes
1+**[:<./~**i.,2&|1&}.i.@-

Usage
   f =: 1+**[:<./~**i.,2&|1&}.i.@-
   f 1
1
   f _1
1
   f 2
1 1 1 1
1 2 2 1
1 2 2 1
1 1 1 1
   f _2
2 2 2 2
2 1 1 2
2 1 1 2
2 2 2 2
   f 3
1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1
   f _3
3 3 3 3 3
3 2 2 2 3
3 2 1 2 3
3 2 2 2 3
3 3 3 3 3

Explanation
The range i. verb outputs [0, 1, ..., n-1] for positive n and [n-1, n-2, ..., 0] for negative n which is useful here.
1+**[:<./~**i.,2&|1&}.i.@-  Input: integer n
                         -  Negate n
                      i.@   Creates range for -n
               2&|          Take n modulo 2, returns 0 or 1
                  1&}.      If n is odd, drop the first value from the range for -n
                            Else do nothing and pass it unmodified
              ,             Append it to
            i.              The range for n
          *                 Get the sign of n
           *                Multiply elementwise with the joined ranges
    [:<./~                  Form a table of the minimum values of the range
  *                         Get the sign of n
   *                        Multiply elementwise with the joined ranges
1+                          Add 1 to each and return

Mathematica, 78 bytes
Abs[Fold[ArrayPad[#,1,#2]&,Table[0,#,#]&@Mod[#,2,1],Range[Abs@#-1]]+1~Min~-#]&

Explanation
Table[0,#,#]&@Mod[#,2,1]

Make initial matrix: 1x1 if odd, 2x2 if even.
Range[Abs@#-1]

Generate a list from 1 to abs(input) - 1.
Fold[ArrayPad[#,1,#2]&, ..., ...]

Pad the initial array using the aforementioned list.
... +1~Min~-#

Add 1 or -input, whichever is smaller.
Abs

Apply absolute value to the entire matrix.

PHP, 177 157 bytes
for($y=-$n=abs($z=$argv[1])+1;++$y<$n;)if($y&&($n&1||$y-1)){for($x=-$n;++$x<$n;)if($x&&($n&1||$x-1)){$v=max(abs($x),abs($y));echo$z<0?$v:$n-$v," ";}echo"
";}

run with php -r '<code>
loops through rows and columns, prints the values depending on their distance to the center.

$n=abs($z)+1: The +1 saves a couple of +1 and -1 in later expressions
loops go from -$n+1 (pre-increment in the condition!) to $n-1 (-abs($z) to abs($z))
line/column 0 (and for odd $n: 1) are skipped
($n&1 is true for even columns here! Remember the +1?)
The printing for positive $z also benefits from the +1.

Haskell, 191 183 173 169 168 bytes
r=reverse;m=map
x!y=(((++)<*>(x.r)).).zipWith(++).m y
g n|n<0=m(m$abs.((n-1)+)).g$abs n|1<2=[id!id,tail!init]!!mod n 2=<<m r$r$m(\x->(x<$[1..x])++[x+1..n])[1..n]
g.(0-)

Usage:
mapM_ print $ (g.(0-)) 3

[1,1,1,1,1]
[1,2,2,2,1]
[1,2,3,2,1]
[1,2,2,2,1]
[1,1,1,1,1]

Thanks to nimi for 2 10 20 24 bytes!

negate is  (0-)

You can change f to [id!id,tail!init]!!mod n 2 and then inline it into g and use the 1<2 guard to bind an intermediate result of the branch: g n| ... |q<-r<$>a n=([id!id,tail!init]!!mod n 2)q$a n. You don't need a name for the main function.

Oh, you can inline a, too (and switch back to the 1<2 guard): g n| ... |1<2=[id!id,tail!init]!!mod n 2=<<map r$r$(\x->(x<$[1..x])++[x+1..n])<$>[1..n].

Last one for today: m=map, in !: ...(++).m y and g: g n|n<0=m(m(abs.((n-1)+)))$g$abs n|1<2=[id!id,tail!init]!!mod n 2=<<m r$r$m(\x->(x<$[1..x])++[x+1..n])[1..n].

JavaScript (ES6), 107 bytes
(n,l=Math.abs(n+n-n%2))=>[...Array(l--)].map((_,i,a)=>a.map((_,j)=>(j=Math.min(i,l-i,j,l-j),n<0?-n-j:j+1)))

l is the size of the array. The n<0?-n-j:j+1 seems awkward but I can't find anything better.

Vim, 152 143 bytes
I'm sure this could be golfed more, especially those last two lines, but my brain is fried.
D:let@z=@-/abs(@-)
a"nywYp:s/\d/x/g<C-v>
YggP:%s/.*/x \0 x<C-v>
:%s/x\+/\=@n-@z/g<C-v>
<Esc>v0"qda<C-r>=@z<0?1:@-*@z
<Esc>@=@-%2?"":"YPJYp"
@=@-*@z-1.(@-*@z>1?"@q":"")

Try it online!
Here it is in xxd format with unprintable characters:
0000000: 443a 6c65 7440 7a3d 402d 2f61 6273 2840  D:let@z=@-/abs(@
0000010: 2d29 0a61 226e 7977 5970 3a73 2f5c 642f  -).a"nywYp:s/\d/
0000020: 782f 6716 0a59 6767 503a 2573 2f2e 2a2f  x/g..YggP:%s/.*/
0000030: 7820 5c30 2078 160a 3a25 732f 785c 2b2f  x \0 x..:%s/x\+/
0000040: 5c3d 406e 2d40 7a2f 6716 0a1b 7630 2271  \=@n-@z/g...v0"q
0000050: 6461 123d 407a 3c30 3f31 3a40 2d2a 407a  da.=@z<0?1:@-*@z
0000060: 0a1b 403d 402d 2532 3f22 223a 2259 504a  ..@=@-%2?"":"YPJ
0000070: 5970 220a 403d 402d 2a40 7a2d 312e 2840  Yp".@=@-*@z-1.(@
0000080: 2d2a 407a 3e31 3f22 4071 223a 2222 29    -*@z>1?"@q":"")

Explanation
It builds the pyramid from the center out, surrounding the center number with xes:
x x x
x 5 x
x x x

Then it replaces the xes with the next number and surrounds it with xes again:
x x x x x
x 4 4 4 x
x 4 5 4 x
x 4 4 4 x
x x x x x

...and so on. For even numbers it does the same thing but starts with a 2x2 base.
Here's the code "ungolfed." It's somewhat unconventional in that I "record" a macro by typing it into a buffer (hence all the <C-v>s) and then deleting it into a register, which is the best way I found to compose a macro without actually executing the keystrokes.
D:let@z=@-/abs(@-)<CR>       " Delete the input (into @-) and set @z to -1 if @- is negative; otherwise 1
a                            " Enter insert mode to compose the macro
  "nyw                         " Copy the number under the cursor to @n
  Yp                           " Copy this line and paste it below
  :s/\d/x/g<C-v><CR>           " Replace digits in the copy with 'x'
  YggP                         " Copy this line and paste it at the top of the buffer
  :%s/.*/x \0 x<C-v><CR>       " Add an 'x' before and after each line
  :%s/x\+/\=@n-@z/g<C-v><CR>   " Replace all 'x'es (and 'xx'es etc.) with the next number
<Esc>v0"qd                   " Done composing macro; delete it into @q (buffer is now empty)
a<C-r>=@z<0?1:@-*@z          " Append the center number (1 or abs(@-)) to the buffer
<Esc>@=@-%2?"":"YPJYp"       " If the input is even, make a 2x2 square
@=@-*@z-1.(@-*@z>1?"@q":"")  " Execute the macro abs(@-)-1 times if it's > 1

PHP, 215 Bytes
for($i=0;$i<$m=($r=($s=abs($n=$argv[1]))*2-$s%2)**2;){$i%$r?:print"\n";$l=min(($x=$i%$r+1)<$s?$x:$x=$r-$x+1,($z=1+floor($i++/$r))<$s?$z:$z=$r-$z+1);$o=($n>0)?$l:$s+1-$l;echo str_pad(" ",1+strlen($s)-strlen($o)).$o;}

R, 112 bytes
k=abs(n);l=2*k;m=diag(l);for(i in 1:k){m[i:(l+1-i),i:(l+1-i)]=i};if(n%%2==1){m=m[-k,-k]};if(n<0){m=abs(m-1+n)};m

Needs integer n in workspace, otherwise run n=scan() for an extra 8 bytes.
k=abs(n)
l=2*k
m=diag(l)                    # Initialize quadratic 2*|n| matrix
for(i in 1:k){
    m[i:(l+1-i),i:(l+1-i)]=i # Assign values to matrix elements according
                             # to their index
}
if(n%%2==1){
   m=m[-k,-k]                # If n is odd, delete middle row and column
}
if(n<0){
    m=abs(m-1+n)             # If n < 0, flip values
}
m                            # Print matrix

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
The Decanting Problem
Given N decanters (0 < N < 10) with that can hold C0 ... CN-1 liters (0 < C < 50) and a goal G liters, please determine if it is possible to reach that goal using only the following actions:

Fill a decanter
Empty a decanter
Pour from one decanter to another until the one being poured to is full or the one being poured from is empty

The goal amount G must be the amount of water in one of the containers at the end. You cannot have a 'output decanter'.
Examples
N: 2
C0: 5
C1: 12
G: 1
Result: Yes
N: 3
C0: 6
C1: 9
C2: 21
G: 5
Result: No
Hint: To calculate if it is possible, check to see if G is divisible by the GCD of the capacities. Also, make sure it will fit in a container.
Remember, this is code-golf, so the code with the lowest number of bytes wins.
Leaderboards
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
# Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:
# Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:
# Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the leaderboard snippet:
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

var QUESTION_ID=94202,OVERRIDE_USER=12537;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

Related.

Is there a "output decanter"?  Aka, if I have a decanter of size 1, is any capacity possible?

@MartinEnder Ahh. Fixed.

@NathanMerrill There is no "output decanter." You need to be able to get it in one of the decanters given.

This same challenge was being Sandboxed.

Jelly, 9 8 7 bytes
-1 byte thanks to @Dennis (use integer division, :, rather than not less than, <¬)
Ṁ:a⁸g/ḍ

TryItOnline
How?
Ṁ:a⁸g/ḍ - Main link: capacities, goal
Ṁ       - maximum capacity
 :      - integer division with goal (effectively not less than goal since non-0 is True)
  a     - and
   ⁸    - left argument (capacities)
    g/  - gcd reduce over list (gcd of capacities)
      ḍ - divides

Haskell, 35 bytes
l%n=n`mod`foldr1 gcd l<1&&any(>=n)l

This paper proves a result that vastly simplifies the problem. Prop 1 says that

You can achieve a goal exactly when it's both:

A multiple of the greatest common divisor (gcd) of the capacities,
At most the maximum capacity

It's clear why both of these are necessary: all amounts remain multiples of the gcd, and the goal must fit in a container. The key of the result is an algorithm to produce any goal amount that fits these conditions.
Call the operator % like [3,6,12]%9.
A 37-byte alternative:
l%n=elem n[0,foldr1 gcd l..maximum l]

I believe the goal has to fit in one of the decanters, it should be less than the largest decanter's volume (based on @Oliver's comment "You need to be able to get it in one of the decanters given.").

Conveniently, that's actually the definition used in the paper and I misread, so that's an easy fix.

05AB1E, 9 8 9 bytes
Uses the CP-1252 encoding
ZU¿%²X>‹‹

Explanation
          # true if
   %      # target size modulo
ZU¿       # gcd of decanter sizes
        ‹ # is smaller than
    ²X>‹  # target size is less than or equal to max decanter size

Try it online!
Saved 1 byte utilizing the less than trick from Luis Mendo's MATL answer

utilizing the less than trick ... which I learned from Dennis :-)

The actual answer is still 9 bytes ;-)

@ETHproductions Oops! Seems I only updated the explanation and TIO link, not the actual code. Thanks :)

MATL, 10 bytes
&Zd\&G<~a<

Try it online!
This uses @xnor's approach.
&Zd    % Take array C as input. Compute the gcd of its elements
\      % Take number G as input. Compute that number modulo the above. Call this A
&G     % Push the two inputs again: C, then G
<~a    % Gives 1 if some element of C is at least G; 0 otherwise. Call this B
<      % Gives true if A is 0 and B is 1; otherwise gives false

JavaScript (ES6), 58 bytes
(n,a)=>a.some(e=>n<=e)&n%a.reduce(g=(d,e)=>d?g(e%d,d):e)<1

Another port of @xnor's answer. Yes, I get to use reduce again!

Alternate sub-function: e=>n<=e is a visual palindrome ;)

Excel: 43 bytes
=AND(MOD(A10,GCD(A1:A9))=0,A10<=MAX(A1:A9))
Try it online!
How to use:
Put this formula anywhere Except A1-A10.
Then input your Decant holding volumes in cells A1:A9 (because the number of decants is fixed) and the goal in A10. cells without decants should be left blank. Wherever you put the formula will contain the result. TRUE if you can achieve the goal, FALSE if you cannot.

Retina, 39 bytes
\d+
$*
^(?>(1+)(,?\1)*;)(\1+)$(?<=\3.+)

Input should be a comma-separated list of the decanters, followed by a semicolon, followed by the target volume. E.g.:
6,9,21;5

Output is 0 (falsy) or 1 (truthy).
Try it online! (The first line enables a linefeed-separated test suite.)
Explanation
\d+
$*

This just converts the input to unary. Afterwards we simply match valid inputs with a single regex:
^(?>(1+)(,?\1)*;)(\1+)$(?<=\3.+)

The part inside (?>...) finds the GCD. We do this by finding the largest substring 1+ with which we can match all the decanters (allowing an optional , only after a full match of the GCD). The atomic group (the (?>...)) itself so that the regex engine doesn't backtrack to divisors of the GCD if the target volume can't be matched (otherwise group 1 will at some point be reduced to matching a single 1 and all inputs will be truthy).
Once we've found the GCD, we try to match the target volume as a multiple of it with a simple (\1+)$.
Finally, we check that the target volume not greater than the largest decanter's capacity, by ensuring that the volume can be matched inside any decanter with (?<=\3.+).

Ruby, 35 bytes
->n,g{g<=n.max&&1>g%n.reduce(:gcd)}

PARI/GP, 31 bytes
Pretty much straightforward. Checking the max (vecmax) is very costly, I wonder if it can be done better.
f(c,g)=g%gcd(c)<1&&vecmax(c)>=g

Perl, 47 bytes
Includes +2 for -ap
Run with the jar sizes on the first line of STDIN and the target jar on the second line:
decanter.pl; echo
2 5 12
1
^D

decanter.pl:
#!/usr/bin/perl -p
$_=($_<@G)>$_%$=;$=--while@G[@F]=grep$_%$=,@F

This solution is unusual in that it processes the input line by line and outputs something for each of them. The output for the first line was carefully designed to be empty while the second line prints the solution. Two bytes are lost on () because < and > are designed to be non-associative in perl.
The regex solution is also nice but 49 bytes:
#!/usr/bin/perl -p
s/\d+/1x$&/eg;$_=/^(?>(1+)( |\1)*:)(\1+)$/&/$3./

(some parts stolen from the Retina solution)
For this one give input on STDIN as jars separated by spaces and target after a ::
decanter.pl <<< "2 5 12:1"

Hard to beat languages with a builtin gcd (21 bytes) and max (7 bytes) for this one...

Scala, 90 53 bytes
def h(g:Int,a:BigInt*)=a.max>g&&a.reduce(_ gcd _)%g<1

Works basically the same as the other answers, but scala doesn't have a built-in gcd function. Scala has a built.in gcd function, but only for BigInt.


text:
Implement tab completion
Tab completion is a useful feature that auto-completes partially written commands.  You're going to be implementing it.
For example, if the available commands were ['apply','apple','apple pie','eat'], then a would complete to  appl, as all of the commands that start with a also start with appl.
Input/Output
You need to input a string, A, and a set of strings, B.
You need to output the longest common prefix of all B that starts with A.

If none of the options starts with A, then return A
You can assume that B is nonempty, and that all strings are nonempty
You cannot assume that any of the options start with A, nor that the common prefix will be longer than A
You can be case sensitive or case insensitive.
You only need to handle printable ASCII
Built-ins that explicitly do this task are allowed

Test cases:
'a'       ['apply','apple','apple pie','eat'] => 'appl'
'a'       ['apple pie']                       => 'apple pie'
'apple'   ['eat','dine']                      => 'apple'
'program' ['programa','programb']             => 'program'
'*%a('    ['*%a()-T>','*%a()-T<','@Da^n&']    => '*%a()-T'
'a'       ['abs','absolute','answer']         => 'a'
'a'       ['a','abs']                         => 'a'
'one to'  ['one to one','one to many']        => 'one to '

Note the trailing space on the last test case
This is a code-golf, so make your answers as short as possible!

Related

Could you add an example with non-alphabetic, printable ASCII characters for posterity?

More examples with non-alphabetic characters couldn't hurt. I just deleted my answer because I realized that it broke with inputs containing \ or '.

Not sure how to represent ' in an example.  If I use " for the strings, then the strings are different than other examples.

That's exactly the problem my answer had. :P

What is the result for 'a' and `['a','abs']?

Good test case! 'a'

Do we have to deal with an empty command list?

@Titus nope. "You can assume that B is nonempty, and that all strings are nonempty"

May we assume B has no trailing spaces?

JavaScript (ES6), 75 bytes
(s,a)=>/^(.*).*(\n\1.*)*$/.exec(a.filter(e=>e.startsWith(s)).join`
`)[1]||s

Explanation: Filters on all matching prefixes, then joins with newlines and matches against a regex that finds the longest common prefix of all lines. If there are no prefixes then the regex returns an empty string in which case we simply return the original string.

You can replace e.startsWith(s) with e.match("^"+s) for a byte off Currying will save another

@ShaunH I can't use match with arbitrary printable ASCII.

Oh right regex and control characters. you can still curry  (s,a)=> to s=>a=>

Jelly, 14 12 bytes
ḣJ$€ċÐff\ṪṪȯ

Try it online! or verify all test cases.
How it works
ḣJ$€ċÐff\ṪṪȯ  Main link. Left argument: B. Right argument: A

  $€          Convert the two links to the left into a monadic chain and apply it
              to each string s in B.
 J              Generate the indices of s, i.e., [1, ..., len(s)].
ḣ               Head; for each index i, take the first i characters of s.
              This generates the prefixes of all strings in B.
     Ðf       Filter; keep prefixes for which the link to the left returns 1.
   ċ            Count the number of times A appears in the prefixes of that string.
       f\     Do a cumulative (i.e., keeping all intermediate values) reduce by
              filter, keeping only common prefixes. f/ is a more obvious choice,
              but it errors on an empty array, i.e., when A isn't a prefix of any
              string in B.
         Ṫ    Tail; take the last prefix array (if any) or return 0.
          Ṫ   Tail; take the last common prefix (if any) or return 0.
           ȯ  Logical OR (flat); replace 0 with A, leave strings untouched.

Pyth, 14 13 bytes
Thanks to @isaacg for -1 byte
.xe@F/#z._MQz

A program that takes the list of strings, and then the string, on STDIN and prints the result.
Verify all test cases
How it works
.xe@F/#z._MQz  Program. Inputs: Q, z
        ._MQ   Map prefixes over Q
     /#z       Filter that by count(z)>0, removing the prefixes corresponding to elements
               in Q that do not start with z
   @F          Fold intersection over that. This yields all the common prefixes
  e            Yield the last element of that, giving the longest common prefix, since the
               prefixes are already sorted by length
.x             But if that throws an exception since no elements of Q start with z:
            z  Yield z instead
               Implicitly print

f}zT => /#z

PowerShell v3+, 112 bytes
param($a,$b)if($c=@($b-like"$a*")){([char[]]$c[0]|%{($i+="$_")}|?{($c-like"$_*").count-eq$c.count})[-1]}else{$a}

Takes input as a string $a and an array of strings $b. Uses the -like operator to pull out those elements from $b that (case-insensitive) starts with $a, explicitly cast those as an array @(...) (since the result could be one match as a scalar, in which case indexing later fails), and store that array into $c.
That forms the if clause. If there's nothing in $c (i.e., nothing starts with $a, so the array is empty), then output $a with the else. Otherwise ...
We cast the first element of $c as a char-array and loop through each element, string-concatenating with the previous $i and placing the strings on the pipeline via encapsulating parens. Those are filtered through |?{...} (the Where-Object clause) to verify that the .count of $c is -equal to the .count of things in $c that are -like the substring (i.e., the substring matches everything in $c). Since we're building our substrings in order shortest to longest, we need the last [-1] of the resultant strings.
Test Cases
PS C:\Tools\Scripts\golfing> $tests=@('a',@('apply','apple','apple pie','eat')),@('a',@('apple pie')),@('apple',@('eat','dine')),@('program',@('programa','programb')),@('one to',@('one to one','one to many')),@('*%a(',@('*%a()-T>', '*%a()-T<', '@Da^n&'))

PS C:\Tools\Scripts\golfing> $tests|%{""+$_[0]+" ("+($_[1]-join',')+") -> "+(.\implement-tab-completion.ps1 $_[0] $_[1])}
a (apply,apple,apple pie,eat) -> appl
a (apple pie) -> apple pie
apple (eat,dine) -> apple
program (programa,programb) -> program
one to (one to one,one to many) -> one to
*%a( (*%a()-T>,*%a()-T<,@Da^n&) -> *%a()-T

Python 2, 122 bytes
s=input();l=[x for x in input()if x[:len(s)]==s]or[s];i=len(l[0])
while len(l)>1:i-=1;l=set(x[:i]for x in l)
print l.pop()

Full program; takes string and list from stdin exactly as given in the examples, except the inputs must be on separate lines.
Verify all test cases

Why l.pop() instead of l[-1]?

@Cyoce Because l is usually a set at that point, which doesn't allow indexing (being unordered). (Fortunately, both sets and lists support pop().)

Perl, 61 bytes
Includes +2 for -0p
Run with the first word followed by the dictionary words on STDIN:
tabcompletion.pl
a
apply
apple
apple pie
eat
^D

tabcompletion.pl:
#!/usr/bin/perl -0p
/^(.+)
((?!\1).*
)*(\1.*).*
((?!\1).*
|\3.*
)*$|
/;$_=$3||$`

Perl, 54 bytes
Includes +2 for -Xp (can be combined with -e) and +3 for -i (cannot be combined)
Give dictionary on STDIN and the word after the -i option, e.g.:
perl -ia -Xpe '/^\Q$^I\E.*?(?{$F[$a{$&}++]=$&})^/}{$_=pop@F||$^I'
apply
apple
apple pie
eat
^D

Just the code:
/^\Q$^I\E.*?(?{$F[$a{$&}++]=$&})^/}{$_=pop@F||$^I

Python 2, 112 bytes
lambda n,h:[a.pop()for a in[{s[:-i]for s in h if s.find(n)==0}for i in range(-len(`h`),0)]+[{n}]if len(a)==1][0]

Haskell, 67 bytes
(a:b)?(c:d)|a==c=a:(b?d)
_?_=""
s%l=foldr1(?)$max[s][x|x<-l,x?s==s]

The auxiliary function ? finds the longest common prefix of two strings by recursively taking the first character as long as it's the same for both strings and the strings are non-empty.
The main function % first keeps only the strings in the list that start with the given one s, checked by the longest common prefix with s being s. To handle there being no valid competitions, it adds s to an empty result via max. Then, it finds the longest common prefix of those by folding the binary function ?.

Python 2, 75 bytes
import os
lambda s,x:os.path.commonprefix([t for t in x if s<=t<s+'ÿ'])or s

Thanks to @xnor for suggesting the built-in, originally used by  @BetaDecay in this answer.
For scoring purposes, ÿ can be replaced with a DEL byte. Test it on Ideone.

D, 88 bytes
S f(S)(S p,S[]q){try p=q.filter!(a=>a.startsWith(p)).fold!commonPrefix;catch{}return p;}

Usage:
assert(f("a", ["apply","apple","apple pie","eat"]) ==  "appl");

The code simply removes all elements from q that don't start with p, then computes the largest common initial subsequence of the remaining elements.
The templated parameters save us two repetitions of string and one of auto.  The exception misuse lets us avoid the temporary variable and conditional that would otherwise be necessary to handle the case where no elements of q start with p.

Python 2, 107 102 bytes
s,x=input();r='';q=1
for c in zip(*[t for t in x if s<=t<s+'ÿ']):q/=len(set(c));r+=c[0]*q
print r or s

For scoring purposes, ÿ can be replaced with a DEL byte. Test it on Ideone.
Thanks to @xnor for saving 5 bytes!

With os.path.commonprefix as Beta Decay found, you can have it do the work for you.

Wow, that saves a lot of bytes. Are you sure you don't want to post that yourself?

I wouldn't feel right posting it myself since it's solely Beta Decay's idea combined with your answer.

For your solution, it looks a bit shorter to iterate for c in ... directly and terminate with error after printing like if len(set(c))>1:print r or s;_.

I think that would fail if x is a singleton array.

Oh, I see. It still seems to save bytes to print afterwards, but use a boolean multiplier to the appended character that starts as 1 and becomes 0 when uniqueness is violated.

Retina, 60 bytes
^(.*)(\n(?!\1).*)*(\n(\1.*)).*(\n((?!\1)|\4).*)*$
$4
s`\n.*

The trailing new line is significant. Takes input as the string on a line and then each word on a separate line (but no trailing newline!). Works in a similar way to my JavaScript answer by matching the longest common prefix of all lines that begin with the string on the first line. If it doesn't find one then it simply deletes all the words.

PHP, 167 160 157 152 bytes
<?for($r=preg_grep("$^".preg_quote($s=$_GET[s])."$",$a=$_GET[a]);$r[0]>$s&&preg_grep("$^".preg_quote($t=$s.$r[0][strlen($s)])."$",$a)==$r;)$s=$t;echo$s;

I could save 3 more bytes by assigning variables with preg_grep and preg_quote, but eh.
breakdown
for(
    // find items in $a that start with $s
    $r=preg_grep("$^".preg_quote($s=$_GET[s])."$",$a=$_GET[a]);
    // while the first match is longer than $s
    $r[0]>$s
    // and appending the next character of the first match
    &&preg_grep("$^".preg_quote($t=$s.$r[0][strlen($s)])."$",$a)
    // does not change the matches
    ==$r
;)
    // keep appending
    $s=$t;
return$s;

PHP, 156 Bytes
with much Help from Titus Thank You
<?foreach($_GET[t]as$v)if(strstr($v,$s=$_GET[s])==$v)$r[]=$z=$v;for(;$i++<strlen($z);){$s=substr($z,0,$i);foreach($r as$x)if($x[$i]!=$z[$i])break 2;}echo$s;

PHP, 199 Bytes
32 Bytes saves by Titus with array_unique
<?foreach($_GET[t]as$v)if(strstr($v,$s=$_GET[s])==$v)$r[]=$v;for(;$i++<strlen($r[0]);$a=[]){foreach($r as$x)$a[]=substr($x,0,$i);if(count($r)==count($a)&count(array_unique($a))<2)$s=$a[0];}echo$s;

I know that the Regex Solution by Titus was shorter till Titus help me to improve my way. Maybe the way I found is interesting for you

Replace $z with $s to fix the apple, [eat,dine] case.

$l= is obsolete; You don´t use that variable. (-2)

$i++<$m is shorter than ++$i<=$m. (-1)

substr($x,0,$i); is shorter than str_split($x,$i)[0]. (-3)

You can put $r[]=$v inside the strlen. (-5)

<2 is shorter than ==1. (-1)
You could use strstr in the first loop: strstr($v,$s)==$v. (-3)

I really like the count(array_unique()) part. But You can save a whole lot with inverting the last condition and putting the curlys in the inner loop instead of the outer: foreach($r as$x){if($x[$i]!=$r[0][$i])break 2;$s=substr($x,0,$i);}. (-33)

@Titus 1-467 Done 5) Your proposal fill the array without check the condition. That is not which I Would reach.

Let me rephrase it: 5) You can combine $r[]=$v;$m=max($m,strlen($v)); to $m=max($m,strlen($r[]=$v)); and drop the curlys. This doesn´t touch the condition.

On second thought, you don´t need $m at all. All you need is something that is >= the minimum length of the replacements. The new 5) Replace {$r[]=$v;$m=max($m,strlen($v));} with $r[]=$v;} and <$m with <strlen($r[0]) (-13)

@Titus All Done and I have found additional 8 Bytes so that our solutions have the same length

Great! And I just found another golf: 9) $r[]=$z=$v; in the first loop and {$s=substr($z,0,$i);foreach($r as$x)if($x[$i]!=$z[$i])break 2;} for the second (-3)

Oh I forgot: You have to add the PHP tag <? if you work with a web server. (+2)

Scala, 119 bytes
def f(s:String,a:Seq[Char]*)=a filter(_ startsWith s)reduceOption(_ zip _ takeWhile(t=>t._1==t._2)map(_._1))getOrElse s

Ungolfed:
def tabComplete(input: String, options: Seq[Char]*) = {
  options.
  filter((x: String) => x.startsWith(input)).
  reduceOption((x: Seq[Char], y: Seq[Char]) =>
    x.zip(y).
    takeWhile((t: (Char, Char)) => t._1 == t._2).
    map((t: (Char, Char)) => t._1)
  ).getOrElse(input)
}

Explanation:
def g(s:String,a:Seq[Char]*)= //define a method g with a string and a vararg array of strings as parameter
  a filter(_ startsWith s)    //filter the options to contains only elements starting with the input
  reduceOption(               //if the filtered array is nonempty, reduce it:
    _ zip _                     //zip two elements together
    takeWhile(t=>t._1==t._2)    //take the tuples while they contain the same char
    map(_._1)                   //take the first element from each tuple
  )getOrElse s                //else return the input

PowerShell, 101 bytes
Based on Nail's awesome regexp.
if($args-join'
'-cmatch'^(.*)(\n(?!\1).*)*(\n(\1.*)).*(\n((?!\1)|\4).*)*$'){$Matches.4}else{$args[0]}

Try it online!

05AB1E, 14 bytes
ʒIÅ?}€ηøʒË}‚˜θ

Try it online or verify all test cases.
Explanation:
ʒ   }           # Filter the (implicit) input-list
 IÅ?            #  Does it start with the (second) input-string
                #   i.e. ["codex","bla","codegolf"] and "c" → ["codex","codegolf"]
     €η         # Then take the prefixes of every remaining string
                #  → [["c","co","cod","code","codex"],
                #     ["c","co","cod","code","codeg","codego","codegol","codegolf"]]
       ø        # Zip/transpose; swapping rows/columns
                #  → [["c","c"],["co","co"],["cod","cod"],["code","code"],["codex","codeg"]]
        ʒ }     # Filter:
         Ë      #  Only keep sublists which only contain the same substrings
                #   → [["c","c"],["co","co"],["cod","cod"],["code","code"]]
           ‚    # Pair it with the (second implicit) input
                #  → ["c",["c","c"],["co","co"],["cod","cod"],["code","code"]]
                # (workaround if nothing in the input-list starts with the input-string)
            ˜   # Flatten this list
                #  → ["c","c","c","co","co","cod","cod","code","code"]
             θ  # And only leave the last item (which is output implicitly as result)
                #  → "code"

Gaia, 12 bytes
e…¦&⊢…Ė⁇_+ₔ)

Try it online!
Takes input as B, then A.
e		| eval B as list of strings
 …¦		| take prefixes of each string
   &⊢		| reduce by set intersection
     …		| take list prefixes of each.
      Ė⁇	| Keep only those with A as an element
	_	| flatten
	 +ₔ	| add A to the beginning of the list
	   )	| take the last element

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Is this string prime?

A string is called a "prime string" if it can't be written as a concatenation of more than one of the same string.

Your task is to write a program that, given a sequence of letters of length N (5 < N < 100), determines if it is prime or not.
Examples
Input: AABBAA
Output: not prime, false, 0, etc.
Input: FDFJKEHKLJHDSUS
Output: prime, true, 1, etc.
Uppercase and lowercase letters count as the same letter.
Remember, this is code-golf, so the code with the smallest number of bytes wins.
Leaderboards
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
# Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:
# Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:
# Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the leaderboard snippet:
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

var QUESTION_ID=94238,OVERRIDE_USER=12537;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

Does the return value actually have to be a string saying "prime" or "not prime"?

Maybe some more test cases?

Is AAB=A A B prime or not? It looks like from one example FDF=F D F would be prime even with two Fs.

AAB is prime since it cannot be represented by more than one of the same string added together. FDF is also prime.

RE the output

You have a case length 3, but you said that 5 ‹ N ‹ 100.

@feersum Changed my mind. Question has been edited.

@zyabin101 fixed.

Did you get this from SPOJ? Is copying problems okay here?

Is this case sensitive (is abAB prime)?

I thought AABBAA is prime...?

Ruby, 16 + 1 (n flag)` = 36 17 bytes
Basically the prime-checking regex for unary numbers. Probably shorter in Retina. If you want a newline after the output, add the newline for 1 bytes.
Edited to a shorter version only for the sake of posterity, since there's not much point in answers to dupe questions.
p ! ~/^(.+)\1+$/

$_="#{"not "if~/^(.+)\1+$/}prime"

The output rules are more relaxed now. $_="#{"n"if~/^(.+)\1+$/}p". np for not prime and p for prime.

@Riley the output rules are now relaxed enough for me to post my original version that prints true and false now, but thanks for letting me know!