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

We start with the following piles of cheese:

$$\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
  • 28
    +1 for that mouse character – Luis Mendo Nov 19 at 21:59
  • 2
    ...make that 103: [[9, 10, 11, 12], [1, 2, 7, 13], [6, 16, 4, 14], [3, 8, 5, 15]] – Jonathan Allan Nov 19 at 23:32
  • 8
    What a nicely written challenge! I'll keep it in mind for the best-of nominations. – xnor Nov 20 at 2:22
  • 7
    After misreading I was a little sad that this was not a hungry moose. – akozi Nov 20 at 13:17
  • 1
    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. – Walter Mitty Nov 20 at 19:05

19 Answers 19

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 at 3:02
  • 1
    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 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, 50 49 47 bytes

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

Input is a matrix, using ; as row separator.

Try it online! Or verify all test cases.

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? – Titus Nov 21 at 1:31
  • @Titus Hm I don't see how – Luis Mendo Nov 21 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. – Titus Nov 21 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 – Luis Mendo Nov 21 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.

R, 128 124 123 bytes

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

Try it online!

TIO link is slightly different, I am still trying to figure out how to make it work.

I do feel like I can golf a lot more out of this. But this works for now.

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

  • You can save one byte changing r==16 for r>15. – Robert Hacken Nov 24 at 23:41
  • 117 bytes -- change it to a function taking a matrix and do some aliasing with the which. – Giuseppe Nov 27 at 15:32

Charcoal, 47 bytes

EA⭆ι§αλ≔QθW›θA«≔⌕KAθθJ﹪θ⁴÷θ⁴≔⌈KMθA»≔ΣEKA⌕αιθ⎚Iθ

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

EA⭆ι§αλ

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.

W›θA«

Repeat while there is something to eat.

≔⌕KAθθ

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

J﹪θ⁴÷θ⁴

Convert to co-ordinates and jump to that location.

≔⌈KMθ

Find the largest adjacent pile.

Eat the current pile.

≔ΣEKA⌕αιθ

Convert the piles back to integers and take the sum.

⎚Iθ

Clear the canvas and output the result.

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

  • 3
    +1 for flatMap() :p – Arnauld Nov 20 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? – Shaggy Nov 20 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. – Shaggy Nov 21 at 17:14
  • I've posted my solution. – Arnauld yesterday

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 :) – GNiklasch Nov 20 at 18:25

Java 10, 272 271 bytes

m->{int r,c,R=4,M=1,x,y,X,Y;for(r=c=X=Y=0;R-->0;)for(C=4;C-->0;)if(m[R][C]>15)m[r=R][c=C]=0;for(;M!=0;m[r=X][c=Y]=0)for(M=-1,C=9;C-->0;)try{if((R=m[x=C<3?r-1:C>5?r+1:r][y=C%3<1?c-1:C%3>1?c+1:c])>M){M=R;X=x;Y=y;}}catch(Exception e){}for(var Z:m)for(int z:Z)M+=z;return M;}

-1 byte indirectly thanks to @Serverfrog.

The cells are checked the same as in my answer for the All the single eights challenge.

Try it online.

Explanation:

m->{                       // Method with integer-matrix parameter and integer return
  int r,                   //  Row-coordinate for the largest number
      c,                   //  Column-coordinate for the largest number
      R=4,C,               //  Row and column indices (later reused as temp integers)
      M=1,                 //  Largest number the mouse just ate, starting at 1
      x,y,X,Y;             //  Temp integers
  for(r=c=X=Y=0;           //  Start `r`, `c`, `X`, and `Y` at 0
      R-->0;)              //  Loop `R` in the range (4, 0]:
    for(C=4;C-->0;)        //   Inner loop `C` in the range (4, 0]:
      if(m[R][C]>15)       //    If the current cell is 16:
        m[r=R][c=C]        //     Set `r,c` to this coordinate
          =0;              //     And empty this cell
  for(;M!=0;               //  Loop as long as the largest number isn't 0:
      ;                    //    After every iteration:
       m[r=X][c=Y]         //     Change the `r,c` coordinates,
         =0)               //     And empty this cell
    for(M=-1,              //   Reset `M` to -1
        C=9;C-->0;)        //   Inner loop `C` in the range (9, 0]:
          try{if((R=       //    Set `R` to:
            m[x=C<3?       //     If `C` is 0, 1, or 2:
                 r-1       //      Look at the previous row
                :C>5?      //     Else-if `C` is 6, 7, or 8:
                 r+1       //      Look at the next row
                :          //     Else (`C` is 3, 4, or 5):
                 r]        //      Look at the current row
             [y=C%3<1?     //     If `C` is 0, 3, or 6:
                 c-1       //      Look at the previous column
                :C%3>1?    //     Else-if `C` is 2, 5, or 8:
                 c+1       //      Look at the next column
                :          //     Else (`C` is 1, 4, or 7):
                 c])       //      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; ? – Serverfrog Nov 22 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. :) – Kevin Cruijssen Nov 22 at 15:48

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 #)

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! – Jonathan Allan Nov 20 at 0:34
  • 2
    @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. – Jonathan Allan Nov 20 at 17:02

Powershell, 143 141 136 130 122 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.

APL (Dyalog Classic), 42 41 bytes

16{×⍺:a∇⍨+/,m×⌈/⌈/⊢⌺3 3⊢a←⍵×~m←⍺=⍵⋄+/,⍵}⊢

Try it online!

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? – Galen Ivanov Nov 20 at 7:45
  • 1
    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. – Jonah Nov 21 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
]

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!


More readable version:

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
}

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!

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! – Shaggy yesterday

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 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 at 14:43
  • can you use bitwise or instead if logical or? – RiaD Nov 24 at 14:45

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.