所有的单八


24

给定一个从0to到的整数的非空矩形数组9,输出的是8和没有相邻的像元的数量为8。这里,在摩尔意义上理解相邻,即包括对角线。因此,每个单元都有8邻居,除了阵列边缘的单元之外。

例如,给定输入

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

输出应为3。以下是三个合格单元格,并标有星号(但仅应输出此类条目的数量):

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

附加规则

  • 您可以选择将定义数组大小的两个数字用作附加输入。

  • 可以通过任何合理的方式进行输入。格式像往常一样灵活。例如,它可以是2D字符数组,也可以是数字列表的列表,也可以是平面列表。

  • 允许使用任何编程语言编写程序或功能。禁止出现标准漏洞

  • 以字节为单位的最短代码获胜。

测试用例

  1. 输入:

    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
    

    输出: 3

  2. 输入项

    8 8
    2 3
    

    输出: 0

  3. 输入:

    5 3 4
    2 5 2
    

    输出: 0

  4. 输入:

    5 8 3 8
    

    输出: 2

  5. 输入:

    8
    0
    8
    

    输出:2

  6. 输入:

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

    输出: 1

  7. 输入:

    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
    

    输出3

  8. 输入:

    8
    

    输出: 1

  9. 输入:

    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
    

    输出:4

  10. 输入:

    8 1 8
    2 5 7
    8 0 1
    

    输出:3

MATLAB格式的输入:

[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]

输入为Python格式:

[[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]]

输出:

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

17
如果你喜欢它,那么你应该把它一票
路易斯Mendo

当我读到“等于8的像元”时,我以为您的意思是一个像元可能大于网格的1x1卡盘(NxN)。应该将其改为“ 8个单元格”,以澄清不需要的数学运算。= P
Tezra

@Tezra编辑。我觉得新措辞不太自然,但我不是母语人士,所以我相信您的判断标准
Luis Mendo

Answers:


2

MATL21 17 10字节

8=t3Y6Z+>z

在线尝试!

感谢Luis Mendo在聊天方面的帮助以及建议2D卷积。

说明:

	#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

如果您熟悉这个概念,可以使用(2D-)卷积节省很多字节
Luis

1
@LuisMendo 2D卷积是我也不了解1D卷积的事情之一,因此我对那里没有希望...听起来像是一次学习两者的机会!
朱塞佩

1
如果您需要帮助,请在聊天室告诉我。卷积是非常有用的操作。如果要学习卷积,请从1D开始。立即将2D泛化
Luis Mendo

9

R117 63 59字节

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

在线尝试!

dist计算矩阵行之间的距离(默认为欧几里得)。which与第二个参数一起TRUE返回谓词为true的坐标。

如果坐标之间的距离不大于2的平方根,则它们是邻居,但是内部坐标<2足够好,因为可能的距离从sqrt(2)ro 跳到2


令人遗憾的是,数值不精确无法colSums()^2<=2正常工作。
朱塞佩

@Giuseppe当然只有几步之遥,而且sqrt(2)跳到2(例如sort(c(dist(expand.grid(1:6,1:6))), decreasing = TRUE))),所以我们在那里太聪明了。
ngm

7

APL(Dyalog Classic)29 28 25字节

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

在线尝试!


注意:甚至不需要0索引原点。
扎卡里

@Zacharý我始终将其用作默认设置,以避免出现意外情况。
ngn

嗯,就像其他人一样1(除非没有明确设置)。那讲得通。
扎卡里

感到惊讶的是它不使用模具。有什么使模版不方便的地方吗?
lirtosiast

@lirtosiast它只是不再与它:)
NGN

5

果冻18 15字节

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

在线尝试!

怎么运行的

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

先前的解决方案,18字节

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

在线尝试!

想要共享另一种方法,尽管比Jonathan Allan的解决方案长1个字节。

怎么运行的

æ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


4

J43,40 37字节

-3个字节,得益于Bubbler

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

在线尝试!

说明:

该算法的第一部分确保我们可以将3x3滑动窗口应用于输入。这是通过在行之前放置零和90度旋转(重复4次)来实现的。

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个字节|.。请注意,@代替@:无效。
Bubbler

@Bubbler谢谢!
加伦·伊万诺夫

