# The Hungry Mouse

Sixteen piles of cheese are put on a 4x4 square. They're labeled from $$\1\$$ to $$\16\$$. The smallest pile is $$\1\$$ and the biggest one is $$\16\$$.

The Hungry Mouse is so hungry that it always goes straight to the biggest pile (i.e. $$\16\$$) and eats it right away.

After that, it goes to the biggest neighboring pile and quickly eats that one as well. (Yeah ... It's really hungry.) And so on until there's no neighboring pile anymore.

A pile may have up to 8 neighbors (horizontally, vertically and diagonally). There's no wrap-around.

## Example

$$\begin{matrix} 3&7&10&5\\ 6&8&12&13\\ 15&9&11&4\\ 14&1&16&2 \end{matrix}$$

The Hungry Mouse first eats $$\16\$$, and then its biggest neighbor pile, which is $$\11\$$.

$$\begin{matrix} 3&7&10&5\\ 6&8&12&13\\ 15&9&🐭&4\\ 14&1&\color{grey}\uparrow&2 \end{matrix}$$

Its next moves are $$\13\$$, $$\12\$$, $$\10\$$, $$\8\$$, $$\15\$$, $$\14\$$, $$\9\$$, $$\6\$$, $$\7\$$ and $$\3\$$ in this exact order.

$$\begin{matrix} 🐭&\color{grey}\leftarrow&\small\color{grey}\swarrow&5\\ \small\color{grey}\nearrow&\small\color{grey}\swarrow&\color{grey}\uparrow&\color{grey}\leftarrow\\ \color{grey}\downarrow&\small\color{grey}\nwarrow&\small\color{grey}\nearrow&4\\ \small\color{grey}\nearrow&1&\color{grey}\uparrow&2 \end{matrix}$$

There's no cheese anymore around the Hungry Mouse, so it stops there.

## The challenge

Given the initial cheese configuration, your code must print or return the sum of the remaining piles once the Hungry Mouse has stopped eating them.

For the above example, the expected answer is $$\12\$$.

## Rules

• Because the size of the input matrix is fixed, you may take it as either a 2D array or a one-dimensional array.
• Each value from $$\1\$$ to $$\16\$$ is guaranteed to appear exactly once.
• This is .

## Test cases

[ [ 4,  3,  2,  1], [ 5,  6,  7,  8], [12, 11, 10,  9], [13, 14, 15, 16] ] --> 0
[ [ 8,  1,  9, 14], [11,  6,  5, 16], [13, 15,  2,  7], [10,  3, 12,  4] ] --> 0
[ [ 1,  2,  3,  4], [ 5,  6,  7,  8], [ 9, 10, 11, 12], [13, 14, 15, 16] ] --> 1
[ [10, 15, 14, 11], [ 9,  3,  1,  7], [13,  5, 12,  6], [ 2,  8,  4, 16] ] --> 3
[ [ 3,  7, 10,  5], [ 6,  8, 12, 13], [15,  9, 11,  4], [14,  1, 16,  2] ] --> 12
[ [ 8,  9,  3,  6], [13, 11,  7, 15], [12, 10, 16,  2], [ 4, 14,  1,  5] ] --> 34
[ [ 8, 11, 12,  9], [14,  5, 10, 16], [ 7,  3,  1,  6], [13,  4,  2, 15] ] --> 51
[ [13, 14,  1,  2], [16, 15,  3,  4], [ 5,  6,  7,  8], [ 9, 10, 11, 12] ] --> 78
[ [ 9, 10, 11, 12], [ 1,  2,  4, 13], [ 7,  8,  5, 14], [ 3, 16,  6, 15] ] --> 102
[ [ 9, 10, 11, 12], [ 1,  2,  7, 13], [ 6, 16,  4, 14], [ 3,  8,  5, 15] ] --> 103

• +1 for that mouse character Nov 19 '18 at 21:59
• ...make that 103: [[9, 10, 11, 12], [1, 2, 7, 13], [6, 16, 4, 14], [3, 8, 5, 15]] Nov 19 '18 at 23:32
• What a nicely written challenge! I'll keep it in mind for the best-of nominations.
– xnor
Nov 20 '18 at 2:22
• After misreading I was a little sad that this was not a hungry moose. Nov 20 '18 at 13:17
• This challenge reminds me of the mouse in the maze program for the txo computer. This game was written way back in the 1950s, and the txo was the first transistorized computer in the world, according to legend. Yes, believe it or not, somebody was writing video games in your grandfather's day. Nov 20 '18 at 19:05

# Python 2, 133 130 bytes

a=input();m=16
for i in range(m):a[i*5:i*5]=0,
while m:i=a.index(m);a[i]=0;m=max(a[i+x]for x in[-6,-5,-4,-1,1,4,5,6])
print sum(a)


Try it online!

Takes a flattened list of 16 elements.

### How it works

a=input();m=16

# Add zero padding on each row, and enough zeroes at the end to avoid index error
for i in range(m):a[i*5:i*5]=0,

# m == maximum element found in last iteration
# i == index of last eaten element
# eaten elements of a are reset to 0
while m:i=a.index(m);a[i]=0;m=max(a[i+x]for x in[-6,-5,-4,-1,1,4,5,6])
print sum(a)

• The adjacent-cell expression a[i+x]for x in[-6,-5,-4,-1,1,4,5,6] can be shortened to a[i+j+j/3*2-6]for j in range(9) (the zero entry is harmless). Python 3 can surely do shorter by hardcoding a length-8 bytestring, but Python 2 might still be better overall.
– xnor
Nov 20 '18 at 3:02
• Though your zero padding loop is clever, it looks like it's shorter to take a 2D list: a=[0]*5 for r in input():a=r+[0]+a. Perhaps there's a yet shorter string slicing solution that doesn't require iterating.
– xnor
Nov 20 '18 at 3:33

# Python 2, 111 bytes

i=x=a=input()
while x:x,i=max((y,j)for j,y in enumerate(a)if i>[]or 2>i/4-j/4>-2<i%4-j%4<2);a[i]=0
print sum(a)


Try it online!

Method and test cases adapted from Bubbler. Takes a flat list on STDIN.

The code checks whether two flat indices i and j represent touching cells by checking that both row different i/4-j/4 and column difference i%4-j%4 are strictly between -2 and 2. The first pass instead has this check automatically succeed so that the largest entry is found disregarding adjacency.

# MATL, 5049 47 bytes

16:HZ^!"2G@m1ZIm~]v16eXK68E16b"Ky0)Y)fyX-X>h]s-


