27
\$\begingroup\$

Given a non-empty rectangular array of integers from 0 to 9, output the amount of cells that are 8 and do not have a neighbour that is 8. Neighbouring is here understood in the Moore sense, that is, including diagonals. So each cell has 8 neighbours, except for cells at the edges of the array.

For example, given the input

8 4 5 6 5
9 3 8 4 8
0 8 6 1 5
6 7 9 8 2
8 8 7 4 2

the output should be 3. The three qualifying cells would be the following, marked with an asterisk (but only the amount of such entries should be output):

* 4 5 6 5
9 3 8 4 *
0 8 6 1 5
6 7 9 * 2
8 8 7 4 2

Additional rules

Test cases

  1. Input:

    8 4 5 6 5
    9 3 8 4 8
    0 8 6 1 5
    6 7 9 8 2
    8 8 7 4 2
    

    Output: 3

  2. Input

    8 8
    2 3
    

    Output: 0

  3. Input:

    5 3 4
    2 5 2
    

    Output: 0

  4. Input:

    5 8 3 8
    

    Output: 2

  5. Input:

    8
    0
    8
    

    Output: 2.

  6. Input:

    4 2 8 5
    2 6 1 8
    8 5 5 8
    

    Output: 1

  7. Input:

    4 5 4 3 8 1 8 2
    8 2 7 7 8 3 9 3
    9 8 7 8 5 4 2 8
    4 5 0 2 1 8 6 9
    1 5 4 3 4 5 6 1
    

    Output 3.

  8. Input:

    8
    

    Output: 1

  9. Input:

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

    Output: 4.

  10. Input:

    8 1 8
    2 5 7
    8 0 1
    

    Output: 3.

Inputs in MATLAB format:

[8 4 5 6 5; 9 3 8 4 8; 0 8 6 1 5; 6 7 9 8 2; 8 8 7 4 2]
[8 8; 2 3]
[5 3 4; 2 5 2]
[5 8 3 8]
[8; 0; 8]
[4 2 8 5; 2 6 1 8; 8 5 5 8]
[4 5 4 3 8 1 8 2; 8 2 7 7 8 3 9 3; 9 8 7 8 5 4 2 8; 4 5 0 2 1 8 6 9; 1 5 4 3 4 5 6 1]
[8]
[8 5 8 1 6 8 7 7; 9 9 2 8 2 7 8 3; 2 8 4 9 7 3 2 7; 9 2 9 7 1 9 5 6; 6 9 8 7 3 1 5 2; 1 9 9 7 1 8 8 2; 3 5 6 8 1 4 7 5]
[8 1 8; 2 5 7; 8 0 1]

Inputs in Python format:

[[8, 4, 5, 6, 5], [9, 3, 8, 4, 8], [0, 8, 6, 1, 5], [6, 7, 9, 8, 2], [8, 8, 7, 4, 2]]
[[8, 8], [2, 3]]
[[5, 3, 4], [2, 5, 2]]
[[5, 8, 3, 8]]
[[8], [0], [8]]
[[4, 2, 8, 5], [2, 6, 1, 8], [8, 5, 5, 8]]
[[4, 5, 4, 3, 8, 1, 8, 2], [8, 2, 7, 7, 8, 3, 9, 3], [9, 8, 7, 8, 5, 4, 2, 8], [4, 5, 0, 2, 1, 8, 6, 9], [1, 5, 4, 3, 4, 5, 6, 1]]
[[8]]
[[8, 5, 8, 1, 6, 8, 7, 7], [9, 9, 2, 8, 2, 7, 8, 3], [2, 8, 4, 9, 7, 3, 2, 7], [9, 2, 9, 7, 1, 9, 5, 6], [6, 9, 8, 7, 3, 1, 5, 2], [1, 9, 9, 7, 1, 8, 8, 2], [3, 5, 6, 8, 1, 4, 7, 5]]
[[8, 1, 8], [2, 5, 7], [8, 0, 1]]

