Reputation: 131
You have a value n, it will determine the dimension of a 2D array or table. Then you should fill the array or the table from the outer layer to the center once with ones and once with zeros up to the point where there is no other element to write.
n=5
n=6
Have been trying this for a long time now, would appreciate any help. Am able to fill the boundaries nothing more.
My latest code :
function fillArray(n) {
var exArray = [];
var html = '';
for (var i = 0; i < n; i++) {
html+= '<tr>';
exArray[i] = [];
for (var j = 0; j < n; j++) {
exArray[i][j] = 0;
if(i%(n-1)==0 || j%(n-1)==0) {
exArray[i][j] = 1;
}
html+='<td class="text-center">'+exArray[i][j]+' ['+i+','+j+']</td>';
};
html+= '</tr>';
};
return html;
}
Upvotes: 4
Views: 328
Reputation: 288500
I think the simplest way is considering only the top-left quadrant, and fill the others by symmetry:
var arr = Array(n);
for(var i=0; i<n/2; ++i) {
arr[ i ] = new Array(n);
arr[n-1-i] = new Array(n);
for(var j=0; j<n/2; ++j)
arr[ i ][j] = arr[ i ][n-1-j] =
arr[n-1-i][j] = arr[n-1-i][n-1-j] =
+ !(Math.min(i,j) % 2);
}
function fillArray(n) {
var arr = Array(n);
for(var i=0; i<n/2; ++i) {
arr[ i ] = new Array(n);
arr[n-1-i] = new Array(n);
for(var j=0; j<n/2; ++j)
arr[ i ][j] = arr[ i ][n-1-j] =
arr[n-1-i][j] = arr[n-1-i][n-1-j] =
+ !(Math.min(i,j) % 2);
}
var table = document.createElement('table');
for(var i=0; i<n; ++i) {
var row = table.insertRow();
for(var j=0; j<n; ++j)
row.insertCell().textContent = arr[i][j];
}
return table;
}
document.body.appendChild(fillArray(9));
td {
width: .8em;
height: .8em;
line-height: .8em;
}
Upvotes: 5
Reputation: 4762
A more readable way
function fillArray(n) {
var exArray = [];
for (var i = 0; i < n; i++) {
exArray[i] = [];
for (var j = 0; j < n; j++) {
exArray[i][j] = 0;
if(i < j) {
if(n - j - 1 > i) {
if(i % 2 == 0) {
exArray[i][j] = 1;
}
}
else {
if((n - j - 1) % 2 == 0) {
exArray[i][j] = 1;
}
}
}
else {
if(j > n - i - 1) {
if((n - i - 1) % 2 == 0) {
exArray[i][j] = 1;
}
}
else {
if(j % 2 == 0) {
exArray[i][j] = 1;
}
}
}
};
};
}
And Fiddle.
Upvotes: 0
Reputation: 171690
Not as succinct but works:
var n = 10;
function isMiddleIndex(middleIdx, rowIndex, cellIndex) {
return middleIdx.indexOf(rowIndex) != -1 && middleIdx.indexOf(cellIndex) != -1;
}
function isBoundaryIndex(n, boundsIdx, i, j) {
return boundsIdx.indexOf(i) > -1 || boundsIdx.indexOf(j) > -1;
}
function fillArray(n) {
var num,
html = '',
nMid = n / 2,
middleIdx = n % 2 == 1 ? [(n - 1) / 2] : [Math.floor(nMid) - 1, Math.ceil(nMid)],
boundsIdx = [0, n - 1];
for (var i = 0; i < n; i++) {
html += '<tr>';
for (var j = 0; j < n; j++) {
num = isMiddleIndex(middleIdx, i, j) || isBoundaryIndex(n, boundsIdx, i, j) ? 1 : 0;
html += '<td class="text-center">' + num + '</td>';
};
html += '</tr>';
};
return html;
}
$('table').html(fillArray(n));
Upvotes: 0