Input is a matrix, using ; as row separator.

### Explanation

16:HZ^!  % Cartesian power of [1 2 ... 16] with exponent 2, transpose. Gives a
% 2-row matrix with 1st column [1; 1], 2nd [1; 2], ..., last [16; 16]
"        % For each column, say [k; j]
2      %   Push 2
G@m    %   Push input matrix, then current column [k; j], then check membership.
%   This gives a 4×4 matrix that contains 1 for entries of the input that
%   contain k or j
1ZI    %   Connected components (based on 8-neighbourhood) of nonzero entries.
%   This gives a 4×4 matrix with each connected component labeled with
%   values 1, 2, ... respectively
m~     %   True if 2 is not present in this matrix. That means there is only
%   one connected component; that is, k and j are neighbours in the
%   input matrix, or k=j
]        % End
v16e     % The stack now has 256 values. Concatenate them into a vector and
% reshape as a 16×16 matrix. This matrix describes neighbourhood: entry
% (k,j) is 1 if values k and j are neighbours in the input or if k=j
XK       % Copy into clipboard K
68E      % Push 68 times 2, that is, 136, which is 1+2+...+16
16       % Push 16. This is the initial value eaten by the mouse. New values will
% be appended to create a vector of eaten values
b        % Bubble up the 16×16 matrix to the top of the stack
"        % For each column. This just executes the loop 16 times
K      %   Push neighbourhood matrix from clipboard K
y      %   Copy from below: pushes a copy of the vector of eaten values
0)     %   Get last value. This is the most recent eaten value
Y)     %   Get that row of the neighbourhood matrix
f      %   Indices of nonzeros. This gives a vector of neighbours of the last
%   eaten value
y      %   Copy from below: pushes a copy of the vector of eaten values
X-     %   Set difference (may give an empty result)
X>     %   Maximum value. This is the new eaten value (maximum neighbour not
%   already eaten). May be empty, if all neighbours are already eaten
h      %   Concatenate to vector of eaten values
]        % End
s        % Sum of vector of all eaten values
-        % Subtract from 136. Implicitly display

• Idk MatLab, but can you save a little if you push -136 instead of +136? Nov 21 '18 at 1:31
• @Titus Hm I don't see how Nov 21 '18 at 9:20
• or the other way round: I thought instead of 1) push 136 2) push each eaten value 3) sum up eaten values 4) subtract from 136 -> 1) push 136 2) push negative of eaten value 3) sum up stack. But as it obviously is only one byte each; it´s probably no gain. Nov 21 '18 at 13:33
• @Titus Ah, yes, I think that uses the same number of bytes. Also, I need each eaten value (not its negative) for the set difference; negating would have to be done at the end Nov 21 '18 at 13:37

# PHP, 177 174 171 bytes

for($v=16;$v;$u+=$v=max($p%4-1?max($a[$p-5],$a[$p-1],$a[$p+3]):0,$a[$p-4],$a[$p+4],$p%4?max($a[$p-3],$a[$p+1],$a[$p+5]):0))$a[$p=array_search($v,$a=&$argv)]=0;echo 120-$u;


Run with -nr, provide matrix elements as arguments or try it online.

# JavaScript, 122 bytes

I took more than a couple of wrong turns on this one and now I've run out of time for further golfing but at least it's working. Will revisit tomorrow (or, knowing me, on the train home this evening!), if I can find a minute.

a=>(g=n=>n?g([-6,-5,-4,-1,1,4,5,6].map(x=>n=a[x+=i]>n?a[x]:n,a[i=a.indexOf(n)]=n=0)|n)-n:120)(16,a=a.flatMap(x=>[...x,0]))