Outputs:

3, 0, 0, 2, 2, 1, 3, 1, 4, 3
\$\endgroup\$
3
  • 20
    \$\begingroup\$ If you like it then you should have put a vote on it \$\endgroup\$
    – Luis Mendo
    Commented Nov 11, 2018 at 19:52
  • \$\begingroup\$ When I read "cells that equal 8", for a moment I thought you meant that a cell could be larger than a 1x1 chuck (NxN) of the grid. Should probably rephrase that to "cells that are 8" to clarify no math needed. =P \$\endgroup\$
    – Tezra
    Commented Nov 12, 2018 at 17:46
  • \$\begingroup\$ @Tezra Edited. I find the new wording a little less natural, but I’m not a native speaker so I’ll trust your criterion \$\endgroup\$
    – Luis Mendo
    Commented Nov 12, 2018 at 18:57

16 Answers 16

9
\$\begingroup\$

R, 117 63 59 bytes

function(m)sum(colSums(as.matrix(dist(which(m==8,T)))<2)<2)

Try it online!

dist computes distances (default is Euclidean) among rows of a matrix. which with second argument TRUE returns the coordinates where the predicate is true.

Coordinates are neighbours if the distance between them is not more than the square root of 2, but the inner <2 is good enough because the possible distance jumps from sqrt(2) ro 2.

\$\endgroup\$
2
  • \$\begingroup\$ it's a shame numerical imprecision doesn't allow colSums()^2<=2 to work. \$\endgroup\$
    – Giuseppe
    Commented Nov 12, 2018 at 22:28
  • \$\begingroup\$ @Giuseppe of course there are only a few possible distances and sqrt(2) jumps to 2 (e.g. sort(c(dist(expand.grid(1:6,1:6))), decreasing = TRUE))) so we were being too clever there. \$\endgroup\$
    – ngm
    Commented Nov 13, 2018 at 15:33
7
\$\begingroup\$

APL (Dyalog Classic), 29 28 25 bytes

≢∘⍸16=2⊥¨3,⌿3,/8=(⍉0,⌽)⍣4

Try it online!

\$\endgroup\$
6
  • \$\begingroup\$ Note: 0 index origin is not even needed. \$\endgroup\$
    – Adalynn
    Commented Nov 12, 2018 at 16:36
  • \$\begingroup\$ @Zacharý I always use it as a default, to avoid surprises. \$\endgroup\$
    – ngn
    Commented Nov 12, 2018 at 20:03
  • \$\begingroup\$ Ah, so like others with 1 (except not explicitly set). That makes sense. \$\endgroup\$
    – Adalynn
    Commented Nov 12, 2018 at 20:05
  • \$\begingroup\$ Surprised this doesn't use Stencil. Is there something that makes stencil inconvenient here? \$\endgroup\$
    – lirtosiast
    Commented Nov 20, 2018 at 7:49
  • \$\begingroup\$ @lirtosiast it's just longer with it :) \$\endgroup\$
    – ngn
    Commented Nov 20, 2018 at 9:39
5
\$\begingroup\$

Jelly, 18 15 bytes

8=µ+Ż+ḊZµ⁺ỊṖḋµS

Try it online!

How it works

8=µ+Ż+ḊZµ⁺ỊṖḋµS    Main link (monad). Input: digit matrix
8=              1) Convert elements by `x == 8`
  µ             2) New chain:
   +Ż+Ḋ              x + [0,*x] + x[1:] (missing elements are considered 0)
                     Effectively, vertical convolution with [1,1,1]
       Z             Transpose
        µ⁺      3) Start new chain, apply 2) again
          ỊṖ       Convert elements by `|x| <= 1` and remove last row
            ḋ      Row-wise dot product with result of 1)
             µS 4) Sum

Previous solution, 18 bytes

æc7B¤ZḊṖ
8=µÇÇỊḋµS

Try it online!

