在同一矩阵中将 16x16 矩阵拆分为 4x4

Split 16x16 matrix in 4x4 in the same matrix

大家好,我正在做一个小练习,将 16x16 矩阵分成 4x4 块,创建一种小矩阵的对角线。我用值为 1 的 4x4 矩阵表示,其余的值为 0,将它们绘制在大矩阵本身中。

这应该是这样的:

"1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0"
"1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0"
"1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0"
"1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0"
"0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1"
"0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1"
"0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1"
"0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1"
"1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0"
"1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0"
"1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0"
"1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0"
"0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1"
"0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1"
"0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1"
"0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1"

这是我目前取得的成就:

红色方块是我所缺少的。这些 4x4 矩阵也必须为“1”。

这是代码(它在 javascript 中,但我不太关心语言)。

let m = Array(16)
    .fill("0")
    .map(() => Array(16).fill("0"));

for (let i = 0; i < m.length; i++) {
    for (let j = 0; j < m.length; j++) {
        if (i % 8 < 4 && j % 8 < 4) {
            m[i][j] = "1";
        }
    }
}

m.map((a) => console.log(JSON.stringify(a + "")));

有人知道怎么解决这个问题吗?提前谢谢您!

我会尝试类似的方法:它使用 even/odd 比较来确定“1”的位置

let m = Array(16)
    .fill("")
    .map(() => Array(16).fill(""));

for (let i = 0; i < m.length; i++) {
    for (let j = 0; j < m.length; j++) {
        let mi = parseInt(i/4);
        let mj = parseInt(j/4);
        m[i][j] = ((mi&1) == (mj&1))?"1":"0";
    }
}

m.map((a) => console.log(JSON.stringify(a + "")));

在Ruby中:

require 'matrix'
m = Matrix.build(16, 16) { |i,j| (i/4).even? == (j/4).even? ? 1 : 0 }

要将矩阵对象转换为数组:

m.to_a
  #=> [[1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
  #    [1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
  #    [1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
  #    [1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
  #    [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
  #    [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
  #    [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
  #    [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
  #    [1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
  #    [1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
  #    [1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
  #    [1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
  #    [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
  #    [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
  #    [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
  #    [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]] 

Matrix::build and Enumerable#to_a

这应该很容易翻译成具有矩阵库的其他语言,但即使这样的库不可用,子句

(i/4).even? == (j/4).even? ? 1 : 0

展示了如何以经济的方式构建数组。



这是另一种不使用矩阵的方法。

a1 =  [1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0]
a2 = a1.reverse
  #=> [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]
Array.new(16) { |i| ((i/4).even? ? a1 : a2).dup }

参见 Array::new and Kernel#dup