Count matrices with row sum and column sum == 4
Method: Iteration by composition
by rplantiko
HTML
Count the 6 x 6 matrices which have only 1 and 0 as coefficients, with the property that the number of one's in each row and in each column amounts to 4.
<div id="output">
<span id="browser-message">Code works only with a modern browser!</span>
</div>
Indeed, this is the seventh number of the OEIS sequence <a href="https://oeis.org/A001499">A001499</a>
CSS
body {
font-family:Lucida,Arial;
padding:1em;
}
#output {
margin:1em 0em;
font-weight:bold;
}
#matrix {
margin:1em 0em;
border-collapse:collapse;
}
#matrix td {
border:solid black 1px;
width:2em;
height:2em;
vertical-align:middle;
text-align:center;
}
#browser-message {
font-style:oblique;
color:orange;
}
JavaScript
(function(){
var output = document.getElementById("output")
var matrix = createMatrix()
var worker = delegateWorker(work, data=>{
if (data.finished) {
output.textContent = `Total count: ${data.count}`
} else {
output.textContent = `Current count: ${data.count}`
showMatrix(matrix,data.M)
}
})
function work() {
var M = new Array(6)
var cols = 0
var count = 0
r(r(r(r(r(r( ()=>{
if (count % 1500 == 0) {
postMessage({
count:count,
M:M
})
}
count++
}))))))()
postMessage({count:count,finished:true})
function r(f) {
var c = cols++
return function() {
for (let i = 1; i<6; i++) {
for (let j = 0; j < i; j++) {
M[c] = fillCol(i,j)
if (rowTracesValid(c)) f()
}
}
}
}
function fillCol(zero1,zero2) {
var col = new Array(6)
for (let k=0;k<6;k++) {
col[k] = (k == zero1 || k== zero2) ? 0 : 1
}
return col
}
function rowTracesValid(c) {
for (let i=0;i<6;i++) {
for (let j=5,ones=0;j>=c;j--) {
if ((ones += M[j][i]) > 4) return false
}
}
return true
}
}
function delegateWorker(workerFunction,onPostMessage) {
var worker =
new Worker( URL.createObjectURL(new Blob(
[`(${workerFunction})()`], {"type": "text/javascript"}
)));
worker.onmessage = e=>{
onPostMessage(e.data)
}
return worker
}
var flag = true
function showMatrix(matrix,M) {
M.forEach((row,i)=>row.forEach((value,j)=>{
matrix.rows[i].cells[j].textContent = value
}
))
}
function createMatrix() {
var matrix = document.createElement("table")
matrix.id = "matrix"
document.body.appendChild(matrix)
for (let i=0;i<6;i++) {
let row = document.createElement("tr")
matrix.appendChild(row)
for (let j=0;j<6;j++) {
row.appendChild(document.createElement("td"))
}
}
return matrix
}
})()