Try it online

• +1 for flatMap() :p Nov 20 '18 at 17:29
• :D I think this is the first time I've used it for golf! Out of interest (and to give me a target when I come back to this), what was your score when you tried it? Nov 20 '18 at 17:46
• Didn't get a minute to come back to this today. Hopefully that means I'll be able to start over with completely fresh eyes tomorrow. Nov 21 '18 at 17:14
• I've posted my solution. Dec 13 '18 at 15:13

# R, 128124123112 110 bytes

function(r){r=rbind(0,cbind(0,r,0),0)
m=r>15
while(r[m]){r[m]=0
m=r==max(r[which(m)+c(7:5,1)%o%-1:1])}
sum(r)}


Try it online!

It creates a 4x4 matrix (which helped me to visualize things), pads it with 0's, then begins from 16 and searches it's surrounding "piles" for the next largest, and so forth.

Upon conclusion, it does output a warning, but it is of no consequence and does not change the result.

EDIT: -4 bytes by compressing the initialization of the matrix into 1 line.

EDIT: -1 thanks to Robert Hacken

EDIT: -13 bytes combining Giuseppe and Robin Ryder's suggestions.

• You can save one byte changing r==16 for r>15. Nov 24 '18 at 23:41
• 117 bytes -- change it to a function taking a matrix and do some aliasing with the which. Nov 27 '18 at 15:32
• 112 bytes improving upon @Giuseppe 's suggestions: you can store m as a logical instead of an integer, and thus only need to call which once instead of twice. May 6 '19 at 14:30
• 110 bytes using @RobinRyder 's golf and messing with compressing the neighborhood adjacency matrix. May 6 '19 at 16:37
• @Sumner18 X%o%Y is an alias for outer(X,Y,'*'). outer is one of the handiest functions around as it can function as the "broadcast" feature of Octave/MATLAB/MATL with aribtrary (vectorized) operators. See here; also handy on rare occasions is kronecker which is linked in that page. May 6 '19 at 18:47

# Charcoal, 47 bytes

ＥＡ⭆ι§αλ≔QθＷ›θA«≔⌕ＫＡθθＪ﹪θ⁴÷θ⁴≔⌈ＫＭθA»≔ΣＥＫＡ⌕αιθ⎚Ｉθ


Try it online! Link is to verbose version of code. Explanation:

ＥＡ⭆ι§αλ


Convert the input numbers into alphabetic characters (A=0 .. Q=16) and print them as a 4x4 grid.

≔Qθ


Start by eating the Q, i.e. 16.

Ｗ›θA«


Repeat while there is something to eat.

≔⌕ＫＡθθ


Find where the pile is. This is a linear view in row-major order.

Ｊ﹪θ⁴÷θ⁴


≔⌈ＫＭθ


A»


Eat the current pile.

≔ΣＥＫＡ⌕αιθ


Convert the piles back to integers and take the sum.

⎚Ｉθ


Clear the canvas and output the result.

# Powershell, 143141136130122 121 bytes

$a=,0*5+($args|%{$_+0}) for($n=16;$i=$a.IndexOf($n)){$a[$i]=0$n=(-1,1+-6..-4+4..6|%{$a[$i+$_]}|sort)[-1]}$a|%{$s+=$_}
$s  Less golfed test script: $f = {

$a=,0*5+($args|%{$_+0}) for($n=16;$i=$a.IndexOf($n)){$a[$i]=0$n=(-1,1+-6..-4+4..6|%{$a[$i+$_]}|sort)[-1] }$a|%{$s+=$_}
$s } @( ,( 0 , ( 4, 3, 2, 1), ( 5, 6, 7, 8), (12, 11, 10, 9), (13, 14, 15, 16) ) ,( 0 , ( 8, 1, 9, 14), (11, 6, 5, 16), (13, 15, 2, 7), (10, 3, 12, 4) ) ,( 1 , ( 1, 2, 3, 4), ( 5, 6, 7, 8), ( 9, 10, 11, 12), (13, 14, 15, 16) ) ,( 3 , (10, 15, 14, 11), ( 9, 3, 1, 7), (13, 5, 12, 6), ( 2, 8, 4, 16) ) ,( 12 , ( 3, 7, 10, 5), ( 6, 8, 12, 13), (15, 9, 11, 4), (14, 1, 16, 2) ) ,( 34 , ( 8, 9, 3, 6), (13, 11, 7, 15), (12, 10, 16, 2), ( 4, 14, 1, 5) ) ,( 51 , ( 8, 11, 12, 9), (14, 5, 10, 16), ( 7, 3, 1, 6), (13, 4, 2, 15) ) ,( 78 , (13, 14, 1, 2), (16, 15, 3, 4), ( 5, 6, 7, 8), ( 9, 10, 11, 12) ) ,( 102, ( 9, 10, 11, 12), ( 1, 2, 4, 13), ( 7, 8, 5, 14), ( 3, 16, 6, 15) ) ,( 103, ( 9, 10, 11, 12), ( 1, 2, 7, 13), ( 6, 16, 4, 14), ( 3, 8, 5, 15) ) ) | % {$expected, $a =$_
$result = &$f @a
"$($result-eq$expected):$result"
}


