验证魔术广场


10

幻方是与侧N组成的不同的正整数1,2的编号的正方形阵列,...,ñ ²布置成使得所述的总和Ñ号码以任何水平,垂直,或主对角线行总是相同的数字,称为魔术常数。

您的程序必须通过std-in输入一个数字,该数字指定正方形的边长,然后指定正方形中的数字。没有号码可多次使用,没有数量大于ň可以使用²,和所有的数字必须大于0,程序必须确定数量的该组合是否是幻方。

Answers:


4

CJam,47 39 35 33 31字节

l~/{_1fb_,Y${\(_@=\}%:++\z}2*;=

像输入

4 [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]

1如果是幻方,0则输出,否则输出。

运作方式

l~/                               "Evaluates the input and split the array into chunks"
                                  "of size N where N is the first integer";
   {                      }2*     "Run this code block 2 times";
    _1fb                          "Copy the 2D array and calculate sum of each row of copy";
        _,                        "Copy the array containing sum of each row and get"
                                  "its length. This is equal to N";
          Y${      }%             "Run this code block for each array of the original"
                                  "2D array that we copied from stack";
             \(_                  "Put the length number to top of stack, decrement and"
                                  "copy that";
                @=\               "Take the element at that index from each row and put"
                                  "N back behind at second position in stack";
                     :+           "Take sum of elements of the array. This is sum of"
                                  "one of the diagonals of the 2D array";
                       +          "Push diagonal sum to row sum array";
                        \z        "Bring original array to top and transpose columns";
                             ;    "At this point, the stack contain 3 arrays:"
                                  "  Array with sum of rows and main diagonal,"
                                  "  Array with sum of columns and secondary diagonal and"
                                  "  The original array. Pop the original array";
                              =   "Check if sum of rows + main diagonal array is equal to ";
                                  "sum of columns + secondary diagonal array";

这可以打得更远。

在这里在线尝试


6

Python 2:132个字符

n,l=input()
r=range
print r(1,n*n+1)==sorted(l)*len({sum(l[i::j][:n])for(i,j)in zip(r(n)+r(0,n*n,n)+[0,n-1],[n]*n+[1]*n+[n+1,n-1])})

运行示例:

STDIN: 4,[16,3,2,13,5,10,11,8,9,6,7,12,4,15,14,1]
Output: True

有两件事要检查:

  1. 总和是行,列和对角线都相等
  2. 元素是 [1,2,...,n*n].

通过获取对应于这些子集的切片的总和来检查第一个。每行,每列或每条对角线均以其起始值和位移来描述。我们获取列表中对应的切片,将其截断n并求和。用Python的[start:end:step]表示法,行是[r*n::1],列是[c::n],两个对角线是[0::n+1][n-1::n-1]。这些存储2*n+2为由产生的对的列表zip

我们取总和集并检查它的长度是否为1。此外,我们对输入进行排序并检查它是否为列表。[1,2,...,n*n].实际上,我们乘以sorted(l)总和的长度将两者合并为一个校验,始终除非总和的长度为1,否则失败。


我意识到,你可以编码一对(i,j)更有效地为单号x,以i=x%Cj=x/C为一些足够大的C。可能以后再试一下。
xnor 2014年

5

APL,35

∧/2=/(+⌿x,⍉x),+/↑1 1∘⍉¨x(⌽x←⎕⍴⍨,⍨⎕)

解释
x←⎕⍴⍨,⍨⎕提示输入,将其成形为矩阵,然后分配给。x
从左到右反转矩阵
x(...)创建矩阵数组:xx反转
1 1∘⍉¨对于每个矩阵,将对角线
+/↑形成一个2×n的数字矩阵对角线和求和

⍉xx
x,然后与x进行转置以形成一个×2n矩阵
+⌿并对列求和

(+⌿x,⍉x),+/↑1 1∘⍉¨x(⌽x←⎕⍴⍨,⍨⎕)串联形成一个总和数组,
2=/检查连续对是否相等,
∧/并将所有结果相加


3

数学128 125

d = Diagonal; r = Reverse; i = Input[];
Length@Union[Tr /@ Join[p = Partition[i[[2]], i[[1]]], 
t = Transpose@p, {d@p}, {d@t}, {d@r@p}, {d@r@t}]] == 1

接受诸如

{4,{16, 3, 2, 13, 5, 10, 11, 8, 9, 6, 7, 12, 4, 15, 14, 1}}

真正


当然,这里可以删除很多空白
Beta Decay 2014年

所有空白都可以删除。我把它留在那里是为了提高可读性。而且我不算不必要的空格。
DavidC 2014年

您可以Input[r=Reverse]保存一个字节。#&@@[[1]]。短一个字节。您可能还可以在Partition另一个字节中使用中缀表示法。并且Thread应该代替Transpose。或者,将此Unicode字符用作后缀运算符(Mathematica将其用于上标T进行转置)。
Martin Ender 2014年

3

杀伤人员地雷47 32

使用TwiNight的出色解决方案并进行更多调整:

∧/2=/+⌿(1 1∘⍉∘⌽,1 1∘⍉,⍉,⊢)⎕⍴⍨,⍨⎕

说明:

这使用功能列,该功能列在Dyalog解释器的v14中引入。APL从右到左执行,,是输入,因此首先是维,然后是数字向量。

⍨⎕,⍨⎕创建矩阵NxN

之后是函数系列,基本上只是应用于正确参数的一系列函数(在方括号之间)。这些功能是:

⊢返回恰到好处的参数(即矩阵)

s转置正确的参数矩阵

11∘⍉返回对角线

11∘⍉∘⌽返回反转(水平)矩阵的对角线

所有结果都与函数“,”连接

此时,结果是一个矩阵,然后将其列求和(+ sum)。然后将以此方式获得的值与∧/ 2 = /检查是否相同。

我也将旧解决方案留在这里:

{M←⍺ ⍺⍴⍵⋄d←M=⍉M⋄(⊃≡∪)((+/,+⌿)M),+/∘,¨d(⌽d)ר⊂M}

将维作为左参数,将元素向量作为右参数,例如:

4{M←⍺ ⍺⍴⍵⋄d←M=⍉M⋄(⊃≡∪)((+/,+⌿)M),+/∘,¨d(⌽d)ר⊂M}16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1
1

可以在这里在线尝试:www.tryapl.org



2

JavaScript(E6)194

使用提示符读取输入并显示输出。
在控制台中使用FireFox> 31进行测试(Array.fill是非常新的)

z=(p=prompt)(n=p()|0).split(' '),u=Array(2*n).fill(e=d=n*(n*n+1)/2),z.map((v,i)=>(r=i/n|0,u[r+n]-=v,u[c=i%n]-=v,d-=v*(r==c),e-=v*(r+c+1==n))),o=!(e|d|u.some(v=>v)),z.sort((a,b)=>a-b||(o=0)),p(o)

少打高尔夫球

n = prompt()|0; // input side length
z = prompt().split(' '); // input list of space separeted numbers  
e = d = n*(n*n+1)/2; // Calc sum for each row, column and diagonal
u = Array(2*n).fill(e), // Init check values for n rows and n columns

z.map( (v,i) => { // loop on number array 
  r = i / n | 0; // row number
  c = i % n; // column number
  u[r+n] -= v; // subtract current value, if correct it will be 0 at loop end
  u[c] -= v; 
  if (r==c) d -= v; // subtract if diagonal \
  if (r+c+1==n) e -=v; // subtract if diagonal /
}),
o=!(e|d|u.some(v=>v)); // true if values for rows, cols and diags are 0
z.sort((a,b)=>a-b||(o=0)); // use sort to verify if there are repeated values in input
alert(o);

2

Pyth,24 30字节

&q1l{sM++JcEQCJm.e@bkd_BJqSlQS

在这里在线尝试。

&q1l{sM++JcEQCJm.e@bkd_BJqSlQSQ   Implicit: Q = evaluated 1st input (contents), E = evaluated 2nd input (side length)
                                  Trailing Q inferred
          cEQ                     Chop E into pieces or length Q
         J                        Store in J
                      _BJ         Pair J with itself with rows reversed
               m                  Map the original and it's reverse, as d, using:
                .e   d              Map each row in d, as b with index k, using:
                  @bk                 Get the kth element of b
                                  The result of this map is [[main diagonal], [antidiagonal]]
        +J                        Prepend rows from J
       +     CJ                   Prepend columns from J (transposed J)
     sM                           Sum each
    {                             Deduplicate
   l                              Length
 q1                               Is the above equal to 1?
&                                 Logic AND the above with...
                          SlQ     ... is the range [1-length(Q)]...
                         q        ... equal to...
                             SQ   ... sorted(Q)

编辑:修复了一个错误,感谢@KevinCruijssen让我知道:o)


这会输出True数字太大或不是唯一的幻方。即4[12,26,23,13,21,15,18,20,17,19,22,16,24,14,11,25]4[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]同时输出True。(尽管几乎所有现有的答案都存在相同的问题,但是由于它们是4年前发布的,因此我不愿在评论中更正他们的错误。)
Kevin Cruijssen

@KevinCruijssen该死,我非常专注于验证我忘记了其他要求的金额……我真是个傻子
Sok,

1

LUA 186字符

s=io.read(1)v=io.read(2)d=0 r=0 for i=1,#s do t=0 for j = 1, #s do t=t+s[i][j]end d=d+s[i][i] r=r+s[i][#s-i+1]if t ~= v then o=true end end if d~=v and r~= v then o=true end print(not o)

1

05AB1E,24 个字节

ô©O®øO®Å\O®Å/O)˜Ë²{¹nLQ*

输入格式:4\n[2,16,13,3,11,5,8,10,7,9,12,6,14,4,1,15]。输出1/ 0对truthy / falsey分别。

在线尝试验证更多测试用例

说明:

ô       # Split the 2nd (implicit) input into parts of a size of the 1st (implicit) input
        #  i.e. [2,16,13,3,11,5,8,10,7,9,12,6,14,4,1,15] and 4
        #   → [[2,16,13,3],[11,5,8,10],[7,9,12,6],[14,4,1,15]]
 ©      # Store it in the register (without popping)
  O     # Take the sum of each row
        #  i.e. [[2,16,13,3],[11,5,8,10],[7,9,12,6],[14,4,1,15]] → [34,34,34,34]
®       # Push the matrix from the register again
 ø      # Zip/transpose; swapping rows/columns
        #  i.e. [[2,16,13,3],[11,5,8,10],[7,9,12,6],[14,4,1,15]]
        #   → [[2,11,7,14],[16,5,9,4],[13,8,12,1],[3,10,6,15]]
  O     # Sum each inner list again
        #  i.e. [[2,11,7,14],[16,5,9,4],[13,8,12,1],[3,10,6,15]] → [34,34,34,34]
®       # Push the matrix from the register again
 Å\     # Get the top-left to bottom-right main diagonal of it
        #  i.e. [[2,16,13,3],[11,5,8,10],[7,9,12,6],[14,4,1,15]] → [2,5,12,15]
   O    # Sum it together
        #  i.e. [2,5,12,15] → 34
®       # Push the matrix from the register again
 Å/     # Get the top-right to bottom-left main diagonal of it
        #  i.e. [[2,16,13,3],[11,5,8,10],[7,9,12,6],[14,4,1,15]] → [3,8,9,14]
   O    # Sum it together
        #  i.e. [3,8,9,14] → 34
)       # Wrap everything on the stack into a list
        #  → [[34,34,34,34],[34,34,34,34],34,34]
 ˜      # Flatten this list
        #  i.e. [[34,34,34,34],[34,34,34,34],34,34] → [34,34,34,34,34,34,34,34,34,34]
  Ë     # Check if all values are equal to each other
        #  i.e. [34,34,34,34,34,34,34,34,34,34] → 1 (truthy)
²       # Push the second input again
 {      # Sort it
        #  i.e. [2,16,13,3,11,5,8,10,7,9,12,6,14,4,1,15]
        #  → [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
  ¹n    # Push the first input again, and take its square
        #  i.e. 4 → 16
    L   # Create a list in the range [1, squared_input]
        #  i.e. 16 → [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
     Q  # Check if the two lists are equal
        #  i.e. [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
        #   and [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] → 1 (truthy)
*       # Check if both checks are truthy by multiplying them with each other
        #  i.e. 1 and 1 → 1
        # (and output the result implicitly)
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.