Hi guys I am doing a small exercise splitting a 16x16 matrix in 4x4 chunks, creating a sort of diagonal of small matrix. I am representing the 4x4 matrix with a value of 1 and the rest with a value of 0, painting them in the big matrix itself.
This what it should look like:
"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"
This is what I have achieved at me moment:
The red squares is what I am missing. These 4x4 matrix has to be "1" as well.
This is code (it is in javascript but I don't really care about the language).
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 "")));
Anyone know how to solve this problem? Thank You in advance!
CodePudding user response:
I've try something like that: it uses even/odd comparison to determine position for "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 "")));
CodePudding user response:
In Ruby:
require 'matrix'
m = Matrix.build(16, 16) { |i,j| (i/4).even? != (j/4).even? ? 0 : 1 }
To convert the matrix object to an array:
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]]
See Matrix::build and Enumerable#to_a.
This should translate easily to other languages that have a matrix library, but even if such a library is not available, the clause
(i/4).even? != (j/4).even? ? 0 : 1
shows how the array can be constructed in an economic way.