Output:

True: 0
True: 0
True: 1
True: 3
True: 12
True: 34
True: 51
True: 78
True: 102
True: 103


Explanation:

First, add top and bottom borders of 0 and make a single dimensional array:

0 0 0 0 0
# # # # 0
# # # # 0
# # # # 0
# # # # 0

↓

0 0 0 0 0 # # # # 0 # # # # 0 # # # # 0 # # # # 0


Powershell returns $null if you try to get the value behind the end of the array. Second, loop biggest neighbor pile started from 16 to non-zero-maximum. And nullify it (The Hungry Mouse eats it). for($n=16;$i=$a.IndexOf($n)){$a[$i]=0$n=(-1,1+-6..-4+4..6|%{$a[$i+$_]}|sort)[-1] }  Third, sum of the remaining piles. # JavaScript (ES7), 97 bytes Takes input as a flattened array. f=(a,s=p=136,m,d)=>a.map((v,n)=>v<m|(n%4-p%4)**2+(n-p)**2/9>d||(q=n,m=v))|m?f(a,s-m,a[p=q]=0,4):s  Try it online! ### Commented f = ( // f= recursive function taking: a, // - a[] = flattened input array s = // - s = sum of cheese piles, initialized to 1 + 2 + .. + 16 = 136 p = 136, // - p = position of the mouse, initially outside the board m, // - m = maximum pile, initially undefined d // - d = distance threshold, initially undefined ) => // a.map((v, n) => // for each pile v at position n in a[]: v < m | // unless this pile is not better than the current maximum (n % 4 - p % 4) ** 2 // or (n % 4 - p % 4)² + (n - p) ** 2 / 9 // + (n - p)² / 9 > d || // is greater than the distance threshold: (q = n, m = v) // update m to v and q to n ) // end of map() | m ? // if we've found a new pile to eat: f( // do a recursive call: a, // pass a[] unchanged s - m, // update s by subtracting the pile we've just eaten a[p = q] = 0, // clear a[q], update p to q and set m = 0 4 // use d = 4 for all next iterations ) // end of recursive call : // else: s // stop recursion and return s  • Yep, I never would have got anywhere close to that! Dec 13 '18 at 16:16 # SAS, 236 219 bytes Input on punch cards, one line per grid (space-separated), output printed to the log. This challenge is slightly complicated by some limitations of arrays in SAS: • There is no way to return the row and column indexes of a matching element from multidimensional data-step array - you have to treat the array as 1-d and then work them out for yourself. • If you go out of bounds, SAS throws an error and halts processing rather than returning null / zero. ## Updates: • Removed infile cards; statement (-13) • Used wildcard a: for array definition rather than a1-a16 (-4) ## Golfed: data;input a1-a16;array a[4,4]a:;p=16;t=136;do while(p);m=whichn(p,of a:);t=t-p;j=mod(m-1,4)+1;i=ceil(m/4);a[i,j]=0;p=0;do k=max(1,i-1)to min(i+1,4);do l=max(1,j-1)to min(j+1,4);p=max(p,a[k,l]);end;end;end;put t;cards; <insert punch cards here> ;  ## Ungolfed: data; /*Produce a dataset using automatic naming*/ input a1-a16; /*Read 16 variables*/ array a[4,4] a:; /*Assign to a 4x4 array*/ p=16; /*Initial pile to look for*/ t=136; /*Total cheese to decrement*/ do while(p); /*Stop if there are no piles available with size > 0*/ m=whichn(p,of a:); /*Find array element containing current pile size*/ t=t-p; /*Decrement total cheese*/ j=mod(m-1,4)+1; /*Get column number*/ i=ceil(m/4); /*Get row number*/ a[i,j]=0; /*Eat the current pile*/ /*Find the size of the largest adjacent pile*/ p=0; do k=max(1,i-1)to min(i+1,4); do l=max(1,j-1)to min(j+1,4); p=max(p,a[k,l]); end; end; end; put t; /*Print total remaining cheese to log*/ /*Start of punch card input*/ cards; 4 3 2 1 5 6 7 8 12 11 10 9 13 14 15 16 8 1 9 14 11 6 5 16 13 15 2 7 10 3 12 4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 10 15 14 11 9 3 1 7 13 5 12 6 2 8 4 16 3 7 10 5 6 8 12 13 15 9 11 4 14 1 16 2 8 9 3 6 13 11 7 15 12 10 16 2 4 14 1 5 8 11 12 9 14 5 10 16 7 3 1 6 13 4 2 15 13 14 1 2 16 15 3 4 5 6 7 8 9 10 11 12 9 10 11 12 1 2 4 13 7 8 5 14 3 16 6 15 9 10 11 12 1 2 7 13 6 16 4 14 3 8 5 15 ; /*End of punch card input*/ /*Implicit run;*/  • +1 for use of punch cards in PPCG :) Nov 20 '18 at 18:25 # Haskell, 163 bytes o f=foldl1 f.concat r=[0..3] q n=take(min(n+2)3).drop(n-1) 0#m=m v#m=[o max$q y$q x<$>n|y<-r,x<-r,m!!y!!x==v]!!0#n where n=map(z<$>)m;z w|w==v=0|0<1=w f=o(+).(16#)  Try it online! The f function takes the input as a list of 4 lists of 4 integers. ### Slightly ungolfed -- helper to fold over the matrix o f = foldl1 f . concat -- range of indices r = [0 .. 3] -- slice a list (take the neighborhood of a given coordinate) -- first we drop everything before the neighborhood and then take the neighborhood itself q n = take (min (n + 2) 3) . drop (n - 1) -- a step function 0 # m = m -- if the max value of the previous step is zero, return the map v # m = -- abuse list comprehension to find the current value in the map -- convert the found value to its neighborhood, -- then calculate the max cell value in it -- and finally take the head of the resulting list [ o max (q y (q x<$>n)) | y <- r, x <- r, m!!y!!x == v] !! 0
# n -- recurse with our new current value and new map
where
-- a new map with the zero put in place of the value the mouse currently sits on
n = map (zero <$>) m -- this function returns zero if its argument is equal to v -- and original argument value otherwise zero w | w == v = 0 | otherwise = w -- THE function. first apply the step function to incoming map, -- then compute sum of its cells f = o (+) . (16 #)  # APL (Dyalog Unicode), 42 41 bytesSBCS 16{×⍺:a∇⍨+/,m×⌈/⌈/⊢⌺3 3⊢a←⍵×~m←⍺=⍵⋄+/,⍵}⊢  Try it online! # Java 10, 272248 239 bytes m->{int r=0,c=0,R,C,M=16,x,y,X=0,Y=0;for(;M-->0;)if(m[M/4][M%4]>15)m[r=M/4][c=M%4]=0;for(;M!=0;m[r=X][c=Y]=0)for(M=0,C=9;C-->0;)try{if((R=m[x=r+C/3-1][y=c+C%3-1])>M){M=R;X=x;Y=y;}}catch(Exception e){}for(var Z:m)for(int z:Z)M+=z;return M;}  The cells are checked the same as in my answer for the All the single eights challenge. -24 bytes thanks to @OlivierGrégoire. -9 bytes thanks to @ceilingcat. Try it online. Explanation: m->{ // Method with integer-matrix parameter and integer return-type int r=0, // Row-coordinate for the largest number, starting at 0 c=0, // Column-coordinate for the largest number, starting at 0 R,C, // Row and column indices (later reused as temp integers) M=16, // Largest number the mouse just ate, starting at 16 x,y,X=0,Y=0; // Temp integers for(;M-->0;) // Loop M in the range (16, 0]: if(m[M/4][M%4]>15) // If the current cell is 16: m[r=M/4][c=M%4] // Set r,c to this coordinate =0; // And empty this cell // (after this first loop, M will be -1) for(;M!=0; // Loop as long as the largest number M isn't 0: ; // After every iteration: m[r=X][c=Y] // Change the r,c coordinates, =0) // And empty this cell for(M=0, // Reset M to 0 C=9;C-->0;) // Inner loop C in the range (9, 0]: try{if((R= // Set R to: m[x=r+C/3-1] // If C is 0, 1, or 2: Look at the previous row // Else-if C is 6, 7, or 8: Look at the next row // Else (C is 3, 4, or 5): Look at the current row [y=c+C%3-1]) // If C is 0, 3, or 6: Look at the previous column // Else-if C is 2, 5, or 8: Look at the next column // Else (C is 1, 4, or 7): Look at the current column >M){ // And if the number in this cell is larger than M M=R; // Change M to this number X=x;Y=y;} // And change the X,Y coordinate to this cell }catch(Exception e){} // Catch and ignore ArrayIndexOutOfBoundsExceptions // (try-catch saves bytes in comparison to if-checks) for(var Z:m) // Then loop over all rows of the matrix: for(int z:Z) // Inner loop over all columns of the matrix: M+=z; // And sum them all together in M (which was 0) return M;} // Then return this sum as result  • could you not to int r=c=X=Y=0,R=4,M=1,x,y; ? Nov 22 '18 at 12:53 • @Serverfrog I'm afraid that's not possible when declaring the variables in Java. Your suggestion did give me an idea to save a byte though, by using int r,c,R=4,M=1,x,y,X,Y;for(r=c=X=Y=0;, so thanks. :) Nov 22 '18 at 15:48 # J, 82 bytes g=.](]*{:@[~:])]_1}~[:>./]{~((,-)1 5 6 7)+]i.{: [:+/[:(g^:_)16,~[:,0,~0,0,0,.~0,.]  Try it online! I plan to golf this more tomorrow, and perhaps write a more J-ish solution similar to this one, but I figured I'd try the flattened approach since I hadn't done that before. • Do you really need the leftmost ] in g? Nov 20 '18 at 7:45 • Thanks Galen, you're right. It's the least of the issues with this code :) I have a much better solution which I'll implement when I have time. Nov 21 '18 at 1:26 # Red, 277 bytes func[a][k: 16 until[t:(index? find load form a k)- 1 p: do rejoin[t / 4 + 1"x"t % 4 + 1]a/(p/1)/(p/2): 0 m: 0 foreach d[-1 0x-1 1x-1 -1x0 1x0 -1x1 0x1 1][j: p + d if all[j/1 > 0 j/1 < 5 j/2 > 0 j/2 < 5 m < t: a/(j/1)/(j/2)][m: t]]0 = k: m]s: 0 foreach n load form a[s: s + n]s]  Try it online! It's really long solution and I'm not happy with it, but I spent so much time fixing it to work in TIO (apparently there are many differences between the Win and Linux stable versions of Red), so I post it anyway... ## More readable: f: func [ a ] [ k: 16 until [ t: (index? find load form a n) - 1 p: do rejoin [ t / 4 + 1 "x" t % 4 + 1 ] a/(p/1)/(p/2): 0 m: 0 foreach d [ -1 0x-1 1x-1 -1x0 1x0 -1x1 0x1 1 ] [ j: p + d if all[ j/1 > 0 j/1 < 5 j/2 > 0 j/2 < 5 m < t: a/(j/1)/(j/2) ] [ m: t ] ] 0 = k: m ] s: 0 foreach n load form a [ s: s + n ] s ]  # Jelly, 31 30 29 bytes ³œiⱮZIỊȦ ⁴ṖŒPŒ!€Ẏ⁴;ⱮṢÇƇṪ FḟÇS  Since the method is far too slow to run within 60s with the mouse starting on 16 this starts her off at 9 and limits her ability such that she is only able to eat 9s or less Try it online! (thus here she eats 9, 2, 7, 4, 8, 6, 3 leaving 97). ### How? ³œiⱮZIỊȦ - Link 1, isSatisfactory?: list of integers, possiblePileChoice ³ - (using a left argument of) program's 3rd command line argument (M) Ɱ - map across (possiblePileChoice) with: œi - first multi-dimensional index of (the item) in (M) Z - transpose the resulting list of [row, column] values I - get the incremental differences Ị - insignificant? (vectorises an abs(v) <= 1 test) Ȧ - any and all? (0 if any 0s are present in the flattened result [or if it's empty]) ⁴ṖŒPŒ!€Ẏ⁴;ⱮṢÇƇṪ - Link 2, getChosenPileList: list of lists of integers, M ⁴ - literal 16 Ṗ - pop -> [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] ŒP - power-set -> [[],[1],[2],...,[1,2],[1,3],...,[2,3,7],...,[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]] € - for each: Œ! - all permutations Ẏ - tighten (to a single list of all these individual permutations) ⁴ - (using a left argument of) literal 16 Ɱ - map across it with: ; - concatenate (put a 16 at the beginning of each one) Ṣ - sort the resulting list of lists Ƈ - filter keep those for which this is truthy: Ç - call last Link as a monad (i.e. isSatisfactory(possiblePileChoice) Ṫ - tail (get the right-most, i.e. the maximal satisfactory one) FḟÇS - Main Link: list of lists of integers, M F - flatten M Ç - call last Link (2) as a monad (i.e. get getChosenPileList(M)) ḟ - filter discard (the resulting values) from (the flattened M) S - sum  • Ah yeah, power-set is not enough! Nov 20 '18 at 0:34 • @Arnauld - finally got a little time to golf :D This should work, but will be (way) too slow for running at TIO with the test case you used before. Nov 20 '18 at 17:02 • Could the down-voter please give some feedback? This works, has a full and clear explanation, and is also the shortest entry at the present time. May 7 '19 at 8:14 • I upvoted, but given the O((n^2)!) of this answer I wish the challenge had required polynomial time. Jun 6 '19 at 9:40 Not my best work. There's some definite improvements to be done, some probably fundamental to the algorithm used -- I'm sure it can be improved by using only an int[], but I couldn't figure out how to efficiently enumerate neighbors that way. I'd love to see a PowerShell solution that uses only a single dimensional array! # PowerShell Core, 348 bytes Function F($o){$t=120;$a=@{-1=,0*4;4=,0*4};0..3|%{$a[$_]=[int[]](-join$o[(3+18*$_)..(3+18*$_+13)]-split',')+,0};$m=16;while($m-gt0){0..3|%{$i=$_;0..3|%{if($a[$i][$_]-eq$m){$r=$i;$c=$_}}};$m=($a[$r-1][$c-1],$a[$r-1][$c],$a[$r-1][$c+1],$a[$r][$c+1],$a[$r][$c-1],$a[$r+1][$c-1],$a[$r+1][$c],$a[$r+1][$c+1]|Measure -Max).Maximum;$t-=$m;$a[$r][$c]=0}$t}


Try it online!

Function F($o){$t=120;
$a=@{-1=,0*4;4=,0*4}; 0..3|%{$a[$_]=[int[]](-join$o[(3+18*$_)..(3+18*$_+13)]-split',')+,0};
$m=16; while($m-gt0){
0..3|%{$i=$_;0..3|%{if($a[$i][$_]-eq$m){$r=$i;$c=$_}}};
$m=($a[$r-1][$c-1],$a[$r-1][$c],$a[$r-1][$c+1],$a[$r][$c+1],$a[$r][$c-1],$a[$r+1][$c-1],$a[$r+1][$c],$a[$r+1][$c+1]|Measure -Max).Maximum;$t-=$m;$a[$r][$c]=0
}
$t }  • 334 bytes after simple restructuring Jan 17 '19 at 22:41 • Oh yeah, weird thing I noticed is that trying to do the (array|sort)[-1] instead of Measure -max worked in PSv5 but was getting incorrect results in core. No idea why. Jan 17 '19 at 22:44 • Yeah, that's weird. I tested it on (0..10|sort)[-1] but it returns 10 on PSv5 but 9 on PS Core. This is because it treats it in lexicographical order instead of numeric. Shame, that. Jan 17 '19 at 23:04 • Classic Microsoft changing the important things. Jan 17 '19 at 23:12 • I agree in this case. I'm not sure why PS Core Sort throws an array of int32 to an array of strings. But, this is straying into a rant, so I'll digress. Thanks for the restructure! Jan 18 '19 at 14:57 # C (gcc), 250 bytes x;y;i;b;R;C; g(int a[][4],int X,int Y){b=a[Y][X]=0;for(x=-1;x<2;++x)for(y=-1;y<2;++y)if(!(x+X&~3||y+Y&~3||a[y+Y][x+X]<b))b=a[C=Y+y][R=X+x];for(i=x=0;i<16;++i)x+=a[0][i];return b?g(a,R,C):x;} s(int*a){for(i=0;i<16;++i)if(a[i]==16)return g(a,i%4,i/4);}  Try it online! Note: This submission modifies the input array. s() is the function to call with an argument of a mutable int[16] (which is the same in-memory as an int[4][4], which is what g() interprets it as). s() finds the location of the 16 in the array, then passes this information to g, which is a recursive function that takes a location, sets the number at that location to 0, and then: • If there is a positive number adjacent to it, recurse with the location of the largest adjacent number • Else, return the sum of the numbers in the array. • s(int*a){for(i=0;a[i]<16;++i);return g(a,i%4,i/4);} – RiaD Nov 24 '18 at 14:37 • if g returns sum of eaten you don't need to calculate sum in it. Just return 16*17/2-g() at the end of s – RiaD Nov 24 '18 at 14:43 • can you use bitwise or instead if logical or? – RiaD Nov 24 '18 at 14:45 • 211 bytes Dec 31 '18 at 18:33 # Wolfram Language (Mathematica), 149 bytes (g@p_:=#&@@Position[s,Max@p];m=g[s=#];While[Tr[b=s[[##]]&@@#&/@Select[#+m&/@Tuples[{-1,0,1},2],Max@#<5&&Min@#>0&]]>0,m=g@b;s[[##&@@m]]=0];Tr[Tr/@s])&  Try it online! # Add++, 281 bytes D,f,@@,VBFB]G€=dbLRz€¦*bMd1_4/i1+$4%B]4 4b[$z€¦o D,g,@@,c2112011022200200BD1€Ω_2$TAVb]8*z€kþbNG€lbM
D,k,@~,z€¦+d4€>¦+$d1€<¦+$@+!*
D,l,@@#,bUV1_$:G1_$:
D,h,@@,{l}A$bUV1_$:$VbU","jG$t0€obU0j","$t€iA$bUpVdbLRG€=€!z€¦*$b]4*$z€¦o
y:?
m:16
t:120
Wm,x,$f>y>m,m,$g>x>y,y,$h>x>y,t,-m Ot  Try it online! Oof, this is a complicated one. Verify all test cases ## How it works For this explanation, we will use the input $$\M = \left[\begin{matrix} 3 & 7 & 10 & 5 \\ 6 & 8 & 12 & 13 \\ 15 & 9 & 11 & 4 \\ 14 & 1 & 16 & 2 \\ \end{matrix}\right]\$$ We start by defining a series of helper functions. We will use $$\x\$$ to represent an integer such that $$\1 \le x \le 16\$$, $$\M\$$ to, initially, represent the $$\4\text{x}4\$$ input matrix. The functions are: • $$\f(x, M)\$$: Given a value and a $$\4\text{x}4\$$ matrix, return the co-ordinates of $$\x\$$ in $$\M\$$ e.g. if $$\x = 16\$$ and $$\M\$$ is above, $$\f(x, M) = (4, 3)\$$ • $$\g(M, y)\$$: Given a matrix and two co-ordinates, return the largest of the neighbours of the value at that point e.g. using $$\f(x, M)\$$ from above, $$\g(M, f(x, M)) = 11\$$ This implements the two helper functions: $$\k(x)\$$ which removes any co-ordinates which would wrap around or be out of bounds $$\l(M, y)\$$ which, given a matrix and co-ordinates, returns the value at those co-ordinates • $$\h(y, M)\$$ which, given a matrix and co-ordinates, sets the value at those indexes to $$\0\$$ After these functions are defined, we come to the main body of the program. The first step is to assign the four variables, x, y, m and t. x is set to $$\0\$$ by default, y to the input, m to $$\16\$$ (the first value to search for) and t to $$\120 \: (1 + 2 + \cdots + 14 + 15)\$$. Next, we enter a while loop, that loops while m does not equal $$\0\$$. The steps in the loop go something along the lines of While m $$\\neq 0\$$: • Set x to $$\f(\textbf{y}, \textbf{m})\$$. For the first iteration, this sets x to the co-ordinates of $$\16\$$ is $$\M\$$ ($$\x := (4, 3)\$$ in our example) • Set m to $$\g(\textbf{x}, \textbf{y})\$$. This yields the largest new neighbour to m, or $$\0\$$, if there are no new neighbours (which ends the while loop). • Set y to $$\h(\textbf{x}, \textbf{y})\$$. This sets the previous value of m ($$\16\$$ in the first iteration) to $$\0\$$, in order for the previous step to work • Set t to $$\\textbf{t} - \textbf{m}\$$, removing that value from the total value amount. Finally, output t, i.e. the remaining, non collected values. # C# (.NET Core), 258 bytes Without LINQ. The using System.Collections.Generic is for the formatting after - the function doesn't require it. e=>{int a=0,b=0,x=0,y=0,j=0,k;foreach(int p in e){if(p>15){a=x=j/4;b=y=j%4;}j++;}e[x,y]=0;while(1>0){for(j=-1;j<2;j++)for(k=-1;k<2;k++){try{if(e[a+k,b+j]>e[x,y]){x=a+k;y=b+j;}}catch{}}if(e[x,y]<1)break;e[x,y]=0;a=x;b=y;}a=0;foreach(int p in e)a+=p;return a;}  Try it online! # Perl 6, 151136126125 119 bytes {my@k=$_;my $a=.grep(16,:k)[0];while @k[$a] {@k[$a]=0;$a=^@k .grep({2>$a+>2-$_+>2&$a%4-$_%4>-2}).max({@k[$_]})};[+] @k}  Super shabby solution. Takes input as flattened array. Try it online! # Perl 5-MList::Util=sum -p, 137 bytes splice@F,$_,0,0for 12,8,4;map{$k{++$,}=$_;$n=$,if$_&16}@F;map{map{$n=$_+$"if$k{$"+$_}>$k{$n}&&!/2|3/}-6..6;$k{$"=$n}=0}@F;$_=sum values%k


