All the single eights
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
You can optionally take two numbers defining the size of the array as additional inputs.
Input can be taken by any reasonable means. The format is flexible as usual. For example, it can be a 2D character array, or a list of lists of numbers, or a flat list.
Programs or functions are allowed, in any programming language. Standard loopholes are forbidden.
Shortest code in bytes wins.
Test cases
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
Input
8 8
2 3
Output:
0
Input:
5 3 4
2 5 2
Output:
0
Input:
5 8 3 8
Output:
2
Input:
8
0
8
Output:
2
.
Input:
4 2 8 5
2 6 1 8
8 5 5 8
Output:
1
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
.
Input:
8
Output:
1
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
.
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
code-golf array-manipulation integer
add a comment |
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
You can optionally take two numbers defining the size of the array as additional inputs.
Input can be taken by any reasonable means. The format is flexible as usual. For example, it can be a 2D character array, or a list of lists of numbers, or a flat list.
Programs or functions are allowed, in any programming language. Standard loopholes are forbidden.
Shortest code in bytes wins.
Test cases
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
Input
8 8
2 3
Output:
0
Input:
5 3 4
2 5 2
Output:
0
Input:
5 8 3 8
Output:
2
Input:
8
0
8
Output:
2
.
Input:
4 2 8 5
2 6 1 8
8 5 5 8
Output:
1
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
.
Input:
8
Output:
1
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
.
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
code-golf array-manipulation integer
15
If you like it then you should have put a vote on it
– Luis Mendo
Nov 11 at 19:52
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
– Tezra
Nov 12 at 17:46
@Tezra Edited. I find the new wording a little less natural, but I’m not a native speaker so I’ll trust your criterion
– Luis Mendo
Nov 12 at 18:57
add a comment |
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
You can optionally take two numbers defining the size of the array as additional inputs.
Input can be taken by any reasonable means. The format is flexible as usual. For example, it can be a 2D character array, or a list of lists of numbers, or a flat list.
Programs or functions are allowed, in any programming language. Standard loopholes are forbidden.
Shortest code in bytes wins.
Test cases
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
Input
8 8
2 3
Output:
0
Input:
5 3 4
2 5 2
Output:
0
Input:
5 8 3 8
Output:
2
Input:
8
0
8
Output:
2
.
Input:
4 2 8 5
2 6 1 8
8 5 5 8
Output:
1
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
.
Input:
8
Output:
1
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
.
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
code-golf array-manipulation integer
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
You can optionally take two numbers defining the size of the array as additional inputs.
Input can be taken by any reasonable means. The format is flexible as usual. For example, it can be a 2D character array, or a list of lists of numbers, or a flat list.
Programs or functions are allowed, in any programming language. Standard loopholes are forbidden.
Shortest code in bytes wins.
Test cases
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
Input
8 8
2 3
Output:
0
Input:
5 3 4
2 5 2
Output:
0
Input:
5 8 3 8
Output:
2
Input:
8
0
8
Output:
2
.
Input:
4 2 8 5
2 6 1 8
8 5 5 8
Output:
1
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
.
Input:
8
Output:
1
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
.
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
code-golf array-manipulation integer
code-golf array-manipulation integer
edited Nov 12 at 18:56
asked Nov 11 at 19:52
Luis Mendo
74k886291
74k886291
15
If you like it then you should have put a vote on it
– Luis Mendo
Nov 11 at 19:52
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
– Tezra
Nov 12 at 17:46
@Tezra Edited. I find the new wording a little less natural, but I’m not a native speaker so I’ll trust your criterion
– Luis Mendo
Nov 12 at 18:57
add a comment |
15
If you like it then you should have put a vote on it
– Luis Mendo
Nov 11 at 19:52
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
– Tezra
Nov 12 at 17:46
@Tezra Edited. I find the new wording a little less natural, but I’m not a native speaker so I’ll trust your criterion
– Luis Mendo
Nov 12 at 18:57
15
15
If you like it then you should have put a vote on it
– Luis Mendo
Nov 11 at 19:52
If you like it then you should have put a vote on it
– Luis Mendo
Nov 11 at 19:52
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
– Tezra
Nov 12 at 17:46
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
– Tezra
Nov 12 at 17:46
@Tezra Edited. I find the new wording a little less natural, but I’m not a native speaker so I’ll trust your criterion
– Luis Mendo
Nov 12 at 18:57
@Tezra Edited. I find the new wording a little less natural, but I’m not a native speaker so I’ll trust your criterion
– Luis Mendo
Nov 12 at 18:57
add a comment |
15 Answers
15
active
oldest
votes
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
You could save quite a few bytes using (2D-)convolution, if you are famiiar with the concept
– Luis Mendo
Nov 12 at 17:31
1
@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!
– Giuseppe
Nov 12 at 17:33
1
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
– Luis Mendo
Nov 12 at 17:39
add a comment |
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
.
it's a shame numerical imprecision doesn't allowcolSums()^2<=2
to work.
– Giuseppe
Nov 12 at 22:28
@Giuseppe of course there are only a few possible distances andsqrt(2)
jumps to2
(e.g.sort(c(dist(expand.grid(1:6,1:6))), decreasing = TRUE))
) so we were being too clever there.
– ngm
Nov 13 at 15:33
add a comment |
APL (Dyalog Classic), 29 28 25 bytes
≢∘⍸16=2⊥¨3,⌿3,/8=(⍉0,⌽)⍣4
Try it online!
Note: 0 index origin is not even needed.
– Zacharý
Nov 12 at 16:36
@Zacharý I always use it as a default, to avoid surprises.
– ngn
Nov 12 at 20:03
Ah, so like others with1
(except not explicitly set). That makes sense.
– Zacharý
Nov 12 at 20:05
Surprised this doesn't use Stencil. Is there something that makes stencil inconvenient here?
– lirtosiast
Nov 20 at 7:49
@lirtosiast it's just longer with it :)
– ngn
Nov 20 at 9:39
add a comment |
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
add a comment |
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
add a comment |
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
1
37 bytes using@:
and moving|.
. Note that@
in place of@:
doesn't work.
– Bubbler
Nov 12 at 10:26
@Bubbler Thank you!
– Galen Ivanov
Nov 12 at 11:07
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...
– Jonah
Nov 12 at 15:00
@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
– Galen Ivanov
Nov 12 at 15:16
1
@Jonah Explanation added
– Galen Ivanov
Nov 12 at 18:26
add a comment |
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 8
s 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 8
s.
(?!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.
add a comment |
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)
add a comment |
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
1
You have forgotten to remove a space between~
and>
– Galen Ivanov
Nov 12 at 11:12
@GalenIvanov Fixed now. Thank you.
– Jonah
Nov 12 at 13:58
add a comment |
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!
Seems shorter if take length from args
– l4m2
Nov 12 at 2:54
add a comment |
Java 8, 181 bytes
(M,R,C)->{int z=0,c,f,t;for(;R-->0;)for(c=C;c-->0;z+=f==1?1:0)for(f=0,t=9;M[R][c]==8&t-->0;)try{f+=M[t<3?R-1:t>5?R+1:R][t%3<1?c-1:t%3>1?c+1:c]==8?1:0;}catch(Exception e){}return z;}
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==1? // If the flag-integer is exactly 1:
1 // Increase the result-counter by 1
:0) // Else: leave it the same
for(f=0, // Reset the flag to 0
t=9;M[R][c]==8& // If the current cell contains an 8:
t-->0;) // Inner loop `t` in the range (9, 0]:
try{f+= // Increase the flag by:
M[t<3? // If `t` is 0, 1, or 2:
R-1 // Look at the previous row
:t>5? // Else-if `t` is 6, 7, or 8:
R+1 // Look at the next row
: // Else (`t` is 3, 4, or 5):
R] // Look at the current row
[t%3<1? // If `t` is 0, 3, or 6:
c-1 // Look at the previous column
:t%3>1? // Else-if `t` is 2, 5, or 8:
c+1 // Look at the next column
: // Else (`t` is 1, 4, or 7):
c] // Look at the current column
==8? // If the digit in this cell is 8:
1 // Increase the flag-integer by 1
:0; // Else: leave it the same
}catch(Exception e){} // Catch and ignore ArrayIndexOutOfBoundsExceptions
// (try-catch saves bytes in comparison to if-checks)
return z;} // And finally return the counter
add a comment |
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.
add a comment |
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.
add a comment |
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!
Bitwise approach fail on[[7]]
– l4m2
Nov 12 at 2:52
@lm42 Oh, thanks. Now fixed.
– Arnauld
Nov 12 at 9:29
add a comment |
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!
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "200"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodegolf.stackexchange.com%2fquestions%2f175724%2fall-the-single-eights%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
15 Answers
15
active
oldest
votes
15 Answers
15
active
oldest
votes
active
oldest
votes
active
oldest
votes
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
You could save quite a few bytes using (2D-)convolution, if you are famiiar with the concept
– Luis Mendo
Nov 12 at 17:31
1
@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!
– Giuseppe
Nov 12 at 17:33
1
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
– Luis Mendo
Nov 12 at 17:39
add a comment |
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
You could save quite a few bytes using (2D-)convolution, if you are famiiar with the concept
– Luis Mendo
Nov 12 at 17:31
1
@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!
– Giuseppe
Nov 12 at 17:33
1
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
– Luis Mendo
Nov 12 at 17:39
add a comment |
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
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
edited Nov 12 at 19:44
answered Nov 12 at 15:51
Giuseppe
16.6k31052
16.6k31052
You could save quite a few bytes using (2D-)convolution, if you are famiiar with the concept
– Luis Mendo
Nov 12 at 17:31
1
@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!
– Giuseppe
Nov 12 at 17:33
1
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
– Luis Mendo
Nov 12 at 17:39
add a comment |
You could save quite a few bytes using (2D-)convolution, if you are famiiar with the concept
– Luis Mendo
Nov 12 at 17:31
1
@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!
– Giuseppe
Nov 12 at 17:33
1
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
– Luis Mendo
Nov 12 at 17:39
You could save quite a few bytes using (2D-)convolution, if you are famiiar with the concept
– Luis Mendo
Nov 12 at 17:31
You could save quite a few bytes using (2D-)convolution, if you are famiiar with the concept
– Luis Mendo
Nov 12 at 17:31
1
1
@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!
– Giuseppe
Nov 12 at 17:33
@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!
– Giuseppe
Nov 12 at 17:33
1
1
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
– Luis Mendo
Nov 12 at 17:39
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
– Luis Mendo
Nov 12 at 17:39
add a comment |
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
.
it's a shame numerical imprecision doesn't allowcolSums()^2<=2
to work.
– Giuseppe
Nov 12 at 22:28
@Giuseppe of course there are only a few possible distances andsqrt(2)
jumps to2
(e.g.sort(c(dist(expand.grid(1:6,1:6))), decreasing = TRUE))
) so we were being too clever there.
– ngm
Nov 13 at 15:33
add a comment |
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
.
it's a shame numerical imprecision doesn't allowcolSums()^2<=2
to work.
– Giuseppe
Nov 12 at 22:28
@Giuseppe of course there are only a few possible distances andsqrt(2)
jumps to2
(e.g.sort(c(dist(expand.grid(1:6,1:6))), decreasing = TRUE))
) so we were being too clever there.
– ngm
Nov 13 at 15:33
add a comment |
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
.
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
.
edited Nov 13 at 15:31
answered Nov 12 at 16:18
ngm
3,27924
3,27924
it's a shame numerical imprecision doesn't allowcolSums()^2<=2
to work.
– Giuseppe
Nov 12 at 22:28
@Giuseppe of course there are only a few possible distances andsqrt(2)
jumps to2
(e.g.sort(c(dist(expand.grid(1:6,1:6))), decreasing = TRUE))
) so we were being too clever there.
– ngm
Nov 13 at 15:33
add a comment |
it's a shame numerical imprecision doesn't allowcolSums()^2<=2
to work.
– Giuseppe
Nov 12 at 22:28
@Giuseppe of course there are only a few possible distances andsqrt(2)
jumps to2
(e.g.sort(c(dist(expand.grid(1:6,1:6))), decreasing = TRUE))
) so we were being too clever there.
– ngm
Nov 13 at 15:33
it's a shame numerical imprecision doesn't allow
colSums()^2<=2
to work.– Giuseppe
Nov 12 at 22:28
it's a shame numerical imprecision doesn't allow
colSums()^2<=2
to work.– Giuseppe
Nov 12 at 22:28
@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.– ngm
Nov 13 at 15:33
@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.– ngm
Nov 13 at 15:33
add a comment |
APL (Dyalog Classic), 29 28 25 bytes
≢∘⍸16=2⊥¨3,⌿3,/8=(⍉0,⌽)⍣4
Try it online!
Note: 0 index origin is not even needed.
– Zacharý
Nov 12 at 16:36
@Zacharý I always use it as a default, to avoid surprises.
– ngn
Nov 12 at 20:03
Ah, so like others with1
(except not explicitly set). That makes sense.
– Zacharý
Nov 12 at 20:05
Surprised this doesn't use Stencil. Is there something that makes stencil inconvenient here?
– lirtosiast
Nov 20 at 7:49
@lirtosiast it's just longer with it :)
– ngn
Nov 20 at 9:39
add a comment |
APL (Dyalog Classic), 29 28 25 bytes
≢∘⍸16=2⊥¨3,⌿3,/8=(⍉0,⌽)⍣4
Try it online!
Note: 0 index origin is not even needed.
– Zacharý
Nov 12 at 16:36
@Zacharý I always use it as a default, to avoid surprises.
– ngn
Nov 12 at 20:03
Ah, so like others with1
(except not explicitly set). That makes sense.
– Zacharý
Nov 12 at 20:05
Surprised this doesn't use Stencil. Is there something that makes stencil inconvenient here?
– lirtosiast
Nov 20 at 7:49
@lirtosiast it's just longer with it :)
– ngn
Nov 20 at 9:39
add a comment |
APL (Dyalog Classic), 29 28 25 bytes
≢∘⍸16=2⊥¨3,⌿3,/8=(⍉0,⌽)⍣4
Try it online!
APL (Dyalog Classic), 29 28 25 bytes
≢∘⍸16=2⊥¨3,⌿3,/8=(⍉0,⌽)⍣4
Try it online!
edited Nov 12 at 10:34
answered Nov 12 at 9:37
ngn
6,94112559
6,94112559
Note: 0 index origin is not even needed.
– Zacharý
Nov 12 at 16:36
@Zacharý I always use it as a default, to avoid surprises.
– ngn
Nov 12 at 20:03
Ah, so like others with1
(except not explicitly set). That makes sense.
– Zacharý
Nov 12 at 20:05
Surprised this doesn't use Stencil. Is there something that makes stencil inconvenient here?
– lirtosiast
Nov 20 at 7:49
@lirtosiast it's just longer with it :)
– ngn
Nov 20 at 9:39
add a comment |
Note: 0 index origin is not even needed.
– Zacharý
Nov 12 at 16:36
@Zacharý I always use it as a default, to avoid surprises.
– ngn
Nov 12 at 20:03
Ah, so like others with1
(except not explicitly set). That makes sense.
– Zacharý
Nov 12 at 20:05
Surprised this doesn't use Stencil. Is there something that makes stencil inconvenient here?
– lirtosiast
Nov 20 at 7:49
@lirtosiast it's just longer with it :)
– ngn
Nov 20 at 9:39
Note: 0 index origin is not even needed.
– Zacharý
Nov 12 at 16:36
Note: 0 index origin is not even needed.
– Zacharý
Nov 12 at 16:36
@Zacharý I always use it as a default, to avoid surprises.
– ngn
Nov 12 at 20:03
@Zacharý I always use it as a default, to avoid surprises.
– ngn
Nov 12 at 20:03
Ah, so like others with
1
(except not explicitly set). That makes sense.– Zacharý
Nov 12 at 20:05
Ah, so like others with
1
(except not explicitly set). That makes sense.– Zacharý
Nov 12 at 20:05
Surprised this doesn't use Stencil. Is there something that makes stencil inconvenient here?
– lirtosiast
Nov 20 at 7:49
Surprised this doesn't use Stencil. Is there something that makes stencil inconvenient here?
– lirtosiast
Nov 20 at 7:49
@lirtosiast it's just longer with it :)
– ngn
Nov 20 at 9:39
@lirtosiast it's just longer with it :)
– ngn
Nov 20 at 9:39
add a comment |
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
add a comment |
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
add a comment |
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
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
edited Nov 12 at 9:15
answered Nov 12 at 5:15
Bubbler
6,282759
6,282759
add a comment |
add a comment |
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
add a comment |
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
add a comment |
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
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
edited Nov 12 at 12:12
answered Nov 12 at 0:14
l4m2
4,6281634
4,6281634
add a comment |
add a comment |
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
1
37 bytes using@:
and moving|.
. Note that@
in place of@:
doesn't work.
– Bubbler
Nov 12 at 10:26
@Bubbler Thank you!
– Galen Ivanov
Nov 12 at 11:07
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...
– Jonah
Nov 12 at 15:00
@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
– Galen Ivanov
Nov 12 at 15:16
1
@Jonah Explanation added
– Galen Ivanov
Nov 12 at 18:26
add a comment |
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
1
37 bytes using@:
and moving|.
. Note that@
in place of@:
doesn't work.
– Bubbler
Nov 12 at 10:26
@Bubbler Thank you!
– Galen Ivanov
Nov 12 at 11:07
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...
– Jonah
Nov 12 at 15:00
@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
– Galen Ivanov
Nov 12 at 15:16
1
@Jonah Explanation added
– Galen Ivanov
Nov 12 at 18:26
add a comment |
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
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
edited Nov 12 at 18:23
answered Nov 12 at 7:57
Galen Ivanov
6,32711032
6,32711032
1
37 bytes using@:
and moving|.
. Note that@
in place of@:
doesn't work.
– Bubbler
Nov 12 at 10:26
@Bubbler Thank you!
– Galen Ivanov
Nov 12 at 11:07
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...
– Jonah
Nov 12 at 15:00
@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
– Galen Ivanov
Nov 12 at 15:16
1
@Jonah Explanation added
– Galen Ivanov
Nov 12 at 18:26
add a comment |
1
37 bytes using@:
and moving|.
. Note that@
in place of@:
doesn't work.
– Bubbler
Nov 12 at 10:26
@Bubbler Thank you!
– Galen Ivanov
Nov 12 at 11:07
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...
– Jonah
Nov 12 at 15:00
@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
– Galen Ivanov
Nov 12 at 15:16
1
@Jonah Explanation added
– Galen Ivanov
Nov 12 at 18:26
1
1
37 bytes using
@:
and moving |.
. Note that @
in place of @:
doesn't work.– Bubbler
Nov 12 at 10:26
37 bytes using
@:
and moving |.
. Note that @
in place of @:
doesn't work.– Bubbler
Nov 12 at 10:26
@Bubbler Thank you!
– Galen Ivanov
Nov 12 at 11:07
@Bubbler Thank you!
– Galen Ivanov
Nov 12 at 11:07
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...
– Jonah
Nov 12 at 15:00
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...
– Jonah
Nov 12 at 15:00
@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
– Galen Ivanov
Nov 12 at 15:16
@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
– Galen Ivanov
Nov 12 at 15:16
1
1
@Jonah Explanation added
– Galen Ivanov
Nov 12 at 18:26
@Jonah Explanation added
– Galen Ivanov
Nov 12 at 18:26
add a comment |
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 8
s 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 8
s.
(?!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.
add a comment |
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 8
s 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 8
s.
(?!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.
add a comment |
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 8
s 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 8
s.
(?!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.
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 8
s 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 8
s.
(?!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.
answered Nov 11 at 21:02
Neil
79.3k744177
79.3k744177
add a comment |
add a comment |
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)
add a comment |
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)
add a comment |
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)
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)
edited Nov 11 at 21:36
answered Nov 11 at 20:36
Jonathan Allan
50.7k534165
50.7k534165
add a comment |
add a comment |
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
1
You have forgotten to remove a space between~
and>
– Galen Ivanov
Nov 12 at 11:12
@GalenIvanov Fixed now. Thank you.
– Jonah
Nov 12 at 13:58
add a comment |
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
1
You have forgotten to remove a space between~
and>
– Galen Ivanov
Nov 12 at 11:12
@GalenIvanov Fixed now. Thank you.
– Jonah
Nov 12 at 13:58
add a comment |
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
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
edited Nov 12 at 16:32
answered Nov 12 at 0:55
Jonah
2,011816
2,011816
1
You have forgotten to remove a space between~
and>
– Galen Ivanov
Nov 12 at 11:12
@GalenIvanov Fixed now. Thank you.
– Jonah
Nov 12 at 13:58
add a comment |
1
You have forgotten to remove a space between~
and>
– Galen Ivanov
Nov 12 at 11:12
@GalenIvanov Fixed now. Thank you.
– Jonah
Nov 12 at 13:58
1
1
You have forgotten to remove a space between
~
and >
– Galen Ivanov
Nov 12 at 11:12
You have forgotten to remove a space between
~
and >
– Galen Ivanov
Nov 12 at 11:12
@GalenIvanov Fixed now. Thank you.
– Jonah
Nov 12 at 13:58
@GalenIvanov Fixed now. Thank you.
– Jonah
Nov 12 at 13:58
add a comment |
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!
Seems shorter if take length from args
– l4m2
Nov 12 at 2:54
add a comment |
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!
Seems shorter if take length from args
– l4m2
Nov 12 at 2:54
add a comment |
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!
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!
edited Nov 11 at 22:18
answered Nov 11 at 22:11
Chas Brown
4,8081522
4,8081522
Seems shorter if take length from args
– l4m2
Nov 12 at 2:54
add a comment |
Seems shorter if take length from args
– l4m2
Nov 12 at 2:54
Seems shorter if take length from args
– l4m2
Nov 12 at 2:54
Seems shorter if take length from args
– l4m2
Nov 12 at 2:54
add a comment |
Java 8, 181 bytes
(M,R,C)->{int z=0,c,f,t;for(;R-->0;)for(c=C;c-->0;z+=f==1?1:0)for(f=0,t=9;M[R][c]==8&t-->0;)try{f+=M[t<3?R-1:t>5?R+1:R][t%3<1?c-1:t%3>1?c+1:c]==8?1:0;}catch(Exception e){}return z;}
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==1? // If the flag-integer is exactly 1:
1 // Increase the result-counter by 1
:0) // Else: leave it the same
for(f=0, // Reset the flag to 0
t=9;M[R][c]==8& // If the current cell contains an 8:
t-->0;) // Inner loop `t` in the range (9, 0]:
try{f+= // Increase the flag by:
M[t<3? // If `t` is 0, 1, or 2:
R-1 // Look at the previous row
:t>5? // Else-if `t` is 6, 7, or 8:
R+1 // Look at the next row
: // Else (`t` is 3, 4, or 5):
R] // Look at the current row
[t%3<1? // If `t` is 0, 3, or 6:
c-1 // Look at the previous column
:t%3>1? // Else-if `t` is 2, 5, or 8:
c+1 // Look at the next column
: // Else (`t` is 1, 4, or 7):
c] // Look at the current column
==8? // If the digit in this cell is 8:
1 // Increase the flag-integer by 1
:0; // Else: leave it the same
}catch(Exception e){} // Catch and ignore ArrayIndexOutOfBoundsExceptions
// (try-catch saves bytes in comparison to if-checks)
return z;} // And finally return the counter
add a comment |
Java 8, 181 bytes
(M,R,C)->{int z=0,c,f,t;for(;R-->0;)for(c=C;c-->0;z+=f==1?1:0)for(f=0,t=9;M[R][c]==8&t-->0;)try{f+=M[t<3?R-1:t>5?R+1:R][t%3<1?c-1:t%3>1?c+1:c]==8?1:0;}catch(Exception e){}return z;}
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==1? // If the flag-integer is exactly 1:
1 // Increase the result-counter by 1
:0) // Else: leave it the same
for(f=0, // Reset the flag to 0
t=9;M[R][c]==8& // If the current cell contains an 8:
t-->0;) // Inner loop `t` in the range (9, 0]:
try{f+= // Increase the flag by:
M[t<3? // If `t` is 0, 1, or 2:
R-1 // Look at the previous row
:t>5? // Else-if `t` is 6, 7, or 8:
R+1 // Look at the next row
: // Else (`t` is 3, 4, or 5):
R] // Look at the current row
[t%3<1? // If `t` is 0, 3, or 6:
c-1 // Look at the previous column
:t%3>1? // Else-if `t` is 2, 5, or 8:
c+1 // Look at the next column
: // Else (`t` is 1, 4, or 7):
c] // Look at the current column
==8? // If the digit in this cell is 8:
1 // Increase the flag-integer by 1
:0; // Else: leave it the same
}catch(Exception e){} // Catch and ignore ArrayIndexOutOfBoundsExceptions
// (try-catch saves bytes in comparison to if-checks)
return z;} // And finally return the counter
add a comment |
Java 8, 181 bytes
(M,R,C)->{int z=0,c,f,t;for(;R-->0;)for(c=C;c-->0;z+=f==1?1:0)for(f=0,t=9;M[R][c]==8&t-->0;)try{f+=M[t<3?R-1:t>5?R+1:R][t%3<1?c-1:t%3>1?c+1:c]==8?1:0;}catch(Exception e){}return z;}
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==1? // If the flag-integer is exactly 1:
1 // Increase the result-counter by 1
:0) // Else: leave it the same
for(f=0, // Reset the flag to 0
t=9;M[R][c]==8& // If the current cell contains an 8:
t-->0;) // Inner loop `t` in the range (9, 0]:
try{f+= // Increase the flag by:
M[t<3? // If `t` is 0, 1, or 2:
R-1 // Look at the previous row
:t>5? // Else-if `t` is 6, 7, or 8:
R+1 // Look at the next row
: // Else (`t` is 3, 4, or 5):
R] // Look at the current row
[t%3<1? // If `t` is 0, 3, or 6:
c-1 // Look at the previous column
:t%3>1? // Else-if `t` is 2, 5, or 8:
c+1 // Look at the next column
: // Else (`t` is 1, 4, or 7):
c] // Look at the current column
==8? // If the digit in this cell is 8:
1 // Increase the flag-integer by 1
:0; // Else: leave it the same
}catch(Exception e){} // Catch and ignore ArrayIndexOutOfBoundsExceptions
// (try-catch saves bytes in comparison to if-checks)
return z;} // And finally return the counter
Java 8, 181 bytes
(M,R,C)->{int z=0,c,f,t;for(;R-->0;)for(c=C;c-->0;z+=f==1?1:0)for(f=0,t=9;M[R][c]==8&t-->0;)try{f+=M[t<3?R-1:t>5?R+1:R][t%3<1?c-1:t%3>1?c+1:c]==8?1:0;}catch(Exception e){}return z;}
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==1? // If the flag-integer is exactly 1:
1 // Increase the result-counter by 1
:0) // Else: leave it the same
for(f=0, // Reset the flag to 0
t=9;M[R][c]==8& // If the current cell contains an 8:
t-->0;) // Inner loop `t` in the range (9, 0]:
try{f+= // Increase the flag by:
M[t<3? // If `t` is 0, 1, or 2:
R-1 // Look at the previous row
:t>5? // Else-if `t` is 6, 7, or 8:
R+1 // Look at the next row
: // Else (`t` is 3, 4, or 5):
R] // Look at the current row
[t%3<1? // If `t` is 0, 3, or 6:
c-1 // Look at the previous column
:t%3>1? // Else-if `t` is 2, 5, or 8:
c+1 // Look at the next column
: // Else (`t` is 1, 4, or 7):
c] // Look at the current column
==8? // If the digit in this cell is 8:
1 // Increase the flag-integer by 1
:0; // Else: leave it the same
}catch(Exception e){} // Catch and ignore ArrayIndexOutOfBoundsExceptions
// (try-catch saves bytes in comparison to if-checks)
return z;} // And finally return the counter
edited Nov 12 at 12:50
answered Nov 12 at 12:37
Kevin Cruijssen
35.6k554186
35.6k554186
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Nov 12 at 16:51
mazzy
2,0951315
2,0951315
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
edited Nov 12 at 21:37
answered Nov 12 at 20:14
Dennis♦
186k32296735
186k32296735
add a comment |
add a comment |
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!
Bitwise approach fail on[[7]]
– l4m2
Nov 12 at 2:52
@lm42 Oh, thanks. Now fixed.
– Arnauld
Nov 12 at 9:29
add a comment |
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!
Bitwise approach fail on[[7]]
– l4m2
Nov 12 at 2:52
@lm42 Oh, thanks. Now fixed.
– Arnauld
Nov 12 at 9:29
add a comment |
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!
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!
edited Nov 12 at 9:29
answered Nov 11 at 23:53
Arnauld
72.4k689305
72.4k689305
Bitwise approach fail on[[7]]
– l4m2
Nov 12 at 2:52
@lm42 Oh, thanks. Now fixed.
– Arnauld
Nov 12 at 9:29
add a comment |
Bitwise approach fail on[[7]]
– l4m2
Nov 12 at 2:52
@lm42 Oh, thanks. Now fixed.
– Arnauld
Nov 12 at 9:29
Bitwise approach fail on
[[7]]
– l4m2
Nov 12 at 2:52
Bitwise approach fail on
[[7]]
– l4m2
Nov 12 at 2:52
@lm42 Oh, thanks. Now fixed.
– Arnauld
Nov 12 at 9:29
@lm42 Oh, thanks. Now fixed.
– Arnauld
Nov 12 at 9:29
add a comment |
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!
add a comment |
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!
add a comment |
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!
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!
edited Nov 13 at 3:55
answered Nov 12 at 21:45
Carcigenicate
2,26911224
2,26911224
add a comment |
add a comment |
If this is an answer to a challenge…
…Be sure to follow the challenge specification. However, please refrain from exploiting obvious loopholes. Answers abusing any of the standard loopholes are considered invalid. If you think a specification is unclear or underspecified, comment on the question instead.
…Try to optimize your score. For instance, answers to code-golf challenges should attempt to be as short as possible. You can always include a readable version of the code in addition to the competitive one.
Explanations of your answer make it more interesting to read and are very much encouraged.…Include a short header which indicates the language(s) of your code and its score, as defined by the challenge.
More generally…
…Please make sure to answer the question and provide sufficient detail.
…Avoid asking for help, clarification or responding to other answers (use comments instead).
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodegolf.stackexchange.com%2fquestions%2f175724%2fall-the-single-eights%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
15
If you like it then you should have put a vote on it
– Luis Mendo
Nov 11 at 19:52
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
– Tezra
Nov 12 at 17:46
@Tezra Edited. I find the new wording a little less natural, but I’m not a native speaker so I’ll trust your criterion
– Luis Mendo
Nov 12 at 18:57