很好 如果没有代码故障,可能值得至少对其功能进行高层次的解释。我花了大约一千万才能解决。同样,有趣的是APL版本(使用相同的方法)短了多少。看起来这主要是有向图而不是单个字符符号的结果……
乔纳

@Jonah我将添加一个解释。为了与APL进行比较,您可以查看ngn解决方案的修订版,尤其是28字节版本
Galen Ivanov,

1
@Jonah说明添加
盖伦·伊万诺夫

3

视网膜0.8.2,84字节

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

在线尝试!说明:

.+
_$&_

用非8字符将每一行换行,以便所有8s的每一侧至少有一个字符。

m`

这是最后一个阶段,因此暗含进行比赛的次数。所述m改性剂使^$字符在任何行的开始或结束相匹配。

(?<!...|8)

不要在8之后直接匹配一个字符,否则...

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

...低于8的字符;(?(1).)^(?<-1>.)*¶(.)*下一行的匹配同一列,但.?.?允许在下一行的8后面将字符设为1左右.

8

匹配8

(?!8|...)

不要在8之前立即匹配8,否则...

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

...下面一行中有8的字符;再次,该(?<-2>.)*$(?(2).)字段(.)*¶与上一行的匹配同一列,但.?.?允许的值在上一行88之前为左或右.


3

果冻,17 个字节

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

在线尝试!或查看测试套件

怎么样?

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

3

J,42个字节

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

在线尝试!

说明

这里的高级方法类似于经典的APL解决方案,用于生活游戏:https//www.youtube.com/watch?v = a9xAKttWgP4

在该解决方案中,我们在8个可能的相邻方向上移动矩阵,创建输入的8个重复项,将其堆叠,然后将“平面”加在一起以获得我们的邻居计数。

在这里,我们使用“乘以无穷大”的技巧来调整解决方案以解决此问题。

[: +/@, 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
您忘记了~和之间删除空格。>
Galen Ivanov

@GalenIvanov现在固定。谢谢。
乔纳

3

Java的8,181个 157 156字节

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

-24个字节,感谢@OlivierGrégoire

将维度作为附加参数R(行数)和C(列数)。

正如我在做的细胞检查非常相似炸模拟器的答案

在线尝试。

说明:

(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 larger than 1:
                0             //       Leave the result-counter the same by adding 0
               :              //      Else:
                f)            //       Add the flag-integer (either 0 or 1)
      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[R+t/3-1]     //       If `t` is 0, 1, or 2: Look at the previous row
                              //       Else-if `t` is 6, 7, or 8: Look at the next row
                              //       Else (`t` is 3, 4, or 5): Look at the current row
                [c+t%3-1]     //       If `t` is 0, 3, or 6: Look at the previous column
                              //       Else-if `t` is 2, 5, or 8: Look at the next column
                              //       Else (`t` is 1, 4, or 7): Look at the current column
                ==8?          //       And 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

2

Python 2,130个字节

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

在线尝试!


如果从args中获取长度似乎更短
l4m2

2

Powershell,121字节

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

少打高尔夫的测试脚本:

$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"
}

输出:

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 : 

说明:

首先,脚本计算第一个字符串的长度。

其次,它为字符串增加了额外的边界。增强现实字符串喜欢:

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

表示多行字符串:

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

注1:的数量=足以容纳任何长度的字符串。

注2:大量的=不影响八字的搜索。

接下来,正则表达式将(?<=[^8]{3}.{$l}[^8])8(?=[^8].{$l}[^8]{3})查找8具有前面的非8 位数(?<=[^8]{3}.{$l}[^8])和以下的非8 位数的数字(?=[^8].{$l}[^8]{3})

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

最后,返回匹配数。


2

果冻,12字节

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

在线尝试!

怎么运行的

œẹ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.

1

JavaScript(ES6),106个字节

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

在线尝试!


按位方法,110字节

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

在线尝试!


按位方法失败[[7]]
l4m2

@ lm42哦,谢谢。现在已修复。
Arnauld

1

Clojure中227个 198字节

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

哎哟。无论如何绝对不是最短的。括号中的54个字节是杀手.。我还是比较满意的。

通过创建一个辅助函数来生成-29字节,该函数自两次执行以来就生成一个范围,将更reduce改为(count (filter设置,并在打高尔夫球后摆脱线程宏。

(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]

test-cases存放所有“ Python测试用例”的数组在哪里

在线尝试!

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.