生成随机魔术方块

Art*_* Si -1 r matrix user-defined-functions magic-square

我想知道如何创建具有随机自然数但每列总和等于每行总和对角线总和的矩阵。

我的意思是,您创建了一个函数,该函数通过选择行,列和对角线的尺寸和总和为您提供一个如上所述的方阵,但是每行和每列的数字不同。

有人知道如何做到这一点吗?

我想自己创建一个没有任何程序包的功能,以完全理解该程序。

M--*_*M-- 5

您可以使用一个名为的包magic

library(magic)
magic(4)
Run Code Online (Sandbox Code Playgroud)

输出看起来像这样:

#      [,1] [,2] [,3] [,4] 
# [1,]    1   12    8   13 
# [2,]   15    6   10    3 
# [3,]   14    7   11    2 
# [4,]    4    9    5   16
Run Code Online (Sandbox Code Playgroud)

您无法确定矩阵的总和是多少。它将会成为:

在此处输入图片说明

其中“ n ”是矩阵的维数。

但是您可以将其乘以一个数字(最好是整数)。

有用的链接:什么是魔术广场?

如何看待功能?

如果您想弄清楚magic函数是如何工作的,可以使用它并逐步进行深入研究。

>functionBody(magic)

# { 
#     if (length(n) > 1) { 
#         return(sapply(n, match.fun(sys.call()[[1]]))) 
#     } 
#     n <- round(n) 
#     if (n == 2) { 
#         stop("Normal magic squares of order 2 do not exist") 
#     } 
#     if (n%%2 == 1) { 
#         return(as.standard(magic.2np1(floor(n/2)))) 
#     } 
#     if (n%%4 == 0) { 
#         return(as.standard(magic.4n(round(n/4)))) 
#     } 
#     if (n%%4 == 2) { 
#         return(as.standard(magic.4np2(round((n - 2)/4)))) 
#     } 
#     stop("This cannot happen") 
# }
Run Code Online (Sandbox Code Playgroud)

您需要研究上面显示的其他功能以完全理解该过程。