Wanted to share another approach, though this is 1 byte longer than Jonathan Allan's solution.

How it works

æc7B¤ZḊṖ    Auxiliary link (monad). Input: integer matrix
æc7B¤       Convolution with [1,1,1] on each row
     ZḊṖ    Zip (transpose), remove first and last elements

8=µÇÇỊḋµS    Main link (monad). Input: digit matrix
8=           Convert 8 to 1, anything else to 0 (*A)
  怀        Apply aux.link twice (effective convolution with [[1,1,1]]*3)
     Ịḋ      Convert to |x|<=1, then row-wise dot product with A
       µS    Sum the result
\$\endgroup\$
4
\$\begingroup\$

Jelly, 17 bytes

=8ŒṪµŒcZIỊȦƲƇẎ⁸ḟL

Try it online! Or see the test-suite.

How?

=8ŒṪµŒcZIỊȦƲƇẎ⁸ḟL - Link: list of lists of integers (digits)
=8                - equals 8?
  ŒṪ              - multidimensional truthy indices (pairs of row & column indices of 8s)
    µ             - start a new monadic chain
     Œc           - all pairs (of the index-pairs) 
            Ƈ     - filter keep if:  (keep those that represent adjacent positions)
           Ʋ      -   last four links as a monad:
       Z          -     transpose
        I         -     incremental differences
         Ị        -     insignificant? (abs(x) <= 1)
          Ȧ       -     all?
             Ẏ    - tighten (to a list of all adjacent 8's index-pairs, at least once each)
              ⁸   - chain's left argument (all the index-pairs again)
               ḟ  - filter discard (remove those found to be adjacent to another)
                L - length (of the remaining pairs of indices of single 8s)
\$\endgroup\$
4
\$\begingroup\$

JavaScript (Node.js), 88 85 bytes

a=>g=(x,y=0,c=0)=>a.map(p=>p.map((q,j)=>c+=q-8?0:1/x?(x-j)**2+y*y<3:g(j,-y)<2)&--y)|c

Try it online!

Thank Arnauld for 2 bytes

\$\endgroup\$
0
4
\$\begingroup\$

J,43, 40 37 bytes

-3 bytes thanks to Bubbler

1#.1#.3 3(16=8#.@:=,);._3(0|:@,|.)^:4

Try it online!

Explanation:

The first part of the algorithm assures that we can apply a 3x3 sliding window to he input. This is achieved by prepending a row of zeroes and 90 degrees rotation, repeated 4 times.

1#.1#.3 3(16=8#.@:=,);._3(0|:@,|.)^:4
                         (       )^:4 - repeat 4 times
                          0|:@,|.     - reverse, prepend wit a row of 0 and transpose
                     ;._3             - cut the input (already outlined with zeroes)
      3 3                             - into matrices with size 3x3
         (          )                 - and for each matrix do
                   ,                  - ravel (flatten)
             8    =                   - check if each item equals 8
              #.@:                    - and convert the list of 1s and 0s to a decimal
          16=                         - is equal to 16?
   1#.                                - add (the result has the shape of the input)
1#.                                   - add again
\$\endgroup\$
4
  • 1
    \$\begingroup\$ 37 bytes using @: and moving |.. Note that @ in place of @: doesn't work. \$\endgroup\$
    – Bubbler
    Commented Nov 12, 2018 at 10:26
  • \$\begingroup\$ This is nice. Probably worth adding at least a high level explanation of how it works, if not a code breakdown. It took me 10m or so to figure it out. Also, it's interesting how much shorter the APL version (which uses the same approach) is. Looks like that's mostly the result of digraphs instead of single char symbols... \$\endgroup\$
    – Jonah
    Commented Nov 12, 2018 at 15:00
  • \$\begingroup\$ @Jonah I'll add an explanation. For comparison with APL you can look at the revisions of ngn's solution, especially the 28 byte version \$\endgroup\$ Commented Nov 12, 2018 at 15:16
  • 1
    \$\begingroup\$ @Jonah Explanation added \$\endgroup\$ Commented Nov 12, 2018 at 18:26
4
\$\begingroup\$

Java 8, 181 157 156 149 147 bytes

(M,R,C)->{int z=0,c,f,t;for(;R-->0;)for(c=C;c-->0;z+=f%9/8)for(f=t=9;M[R][c]==8&t-->0;)try{f-=M[R+t/3-1][c+t%3-1]%9/8;}finally{continue;}return z;}

-24 bytes thanks to @OlivierGrégoire
-2 bytes thanks to @ceilingcat.

Takes the dimensions as additional parameters R (amount of rows) and C (amount of columns).

The cells are checked pretty similar as I did in my Fryer simulator answer.

Try it online.

Explanation:

(M,R,C)->{                  // Method with integer-matrix as parameter & integer return
  int z=0,                  //  Result-counter, starting at 0
      c,f,t;                //  Temp-integers, starting uninitialized
  for(;R-->0;)              //  Loop over the rows:
    for(c=C;c-->0           //   Inner loop over the columns:
           ;                //     After every iteration:
            z+=f%9/8)       //      If the digit in this cell is 8:
                            //       Increase the result-counter by 1
                            //      Else: leave it the same
      for(f=t=9;            //    Reset the flag to 9
          M[R][c]==8&       //    If the current cell contains an 8:
            t-->0;)         //     Inner loop `t` in the range (9, 0]:
        try{f-=             //      Decrease the flag by:
               M[R+t/3-1]   //       If `t` is 0, 1, or 2: Look at the previous row
                            //       Else-if `t` is 3, 4, or 5: Look at the current row
                            //       Else (`t` is 6, 7, or 8): Look at the next row
                [c+t%3-1]   //       If `t` is 0, 3, or 6: Look at the previous column
                            //       Else-if `t` is 1, 4, or 7: Look at the current column
                            //       Else (`t` is 2, 5, or 8): Look at the next column
                %9/8;       //       And if the digit in this cell is 8:
                            //        Decrease the flag-integer by 1
                            //       Else: leave it the same
        }finally{continue;} //      Catch and ignore ArrayIndexOutOfBoundsExceptions
                            //      (try-finally saves bytes in comparison to if-checks)
  return z;}                //  And finally return the counter
\$\endgroup\$
0
3
\$\begingroup\$

MATL, 21 17 10 bytes

8=t3Y6Z+>z

Try it online!

Thanks to Luis Mendo for help in chat, and for suggesting 2D convolution.

Explanation:

	#implicit input, m
8=	#equal to 8? matrix of 1 where m is 8, 0 otherwise
t	#duplicate
3Y6	#push [1 1 1; 1 0 1; 1 1 1], "neighbor cells" for convolution
Z+	#2D convolution; each element is replaced by the number of neighbors that are 8
>	#elementwise greater than -- matrix of 1s where an 8 is single, 0s otherwise
z	#number of nonzero elements -- number of single eights
	#implicit output
\$\endgroup\$
3
  • \$\begingroup\$ You could save quite a few bytes using (2D-)convolution, if you are famiiar with the concept \$\endgroup\$
    – Luis Mendo
    Commented Nov 12, 2018 at 17:31
  • 1
    \$\begingroup\$ @LuisMendo 2D convolution is one of those things where I don't understand 1D convolution either so there's no hope for me there...sounds like an opportunity to learn both! \$\endgroup\$
    – Giuseppe
    Commented Nov 12, 2018 at 17:33
  • 1
    \$\begingroup\$ If you need help with that let me know in the chat room. Convolution is a very useful operation. If you want to learn convolution start with 1D. The generalization to 2D is immediate \$\endgroup\$
    – Luis Mendo
    Commented Nov 12, 2018 at 17:39
3
\$\begingroup\$

Retina 0.8.2, 84 bytes

.+
_$&_
m`(?<!(?(1).)^(?<-1>.)*.?.?8.*¶(.)*.|8)8(?!8|.(.)*¶.*8.?.?(?<-2>.)*$(?(2).))

Try it online! Explanation:

.+
_$&_

Wrap each line in non-8 characters so that all 8s have at least one character on each side.

m`

This is the last stage, so counting matches is implied. The m modifier makes the ^ and $ characters match at the start or end of any line.

(?<!...|8)

Don't match a character directly after an 8, or...

(?(1).)^(?<-1>.)*.?.?8.*¶(.)*.

... a character below an 8; the (?(1).)^(?<-1>.)* matches the same column as the ¶(.)* on the next line, but the .?.? allows the 8 to be 1 left or right of the character after the . on the next line.

8

Match 8s.

(?!8|...)

Don't match an 8 immediately before an 8, or...

.(.)*¶.*8.?.?(?<-2>.)*$(?(2).)

... a character with an 8 in the line below; again, the (?<-2>.)*$(?(2).) matches the same column as the (.)*¶ on the previous line, but the .?.? allows the 8 to be 1 left or right of the 8 before the . on the previous line.

\$\endgroup\$
3
\$\begingroup\$

J, 42 bytes

[:+/@,8=]+[:+/(<:3 3#:4-.~i.9)|.!.0(_*8&=)

Try it online!

explanation

The high-level approach here is similar to the one used in the classic APL solution to the game of life: https://www.youtube.com/watch?v=a9xAKttWgP4.

In that solution, we shift our matrix in the 8 possible neighbor directions, creating 8 duplicates of the input, stack them up, and then add the "planes" together to get our neighbor counts.

Here, we use a "multiply by infinity" trick to adapt the solution for this problem.

[: +/@, 8 = ] + [: +/ (neighbor deltas) (|.!.0) _ * 8&= NB. 
                                                        NB.
[: +/@,                                                 NB. the sum after flattening
        8 =                                             NB. a 0 1 matrix created by
                                                        NB. elmwise testing if 8
                                                        NB. equals the matrix
            (the matrix to test for equality with 8   ) NB. defined by...
            ] +                                         NB. the original input plus
                [: +/                                   NB. the elmwise sum of 8
                                                        NB. matrices defined by
                                                _ *     NB. the elmwise product of 
                                                        NB. infinity and
                                                    8&= NB. the matrix which is 1
                                                        NB. where the input is 8
                                                        NB. and 0 elsewhere, thus
                                                        NB. creating an infinity-0
                                                        NB. matrix
                                        (|.!.0)         NB. then 2d shifting that 
                                                        NB. matrix in the 8 possible
                                                        NB. "neighbor" directions
                      (neighbor deltas)                 NB. defined by the "neighbor
                                                        NB. deltas" (see below)
                                                        NB. QED.
                                                        NB. ***********************
                                                        NB. The rest of the
                                                        NB. explanation merely
                                                        NB. breaks down the neighbor
                                                        NB. delta construction.


                      (neighbor deltas  )               NB. the neighbor deltas are
                                                        NB. merely the cross product
                                                        NB. of _1 0 1 with itself,
                                                        NB. minus "0 0"
                      (<: 3 3 #: 4 -.~ i.9)             NB. to create that...
                       <:                               NB. subtract one from
                          3 3 #:                        NB. the base 3 rep of
                                       i.9              NB. the numbers 0 - 8
                                 4 -.~                  NB. minus the number 4
                                                        NB.
                                                        NB. All of which produces
                                                        NB. the eight "neighbor"
                                                        NB. deltas:
                                                        NB. 
                                                        NB.       _1 _1
                                                        NB.       _1  0
                                                        NB.       _1  1
                                                        NB.        0 _1
                                                        NB.        0  1
                                                        NB.        1 _1
                                                        NB.        1  0
                                                        NB.        1  1
\$\endgroup\$
2
  • 1
    \$\begingroup\$ You have forgotten to remove a space between ~ and > \$\endgroup\$ Commented Nov 12, 2018 at 11:12
  • \$\begingroup\$ @GalenIvanov Fixed now. Thank you. \$\endgroup\$
    – Jonah
    Commented Nov 12, 2018 at 13:58
3
\$\begingroup\$

Jelly, 12 bytes

œẹ8ạṀ¥þ`’Ạ€S

Try it online!

How it works

œẹ8ạṀ¥þ`’Ạ€S  Main link. Argument: M (matrix)

œẹ8           Find all multidimensional indices of 8, yielding an array A of pairs.
      þ`      Table self; for all pairs [i, j] and [k, l] in A, call the link to the
              left. Return the results as a matrix.
   ạ              Absolute difference; yield [|i - k|, |j - l|].
    Ṁ             Take the maximum.
        ’     Decrement all the maxmima, mapping 1 to 0.
         Ạ€   All each; yield 1 for each row that contains no zeroes.
           S  Take the sum.
\$\endgroup\$
3
\$\begingroup\$

05AB1E, 27 bytes

8Q2Fø0δ.ø}2Fø€ü3}˜9ôʒÅs}OΘO

Try it online or verify all test cases.

Explanation:

8Q       # Check for each inner value in the (implicit) input-matrix if it's an 8
         # (1 if 8; 0 if not)
2Fø0δ.ø} # Add a border of 0s around the matrix:
2F     } #  Loop 2 times:
  ø      #   Zip/transpose; swapping rows/columns
    δ    #   Map over each inner list:
   0 .ø  #    Surround it with a leading/trailing 0
2Fø€ü3}  # Then get all overlapping 3x3 blocks of this modified matrix:
2F    }  #  Loop 2 times again:
  ø      #   Zip/transpose again
   €     #   Map over each inner list again:
    ü3   #    Split it into overlapping triplets
˜        # Flatten the entire list of lists of lists of lists of integers
         # (aka the list of lists of 3x3 blocks)
 9ô      # Split it into parts of size 9
         # (so we now have a single list with flattened 3x3 blocks)
ʒÅs}     # Keep the (flattened) 3x3 blocks with a 1 in the center:
ʒ  }     # Filter over the list of flattened 3x3 blocks:
 Ås      #  Pop the list and push its center value
O        # Sum the inner lists of any remaining flattened 3x3 block
 Θ       # Check for each sum whether it's equal to 1 (1 if 1; 0 otherwise)
  O      # Sum those together again
         # (after which this sum is output implicitly as result)
\$\endgroup\$
2
\$\begingroup\$

Python 2, 130 bytes

lambda a:sum(sum(u[~-c*(c>0):c+2].count(8)for u in a[~-r*(r>0):r+2])*8==8==a[r][c]for r in range(len(a))for c in range(len(a[0])))

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Seems shorter if take length from args \$\endgroup\$
    – l4m2
    Commented Nov 12, 2018 at 2:54
2
\$\begingroup\$

Powershell, 121 bytes

param($a)(($b='='*4*($l=($a|% Le*)[0]))+($a|%{"!$_!"})+$b|sls "(?<=[^8]{3}.{$l}[^8])8(?=[^8].{$l}[^8]{3})" -a|% m*).Count

Less golfed test script:

$f = {

param($a)

$length=($a|% Length)[0]
$border='='*4*$length
$pattern="(?<=[^8]{3}.{$length}[^8])8(?=[^8].{$length}[^8]{3})"
$matches=$border+($a|%{"!$_!"})+$border |sls $pattern -a|% Matches
$matches.count

}

@(

,(3,"84565","93848","08615","67982","88742")
,(0,"88","23")
,(0,"534","252")
,(2,"5838")
,(2,"8","0","8")
,(1,"4285","2618","8558")
,(3,"45438182","82778393","98785428","45021869","15434561")
,(1,"8")
,(4,"85816877","99282783","28497327","92971956","69873152","19971882","35681475")
,(3,"818","257","801")
,(0,"")

) | % {
    $expected,$a = $_
    $result = &$f $a
    "$($result-eq$expected): $result : $a"
}

Output:

True: 3 : 84565 93848 08615 67982 88742
True: 0 : 88 23
True: 0 : 534 252
True: 2 : 5838
True: 2 : 8 0 8
True: 1 : 4285 2618 8558
True: 3 : 45438182 82778393 98785428 45021869 15434561
True: 1 : 8
True: 4 : 85816877 99282783 28497327 92971956 69873152 19971882 35681475
True: 3 : 818 257 801
True: 0 : 

Explanation:

First, the script calculates a length of the first string.

Second, it adds extra border to strings. Augmended reality string likes:

....=========!84565! !93848! !08615! !67982! !88742!===========....

represents the multiline string:

...=====
=======
!84565!
!93848!
!08615!
!67982!
!88742!
=======
========...

Note 1: the number of = is sufficient for a string of any length.

Note 2: a large number of = does not affect the search for eights.

Next, the regular expression (?<=[^8]{3}.{$l}[^8])8(?=[^8].{$l}[^8]{3}) looks for the digit 8 with the preceding non-eights (?<=[^8]{3}.{$l}[^8]) and the following non-eights (?=[^8].{$l}[^8]{3}):

.......
<<<....
<8>....
>>>....
.......

Finally, the number of matches is returned as a result.

\$\endgroup\$
1
\$\begingroup\$

JavaScript (ES6), 106 bytes

a=>a.map((r,y)=>r.map((v,x)=>k+=v==8&[...'12221000'].every((d,i,v)=>(a[y+~-d]||0)[x+~-v[i+2&7]]^8)),k=0)|k

Try it online!


Bitwise approach, 110 bytes

a=>a.map(r=>r.map(v=>x=x*2|v==8,x=k=0)|x).map((n,y,b)=>a[0].map((_,x)=>(n^1<<x|b[y-1]|b[y+1])*2>>x&7||k++))&&k

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Bitwise approach fail on [[7]] \$\endgroup\$
    – l4m2
    Commented Nov 12, 2018 at 2:52
1
\$\begingroup\$

Clojure, 227 198 bytes

(fn[t w h](let[c #(for[y(range %3 %4)x(range % %2)][x y])e #(= 8(get-in t(reverse %)0))m(fn[[o p]](count(filter e(c(dec o)(+ o 2)(dec p)(+ p 2)))))](count(filter #(= 1(m %))(filter e(c 0 w 0 h))))))

Ouch. Definitely not the shortest here by any means. 54 bytes of parenthesis is killer. I'm still relatively happy with it though.

-29 bytes by creating a helper function that generates a range since I was doing that twice, changing the reduce to a (count (filter setup, and getting rid of the threading macro after golfing.

(defn count-single-eights [td-array width height]
  ; Define three helper functions. One generates a list of coords for a given range of dimensions, another checks if an eight is
  ; at the given coord, and the other counts how many neighbors around a coord are an eight
  (letfn [(coords [x-min x-max y-min y-max]
            (for [y (range y-min y-max)
                  x (range x-min x-max)]
              [x y]))
          (eight? [[x y]] (= 8 (get-in td-array [y x] 0)))
          (n-eights-around [[cx cy]]
            (count (filter eight?
                           (coords (dec cx) (+ cx 2), (dec cy) (+ cy 2)))))]

    ; Gen a list of each coord of the matrix
    (->> (coords 0 width, 0 height)

         ; Remove any coords that don't contain an eight
         (filter eight?)

         ; Then count how many "neighborhoods" only contain 1 eight
         (filter #(= 1 (n-eights-around %)))
         (count))))

(mapv #(count-single-eights % (count (% 0)) (count %))
      test-cases)
=> [3 0 0 2 2 1 3 1 4 3]

Where test-cases is an array holding all the "Python test cases"

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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