Try it online!

# K (ngn/k), 49 bytes

{{h[,x]:0;*>(+x+0,'1-!3 3)#h}\*>h::(+!4 4)!x;+/h}


Try it online!

the input (x) is a 1d array

(+!4 4)!x a dictionary that maps pairs of coords to the values of x

h:: assign to a global variable h

*> the key corresponding to the max value

{ }\ repeat until convergence, collecting intermediate values in a list

h[,x]:0 zero out the current position

+x+0,'1-!3 3 neighbour positions

( )#h filter them from h as a smaller dictionary

*> which neighbour has the max value? it becomes the current position for the new iteration

+/h finally, return the sum of h's remaining values

# Wolfram Language (Mathematica), 124 115 bytes

(p=#&@@Position[m=Join@@ArrayPad[#,1],16];Do[m[[p]]=0;p=MaximalBy[#&@@p+{0,-1,1,-5,5,-6,6,-7,7},m[[#]]&],16];Tr@m)&


Try it online!

This takes a 2D array, pads it on each side, then immediately flattens it so we don't have to spend bytes indexing. The only cost to this is Join@@ to flatten. Afterwards it proceeds as below.

124-byte version for a 2D array: Try it online!

Mostly my own work, with a bit derived from J42161217's 149-byte answer.

Ungolfed:

(p = #& @@ Position[m = #~ArrayPad~1,16];     m = input padded with a layer of 0s
p = location of 16
Do[
m = MapAt[0&,m,p];                        Put a 0 at location p
p = #& @@ MaximalBy[                      Set p to the member of
p+#& /@ Tuples[{0,-1,1},2],             {all possible next locations}
m~Extract~#&],                        that maximizes that element of m,
ties broken by staying at p+{0,0}=p.
16];                                        Do this 16 times.
Tr[Tr/@m]                                   Finally, output the sum of m.
)&


Not the shortest solution, but pretty straight forward.

## Ruby, 207

a=eval(ARGV[0])
n=16
while n!=0 do
a[i=a.index(n)]=0
t=[a[i+4]]
t<<a[i-4]if i>3
if i%4!=0
t<<a[i-5]if i>3
t<<a[i-1]
t<<a[i+3]
end
if i%4!=3
t<<a[i+1]
t<<a[i+5]
t<<a[i-3]if i>3
end
n=t.compact.max
end
p a.sum