Related
I'm trying to push to a two-dimensional array without it messing up, currently My array is:
var myArray = [
[1,1,1,1,1],
[1,1,1,1,1],
[1,1,1,1,1]
]
And my code I'm trying is:
var r = 3; //start from rows 3
var c = 5; //start from col 5
var rows = 8;
var cols = 7;
for (var i = r; i < rows; i++)
{
for (var j = c; j < cols; j++)
{
myArray[i][j].push(0);
}
}
That should result in the following:
var myArray = [
[1,1,1,1,1,0,0],
[1,1,1,1,1,0,0],
[1,1,1,1,1,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
]
But it doesn't and not sure whether this is the correct way to do it or not.
So the question is how would I accomplish this?
You have some errors in your code:
Use myArray[i].push( 0 ); to add a new column. Your code (myArray[i][j].push(0);) would work in a 3-dimensional array as it tries to add another element to an array at position [i][j].
You only expand (col-d)-many columns in all rows, even in those, which haven't been initialized yet and thus have no entries so far.
One correct, although kind of verbose version, would be the following:
var r = 3; //start from rows 3
var rows = 8;
var cols = 7;
// expand to have the correct amount or rows
for( var i=r; i<rows; i++ ) {
myArray.push( [] );
}
// expand all rows to have the correct amount of cols
for (var i = 0; i < rows; i++)
{
for (var j = myArray[i].length; j < cols; j++)
{
myArray[i].push(0);
}
}
In your case you can do that without using push at all:
var myArray = [
[1,1,1,1,1],
[1,1,1,1,1],
[1,1,1,1,1]
]
var newRows = 8;
var newCols = 7;
var item;
for (var i = 0; i < newRows; i++) {
item = myArray[i] || (myArray[i] = []);
for (var k = item.length; k < newCols; k++)
item[k] = 0;
}
You have to loop through all rows, and add the missing rows and columns. For the already existing rows, you loop from c to cols, for the new rows, first push an empty array to outer array, then loop from 0 to cols:
var r = 3; //start from rows 3
var c = 5; //start from col 5
var rows = 8;
var cols = 7;
for (var i = 0; i < rows; i++) {
var start;
if (i < r) {
start = c;
} else {
start = 0;
myArray.push([]);
}
for (var j = start; j < cols; j++) {
myArray[i].push(0);
}
}
Iterating over two dimensions means you'll need to check over two dimensions.
assuming you're starting with:
var myArray = [
[1,1,1,1,1],
[1,1,1,1,1],
[1,1,1,1,1]
]; //don't forget your semi-colons
You want to expand this two-dimensional array to become:
var myArray = [
[1,1,1,1,1,0,0],
[1,1,1,1,1,0,0],
[1,1,1,1,1,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
];
Which means you need to understand what the difference is.
Start with the outer array:
var myArray = [
[...],
[...],
[...]
];
If you want to make this array longer, you need to check that it's the correct length, and add more inner arrays to make up the difference:
var i,
rows,
myArray;
rows = 8;
myArray = [...]; //see first example above
for (i = 0; i < rows; i += 1) {
//check if the index exists in the outer array
if (!(i in myArray)) {
//if it doesn't exist, we need another array to fill
myArray.push([]);
}
}
The next step requires iterating over every column in every array, we'll build on the original code:
var i,
j,
row,
rows,
cols,
myArray;
rows = 8;
cols = 7; //adding columns in this time
myArray = [...]; //see first example above
for (i = 0; i < rows; i += 1) {
//check if the index exists in the outer array (row)
if (!(i in myArray)) {
//if it doesn't exist, we need another array to fill
myArray[i] = [];
}
row = myArray[i];
for (j = 0; j < cols; j += 1) {
//check if the index exists in the inner array (column)
if (!(i in row)) {
//if it doesn't exist, we need to fill it with `0`
row[j] = 0;
}
}
}
var r = 3; //start from rows 3
var c = 5; //start from col 5
var rows = 8;
var cols = 7;
for (var i = 0; i < rows; i++)
{
for (var j = 0; j < cols; j++)
{
if(j <= c && i <= r) {
myArray[i][j] = 1;
} else {
myArray[i][j] = 0;
}
}
}
you are calling the push() on an array element (int), where push() should be called on the array, also handling/filling the array this way makes no sense
you can do it like this
for (var i = 0; i < rows - 1; i++)
{
for (var j = c; j < cols; j++)
{
myArray[i].push(0);
}
}
for (var i = r; i < rows - 1; i++)
{
for (var j = 0; j < cols; j++)
{
col.push(0);
}
}
you can also combine the two loops using an if condition, if row < r, else if row >= r
Create am array and put inside the first, in this case i get data from JSON response
$.getJSON('/Tool/GetAllActiviesStatus/',
var dataFC = new Array();
function (data) {
for (var i = 0; i < data.Result.length; i++) {
var serie = new Array(data.Result[i].FUNCAO, data.Result[i].QT, true, true);
dataFC.push(serie);
});
The solution below uses a double loop to add data to the bottom of a 2x2 array in the Case 3. The inner loop pushes selected elements' values into a new row array. The outerloop then pushes the new row array to the bottom of an existing array (see Newbie: Add values to two-dimensional array with for loops, Google Apps Script).
In this example, I created a function that extracts a section from an existing array. The extracted section can be a row (full or partial), a column (full or partial), or a 2x2 section of the existing array. A new blank array (newArr) is filled by pushing the relevant section from the existing array (arr) into the new array.
function arraySection(arr, r1, c1, rLength, cLength) {
rowMax = arr.length;
if(isNaN(rowMax)){rowMax = 1};
colMax = arr[0].length;
if(isNaN(colMax)){colMax = 1};
var r2 = r1 + rLength - 1;
var c2 = c1 + cLength - 1;
if ((r1< 0 || r1 > r2 || r1 > rowMax || (r1 | 0) != r1) || (r2 < 0 ||
r2 > rowMax || (r2 | 0) != r2)|| (c1< 0 || c1 > c2 || c1 > colMax ||
(c1 | 0) != c1) ||(c2 < 0 || c2 > colMax || (c2 | 0) != c2)){
throw new Error(
'arraySection: invalid input')
return;
};
var newArr = [];
// Case 1: extracted section is a column array,
// all elements are in the same column
if (c1 == c2){
for (var i = r1; i <= r2; i++){
// Logger.log("arr[i][c1] for i = " + i);
// Logger.log(arr[i][c1]);
newArr.push([arr[i][c1]]);
};
};
// Case 2: extracted section is a row array,
// all elements are in the same row
if (r1 == r2 && c1 != c2){
for (var j = c1; j <= c2; j++){
newArr.push(arr[r1][j]);
};
};
// Case 3: extracted section is a 2x2 section
if (r1 != r2 && c1 != c2){
for (var i = r1; i <= r2; i++) {
rowi = [];
for (var j = c1; j <= c2; j++) {
rowi.push(arr[i][j]);
}
newArr.push(rowi)
};
};
return(newArr);
};
You can also try like this.
var r = 3; //start from rows 3
var c = 5; //start from col 5
var rows = 8;
var cols = 7;
for (var i = r; i < rows; i++)
{
for (var j = c; j < cols; j++)
{
myArray.push([var[i],var[j])
}
}
this will create a 2d array for you.
<script>
let test = new Array;
for(let i = 1; i < 10; i++){
test[i] = new Array;
test[i]['type'] = 'test-type'+i;
test[i]['content'] = 'test-content'+i;
}
console.log(test);
</script>
This is my code:
// Population
var Gene = function(text){
if(text){
this.text = text;
}
};
Gene.fitness = 0;
Gene.generation = 0;
var word = new Gene('Hello');
// This is where it crashes!!
// Make elements
var genArr = [];
var population = 20;
var mutation = 0;
for(var i = 0; i < population; i++){
var gene = "";
var abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var j = 0; i < word.text.length; j++) {
var element = abc.charAt(Math.floor(Math.random() * abc.length));
gene += element;
}
genArr.push(gene);
}
// Divide them - fitness
// 1/20 - 0.05% each
var fitElements = [];
for (var i = 0; i < genArr.length; i++) {
var score = 0;
var curWord = Array.from(genArr[i]);
for (var j = 0; j < word.text.length; j++) {
if(genArr[j].substr(j, 1) == word.text.substr(j, 1)){
score += 1;
}
}
if(score > 0){
fitElements.push([genArr[i], (score * (1 / population)) ** 2]);
}
}
for (var i = 0; i < fitElements.length; i++) {
console.log('Element: ' + fitElements[i][0] + ', Score: ' + fitElements[i][1]);
}
My problem is that it crashes the page but doesn't gives errors. The idea is to create a simple word register in fitElements Array but I can't see what am I missing?
Thanks in advance.
In your code the nested for loop with variable j's end condition relies on i.
Take a the line:
// VVVV it relies on i instead of j
for (var j = 0; i < word.text.length; j++) {
var element = abc.charAt(Math.floor(Math.random() * abc.length));
gene += element;
}
The new code would look something like
for (var j = 0; j < word.text.length; j++)
var element = abc.charAt(Math.floor(Math.random() * abc.length));
gene += element;
}
The only difference in the entire sample is the i is changed to a j. Cheers!
I'm playing around with online tests to improve my coding logic and I had a test where I needed to create a sample of a chessboard, where basically the input would be rows and columns of the chessboard, and then generate the output that was asked, but I'm not quite happy with my solution, I wonder if it is possible having the same output without having a temp variable, for example store the input values in a array and using some array functions that keeps looping inside giving me different values in the for loops. Here is my code:
/*
Sample output:
0101010
1010101
0101010
1010101
*/
function chess(m, n) { //7,4
var zero = 0;
var um = 1;
var temp = 0;
for (var i = 0; i < n; i++) {
for (var r = 0; r < m; r++) {
if (temp === 1) {
document.write(um);
temp = 0;
}
else {
document.write(zero);
temp = 1;
}
}
document.write("<br>");
}
}
chess(7, 4);
try
function chess(m,n){ //7,4
var zero = 0;
var um = 1;
var temp = 0;
for(var i = 0; i < n; i++){
for(var r = 0; r < m; r++){
if((i+r)%2 === 1){
document.write(um);
}else{
document.write(zero);
}
}
document.write("<br>");
}
}
chess(7,4);
You can directly compute and print. You do not need to store it in any variable.
function chess(m,n){ //7,4
for(var i = 0; i < n; i++){
for(var r = 0; r < m; r++){
document.write((i+r)%2);
}
document.write("<br>");
}
}
chess(7,4);
I want to create a multidimensional array like this:
array[0][1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
array[1][21,22,23,24,25,26,27....]
array[.][....]
How can I do this in Javascript?
I have tried this:
var squares = new Array();
for(var i = 1; i <= 8; i++)
{
for(var j = 1; j <= 20; j++)
{
squares.push(i, j);
}
}
How can I accomplish this?
You can do something like this:
var squares = new Array();
for(var i = 0; i <= 8; i++)
{
squares[i] = new Array();
for(var j = (i * 20) + 1; j <= 20 * i + 20; j++)
if (squares[i] == null)
squares[i] = j;
else
squares[i].push(j);
}
Output comes like:
array[0][1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
array[1][21,22,23,24,25,26,27....]
var array = []; // Main array
var numArrays = 10, // Number of sub-arrays
numPerArray = 20; // Number of squares per sub-array
for(var i = 0; i < numArrays; i++){
var subArray = [];
// Number to start at
var start = i * numPerArray;
// Count up to start + numPerArray
for(var j = start; j < start + numPerArray; j++){
subArray.push(j);
}
// Add to main array
array.push(subArray);
}
Use modulus operand to limit the inner array's size
var limit = 80
var inner_limit = 20
var square=[]
var inner =[]
for(var i=1;i<=limit;i++){
inner.push(i)
if(i%inner_limit==0){
square.push(inner)
inner = []
}
}
You can do it with two "for" loops. In the first loop you go through the main array and for each element add the elements from the second loop.
var arrayLength = 10; // Main array length
var limit = 20; // Number of squares
var array = [];
for ( var i = 0; i < arrayLength; i++ )
{
array[i] = []; // Create subArray
for( var j = 1; j <= limit; j++ )
{
array[i].push(j);
}
}
I'm trying to push to a two-dimensional array without it messing up, currently My array is:
var myArray = [
[1,1,1,1,1],
[1,1,1,1,1],
[1,1,1,1,1]
]
And my code I'm trying is:
var r = 3; //start from rows 3
var c = 5; //start from col 5
var rows = 8;
var cols = 7;
for (var i = r; i < rows; i++)
{
for (var j = c; j < cols; j++)
{
myArray[i][j].push(0);
}
}
That should result in the following:
var myArray = [
[1,1,1,1,1,0,0],
[1,1,1,1,1,0,0],
[1,1,1,1,1,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
]
But it doesn't and not sure whether this is the correct way to do it or not.
So the question is how would I accomplish this?
You have some errors in your code:
Use myArray[i].push( 0 ); to add a new column. Your code (myArray[i][j].push(0);) would work in a 3-dimensional array as it tries to add another element to an array at position [i][j].
You only expand (col-d)-many columns in all rows, even in those, which haven't been initialized yet and thus have no entries so far.
One correct, although kind of verbose version, would be the following:
var r = 3; //start from rows 3
var rows = 8;
var cols = 7;
// expand to have the correct amount or rows
for( var i=r; i<rows; i++ ) {
myArray.push( [] );
}
// expand all rows to have the correct amount of cols
for (var i = 0; i < rows; i++)
{
for (var j = myArray[i].length; j < cols; j++)
{
myArray[i].push(0);
}
}
In your case you can do that without using push at all:
var myArray = [
[1,1,1,1,1],
[1,1,1,1,1],
[1,1,1,1,1]
]
var newRows = 8;
var newCols = 7;
var item;
for (var i = 0; i < newRows; i++) {
item = myArray[i] || (myArray[i] = []);
for (var k = item.length; k < newCols; k++)
item[k] = 0;
}
You have to loop through all rows, and add the missing rows and columns. For the already existing rows, you loop from c to cols, for the new rows, first push an empty array to outer array, then loop from 0 to cols:
var r = 3; //start from rows 3
var c = 5; //start from col 5
var rows = 8;
var cols = 7;
for (var i = 0; i < rows; i++) {
var start;
if (i < r) {
start = c;
} else {
start = 0;
myArray.push([]);
}
for (var j = start; j < cols; j++) {
myArray[i].push(0);
}
}
Iterating over two dimensions means you'll need to check over two dimensions.
assuming you're starting with:
var myArray = [
[1,1,1,1,1],
[1,1,1,1,1],
[1,1,1,1,1]
]; //don't forget your semi-colons
You want to expand this two-dimensional array to become:
var myArray = [
[1,1,1,1,1,0,0],
[1,1,1,1,1,0,0],
[1,1,1,1,1,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
];
Which means you need to understand what the difference is.
Start with the outer array:
var myArray = [
[...],
[...],
[...]
];
If you want to make this array longer, you need to check that it's the correct length, and add more inner arrays to make up the difference:
var i,
rows,
myArray;
rows = 8;
myArray = [...]; //see first example above
for (i = 0; i < rows; i += 1) {
//check if the index exists in the outer array
if (!(i in myArray)) {
//if it doesn't exist, we need another array to fill
myArray.push([]);
}
}
The next step requires iterating over every column in every array, we'll build on the original code:
var i,
j,
row,
rows,
cols,
myArray;
rows = 8;
cols = 7; //adding columns in this time
myArray = [...]; //see first example above
for (i = 0; i < rows; i += 1) {
//check if the index exists in the outer array (row)
if (!(i in myArray)) {
//if it doesn't exist, we need another array to fill
myArray[i] = [];
}
row = myArray[i];
for (j = 0; j < cols; j += 1) {
//check if the index exists in the inner array (column)
if (!(i in row)) {
//if it doesn't exist, we need to fill it with `0`
row[j] = 0;
}
}
}
var r = 3; //start from rows 3
var c = 5; //start from col 5
var rows = 8;
var cols = 7;
for (var i = 0; i < rows; i++)
{
for (var j = 0; j < cols; j++)
{
if(j <= c && i <= r) {
myArray[i][j] = 1;
} else {
myArray[i][j] = 0;
}
}
}
you are calling the push() on an array element (int), where push() should be called on the array, also handling/filling the array this way makes no sense
you can do it like this
for (var i = 0; i < rows - 1; i++)
{
for (var j = c; j < cols; j++)
{
myArray[i].push(0);
}
}
for (var i = r; i < rows - 1; i++)
{
for (var j = 0; j < cols; j++)
{
col.push(0);
}
}
you can also combine the two loops using an if condition, if row < r, else if row >= r
Create am array and put inside the first, in this case i get data from JSON response
$.getJSON('/Tool/GetAllActiviesStatus/',
var dataFC = new Array();
function (data) {
for (var i = 0; i < data.Result.length; i++) {
var serie = new Array(data.Result[i].FUNCAO, data.Result[i].QT, true, true);
dataFC.push(serie);
});
The solution below uses a double loop to add data to the bottom of a 2x2 array in the Case 3. The inner loop pushes selected elements' values into a new row array. The outerloop then pushes the new row array to the bottom of an existing array (see Newbie: Add values to two-dimensional array with for loops, Google Apps Script).
In this example, I created a function that extracts a section from an existing array. The extracted section can be a row (full or partial), a column (full or partial), or a 2x2 section of the existing array. A new blank array (newArr) is filled by pushing the relevant section from the existing array (arr) into the new array.
function arraySection(arr, r1, c1, rLength, cLength) {
rowMax = arr.length;
if(isNaN(rowMax)){rowMax = 1};
colMax = arr[0].length;
if(isNaN(colMax)){colMax = 1};
var r2 = r1 + rLength - 1;
var c2 = c1 + cLength - 1;
if ((r1< 0 || r1 > r2 || r1 > rowMax || (r1 | 0) != r1) || (r2 < 0 ||
r2 > rowMax || (r2 | 0) != r2)|| (c1< 0 || c1 > c2 || c1 > colMax ||
(c1 | 0) != c1) ||(c2 < 0 || c2 > colMax || (c2 | 0) != c2)){
throw new Error(
'arraySection: invalid input')
return;
};
var newArr = [];
// Case 1: extracted section is a column array,
// all elements are in the same column
if (c1 == c2){
for (var i = r1; i <= r2; i++){
// Logger.log("arr[i][c1] for i = " + i);
// Logger.log(arr[i][c1]);
newArr.push([arr[i][c1]]);
};
};
// Case 2: extracted section is a row array,
// all elements are in the same row
if (r1 == r2 && c1 != c2){
for (var j = c1; j <= c2; j++){
newArr.push(arr[r1][j]);
};
};
// Case 3: extracted section is a 2x2 section
if (r1 != r2 && c1 != c2){
for (var i = r1; i <= r2; i++) {
rowi = [];
for (var j = c1; j <= c2; j++) {
rowi.push(arr[i][j]);
}
newArr.push(rowi)
};
};
return(newArr);
};
You can also try like this.
var r = 3; //start from rows 3
var c = 5; //start from col 5
var rows = 8;
var cols = 7;
for (var i = r; i < rows; i++)
{
for (var j = c; j < cols; j++)
{
myArray.push([var[i],var[j])
}
}
this will create a 2d array for you.
<script>
let test = new Array;
for(let i = 1; i < 10; i++){
test[i] = new Array;
test[i]['type'] = 'test-type'+i;
test[i]['content'] = 'test-content'+i;
}
console.log(test);
</script>