How do I traverse an array diagonally in javascript [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have an array with strings that I would like to traverse diagonally.
Assumptions:
Each string is the same length.
Arrays could be square or rectangular, horizontally or vertically.
The matrix looks like this:
A B C D
E F G H
I J K L
I Would like to get (from top left to bottom right):
A
EB
IFC
JGD
KH
L
and (from the bottom left to top right):
I
JE
KFA
LGB
HC
D
I already have a piece of code that works 3/4 of the way, but i cant seem to figure out what I am doing (wrong).
//the array
var TheArray = ['ABCD','EFGH','IJKL'];
//amount of rows
var RowLength = TheArray.length;
//amount of colums
var ColumnLength = TheArray[0].length;
The code I have chops up the diagonals into 4 of these loops to get all the diagonals. It looks as 2 for loops with an if to not loop over unbound values. The pseudo code looks a bit like this:
for(loop rows){
var outputarray = [];
for(loop columns){
if(delimit for out of bound){
var temprow = TheArray[something?];
var tempvalue = temprow[something?];
outputarray.push(tempvalue);
}
}
//use values
document.getElementById("theDiv").innerHTML += outputarray.join("")+"<br>";
}
I hope somebody can help me with this.

From top left to bottom right
var theArray = ["ABCD","EFGH","IJKL"];
var length = { "x" : theArray[0].length, "y" : theArray.length };
length.max = Math.max(length.x, length.y);
var temp, k, x, y;
for (k = 0; k <= 2 * (length.max - 1); ++k) {
for (temp = [], y = length.y - 1; (x = k - y), y >= 0; --y) {
x >= 0 && x < length.x && temp.push(theArray[y][x]);
}
temp.length > 0 && (document.body.innerHTML += temp.join('') + '<br>');
}
(see also this Fiddle)
From the bottom left to top right
var theArray = ["ABCD","EFGH","IJKL"];
var length = { "x" : theArray[0].length, "y" : theArray.length };
length.max = Math.max(length.x, length.y);
var temp, k, x, y;
for (k = 0; k <= 2 * (length.max - 1); ++k) {
for (temp = [], y = length.y - 1; (x = k + y - length.y), y >= 0; --y) {
x >= 0 && x < length.x && temp.push(theArray[y][x]);
}
temp.length > 0 && (document.body.innerHTML += temp.join('') + '<br>');
}
(see also this Fiddle)
Combined
As there's but a single line of difference between both, you can easily combine them in a single function :
var theArray = ["ABCD","EFGH","IJKL"];
function diagonal(data, fromBottom) {
var length = { "x" : data[0].length, "y" : data.length };
length.max = Math.max(length.x, length.y);
var temp, k, x, y;
var returnMe = [];
for (k = 0; k <= 2 * (length.max - 1); ++k) {
for (temp = [], y = length.y - 1; y >= 0; --y) {
x = k - (fromBottom ? length.y - y : y);
x >= 0 && x < length.x && temp.push(data[y][x]);
}
temp.length > 0 && returnMe.push(temp.join(''));
}
return returnMe;
}
document.body.innerHTML = diagonal(theArray).join('<br>') +
'<br><br><br>' +
diagonal(theArray, true).join('<br>');
(see also this Fiddle)

This does the trick, and outputs the desired results to the screen:
var array = ['ABCD','EFGH','IJKL'];
var rows = array.length;
var cols = array[0].length;
for (var n = 0; n < cols + rows - 1; n += 1)
{
var r = n;
var c = 0;
var str = '';
while (r >= 0 && c < cols)
{
if (r < rows)
str += array[r][c];
r -= 1;
c += 1;
}
document.write(str+"<br>");
}
Result:
A
EB
IFC
JGD
KH
L

Yet another solution:
function getAllDiagonal(array) {
function row(offset) {
var i = array.length, a = '';
while (i--) {
a += array[i][j + (offset ? offset - i : i)] || '';
}
return a;
}
var result = [[], []], j;
for (j = 1 - array.length; j < array[0].length; j++) {
result[0].push(row(0));
result[1].push(row(array.length - 1));
}
return result;
}
var array = ['ABCD', 'EFGH', 'IJKL'];
document.write('<pre>' + JSON.stringify(getAllDiagonal(array), 0, 4) + '</pre>');

Use indices:
[i][j-i]
Where i goes from 0 to M-1
j goes from 0 to i
While j++ < N
for the matrix
type Array[M][N]
However this may miss a few at the bottom right if the matrix is rectangular, and you might need a second nested for loop with i and j to capture those.

Try this
var TheArray = ['ABCD', 'EFGH', 'IJKL'];
//amount of rows
var RowLength = TheArray.length;
//amount of colums
var ColumnLength = TheArray[0].length;
var totalNoComb = RowLength + ColumnLength - 1;
var combArr = new Array(totalNoComb);
for (var i = 0; i < totalNoComb; i++) {
combArr[i] = "";
for (var j = RowLength-1; j >-1; j--) {
if (i - j > -1 && i - j < ColumnLength)
combArr[i] += TheArray[j][i-j];
}
}
alert(combArr);
for (var i = 0; i < totalNoComb; i++) {
combArr[i] = "";
for (var j = 0; j < RowLength; j++) {
if (i - j > -1 && i - j < ColumnLength)
combArr[i] += TheArray[ RowLength -1-j][i - j];
}
}
alert(combArr);

This should work even for rectangular matrices:
var array = ["ABCD", "EFGH", "IJKL"];
var arrOfArr = [];
var resultArray = [];
for (var i = 0; i < array.length; ++i) {
arrOfArr.push(array[i].split(''));
}
var rows = arrOfArr.length;
var columns = arrOfArr[0].length;
var index = 0;
for (var i = 0; i < rows; ++i) {
var k = 0;
resultArray[index] = new Array();
for (var j = i; j >= 0; --j) {
resultArray[index].push(arrOfArr[j][k]);
++k;
if ( k === columns) {
break;
}
}
resultArray[index] = resultArray[index].join('');
++index;
}
for (var j = 1; j < columns; ++j) {
var k = rows - 1;
resultArray[index] = new Array();
for (var i = j; i < columns; ++i) {
resultArray[index].push(arrOfArr[k][i]);
--k;
if ( k === -1) {
break;
}
}
resultArray[index] = resultArray[index].join('');
++index;
}
console.log(JSON.stringify(resultArray));

Note: This assumes that all strings are the same size, or at least are as large as the first string.
In a 2D array (or in this case, an array of strings), a diagonal's indexes add up to the diagonal's number (like a row-number). 00, 01 10, 02 11 20, etc.
Using this method, the number of diagonal "rows" (starting at zero) is equal to the sum of the largest indexes, or the sum of (columnlength+rowlength-2).
Therefore, my solution is to iterate through the diagonal row numbers and print all index pairs whose sum is equal to the current diagonal row.
var TheArray = ["ABCD","EFGH","IJKL"];
//amount of rows
var RowLength = TheArray.length;
//amount of colums
var ColumnLength = TheArray[0].length;
var text = ''
for (i = 0; i <= (RowLength+ColumnLength-2); i++){
for (x = 0; x<=i; x++){
if (TheArray[i-x] && TheArray[i-x][x]){
text += TheArray[i-x][x];
}
}
text += "<br/>";
}
document.getElementById('text').innerHTML = text;
JSFiddle Link

Here is my try for 'from top left to bottom right':
for (i=0; i<nbRows; i++) {
x = 0; y = i;
while (x < nbColumns && y >= 0) {
print(array[x, y]);
x++; y--;
}
print("\n");
}
for (i=1; i<nbColumns; i++) {
x = i; y = nbRows - 1;
while (x < nbColumns && y >=0) {
print(array[x, y]);
x++; y--;
}
}
Needs a few adaptations to fit JavaScript syntax.

Full solution for both diagonals:
var TheArray = ['ABCD', 'EFGH', 'IJKL'];
var RowLength = TheArray.length;
var ColumnLength = TheArray[0].length;
// Diagonals
var diagonal = [[], []];
for (var i = 0; i < Math.min(RowLength, ColumnLength); i++) {
diagonal[0].push({'row': 0-i, 'col': i});
diagonal[1].push({'row': 0-i, 'col': 0-i});
}
// Entry points
// 1///
// 2///
// 3456
var points = [[], []];
for (var y = 0; y < RowLength; y++) {
points[0].push({'row': y, 'col': 0});
}
for (var x = 1; x < ColumnLength; x++) {
points[0].push({'row': RowLength - 1, 'col': x});
}
// Entry points
// \\\6
// \\\5
// 1234
for (var x = 0; x < ColumnLength; x++) {
points[1].push({'row': RowLength - 1, 'col': x});
}
for (var y = RowLength - 2; y >= 0; y--) {
points[1].push({'row': y, 'col': ColumnLength - 1});
}
var strings = [[], []];
for (var line = 0; line < diagonal.length; line++) {
for (var point = 0; point < points[line].length; point++) {
var inside = true;
var index = 0;
var string = '';
while (inside && index < diagonal[line].length) {
var row = points[line][point]['row'] + diagonal[line][index]['row'];
var col = points[line][point]['col'] + diagonal[line][index]['col'];
if (row >= 0 && row < RowLength && col >= 0 && col < ColumnLength) {
string += TheArray[row][col];
index++;
} else {
inside = false;
}
}
strings[line].push(string);
}
}
console.log(strings);

Related

Struggling with while loop in this algorithm

I am writing a program to calculate euclidean distance and then display the lines based, with the below code:
function discreteFrechet(X, Y) {
var M = X.length;
var N = Y.length;
var S = [
[],
[]
];
var backpointers = [
[],
[]
];
var backpaths = [];
var idx;
var path = [];
var paths;
var back = [
[],
[]
];
for (i = 0; i < M; i++) {
for (j = 0; j < N; j++) {
S[i][j] = 0;
backpointers[i][j] = 0;
}
} /* populates S array */
/*sanity check*/
S[0, 0] = euclidian(X, Y, 0, 0);
opt1 = [-1, 0];
opt2 = [0, -1];
opt3 = [-1, -1];
backpaths.push(opt1);
backpaths.push(opt2);
backpaths.push(opt3);
/*backpaths populated*/
for (i = 0; i < M; i++) {
for (j = 0; j < N; j++) {
options = [];
if (i != 0 || j != 0) {
if (i > 0) {
options[0] = S[i - 1, j];
}
if (j > 0) {
options[1] = S[i - 1, j];
}
if (i > 0 && j > 0) {
options[2] = S[i - 1, j];
}
idx = Math.min(options);
backpointers[i][j] = idx;
S[i][j] = Math.max(options[idx], euclidian(X, Y, i, j));
}
}
}
console.log(S);
paths = [
[M - 1, N - 1]
];
path = [
[],
[]
];
path.push(paths);
//Create "path"
i = M - 1;
j = N - 1;
count = 0;
while ((path[path.length - 1][0] != 0) || (path[0][path[1].length - 1] != 0)) {
back[0][1] = backpaths[backpointers[i], [j]];
i += back[0];
j += back[1];
path.push([i, j]);
if (count > 1000) {
console.log("too many loops");
break;
}
count += 1;
}
path.push([0, 0]);
path.reverse();
//returns bottleneck and the path
}
As I am testing, I am running into a problem with an infinite while loop (hence the break statement) any help or suggestions would be greatly appreciated! The goal is to append indicies into the path element, such that I can then take those path indicies and the bottleneck and use them to plot with d3.

Push value in multi dimensional object array - Typescript [duplicate]

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>

Why do I get an Uncaught TypeError: property 4 is undefined when looping through a 2d array?

So I am building Tetris. After creating an array, data, I am trying to implement gravity by checking
every string in an array if it's is "full" as well as being able the space below it being empty. However, it is giving me an error that suggests that something is undefined. The I tried a for loop and a for...of loop, as well as Googling it.Why do I get this error, and how can I fix it?
const editor = document.getElementById("edit");
var data = [];
function array(x, text) {
var y = [];
for (var i = 0; i < x - 1; i++) {
y.push(text);
}
return y;
}
for (var i = 0; i < 20; i++) {
data.push(array(10, "b"));
}
function draw() {
var j;
var i;
var dataOut = data;
for (i = 0; i < data.length; i++) {
for (j = 0; j < data[i].length; j++) {
if (data[i][j] == "a" && data[i + 1][j] == "b") {
if (i < data.length - 1) {
dataOut[i][j] = "b";
dataOut[i + 1][j] = "a";
}
}
}
}
data = dataOut;
console.log(data);
requestAnimationFrame(draw);
}
data[0][4] = "a";
requestAnimationFrame(draw);
with for-of-loop you iterate only objects/values of array and not indexes.
use only for-loop in order to use indexes
const editor = document.getElementById("edit");
var data = [];
function array(x, text) {
var y = [];
for (var i = 0; i < x - 1; i++) {
y.push(text);
}
return y;
}
for (var i = 0; i < 20; i++) {
data.push(array(10, "b"));
}
function draw() {
var dataOut = data;
for (let i = 0; i < data.length - 1; i++) { // logical error here
for (let j = 0; j < data.length; j++) {
if (data[i][j] == "a" && data[i + 1][j] == "b") {
if (i < data.length - 1) {
dataOut[i][j] = "b";
dataOut[i + 1][j] = "a";
}
}
}
}
data = dataOut;
console.log(data);
requestAnimationFrame(draw);
}
data[0][4] = "a";
requestAnimationFrame(draw);
A simple example of for-of-loop
const arr = ["aa","bb"]
for(let a of arr) console.log(a);
// will print
/*
aa
bb
*/
for(let a = 0; a < arr.length; a++) console.log(a);
// will print
/*
0
1
*/

How to program Pascal's Triangle in Javascript - confusion re Arrays

I'm having a little trouble with my attempt at this problem. Code Below:
function pasc(n){
var result = [[1]];
for (var row = 1; row < n; row++){
for (var col = 1; col <= row; col++){
result[row][col] = result[row - 1][col] + result[row - 1][col - 1];
}
}
return result;
}
pasc(10)
for (var i = 0; i < result.length; i++){
document.write(result[i]+"<br>");
}
It seems the problem hinges on assigning values to an array using an expression like myArray[1][1] = "foo"
I'm confused about this because I can do this: var myArray = []; myArray[4] = "foo" which seems to suggest that an element can be created at an arbitrary position in a 1 dimensional array, but not with 2 dimensions.
Any help with clearing up my misconceptions appreciated.
The Pascal's Triangle can be printed using recursion
Below is the code snippet that works recursively.
We have a recursive function pascalRecursive(n, a) that works up till the number of rows are printed. Each row is a element of the 2-D array ('a' in this case)
var numRows = 10,
triangle,
start,
stop;
// N is the no. of rows/tiers
// a is the 2-D array consisting of the row content
function pascalRecursive(n, a) {
if (n < 2) return a;
var prevRow = a[a.length-1];
var curRow = [1];
for (var i = 1; i < prevRow.length; i++) {
curRow[i] = prevRow[i] + prevRow[i-1];
}
curRow.push(1);
a.push(curRow);
return pascalRecursive(n-1, a); // Call the function recursively
}
var triangle = pascalRecursive(numRows, [[1]]);
for(var i = 0; i < triangle.length; i++)
console.log(triangle[i]+"\n");
JavaScript doesn't have two-dimensional arrays. What it does have is arrays that happen to contain other arrays. So, yes, you can assign a value to any arbitrary position in an array, and the array will magically make itself big enough, filling in any gaps with 'undefined'... but you can't assign a value to any position in a sub-array that you haven't explicitly created yet. You have to assign sub-arrays to the positions of the first array before you can assign values to the positions of the sub-arrays.
Replacing
for (var row = 1; row < n; row++){
for (var col = 1; col <= row; col++){
with
for (var row = 1; row < n; row++){
result[row] = [];
for (var col = 1; col <= row; col++){
should do it. Assuming all of your indexing logic is correct, anyway. You've got some problems there, too, since your initial array only contains a single value, so result[row][col] = result[row - 1][col] + result[row - 1][col - 1]; is accessing at least one cell that has never been defined.
Thanks Logan R. Kearsley. I have now solved it:
function pasc(n){
var result = [];
result[0] = [1];
result[1] = [1,1];
for (var row = 2; row < n; row++){
result[row] = [1];
for (var col = 1; col <= row -1; col++){
result[row][col] = result[row-1][col] + result[row-1][col-1];
result[row].push(1);
}
}
return result;
}
for (var i = 0; i < pasc(10).length; i++){
document.write(pasc(10)[i]+"<br>");
console.log(pasc(10)[i]+"<br>");
}
you can create Pascal's triangle using below code:
function pascal(n) {
var arr = [];
if (n == 1) {
arr[0] = [];
arr[0][0] = 1;
} else if (n == 2) {
arr[0] = [];
arr[0][0] = 1;
arr[1] = [];
arr[1][0] = 1;
arr[1][1] = 1;
} else if (n > 2) {
arr[0] = [];
arr[1] = [];
arr[0][0] = 1;
arr[1][0] = 1;
arr[1][1] = 1;
for (i = 2; i < n; i++) {
arr[i] = [];
arr[i][0] = 1;
for (j = 1; j < i; j++) {
arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];
}
arr[i][j] = 1;
}
}
console.log(arr);
for (i = 0; i < arr.length; i++) {
console.log(arr[i].join(' '))
}
}
function pascal(n) {
var arr = [];
if (n == 1) {
arr[0] = [];
arr[0][0] = 1;
} else if (n == 2) {
arr[0] = [];
arr[0][0] = 1;
arr[1] = [];
arr[1][0] = 1;
arr[1][1] = 1;
} else if (n > 2) {
arr[0] = [];
arr[1] = [];
arr[0][0] = 1;
arr[1][0] = 1;
arr[1][1] = 1;
for (i = 2; i < n; i++) {
arr[i] = [];
arr[i][0] = 1;
for (j = 1; j < i; j++) {
arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];
}
arr[i][j] = 1;
}
}
console.log(arr);
for (i = 0; i < arr.length; i++) {
console.log(arr[i].join(' '))
}
}
pascal(5)
This function will calculate Pascal's Triangle for "n" number of rows. It will create an object that holds "n" number of arrays, which are created as needed in the second/inner for loop.
function getPascalsTriangle(n) {
var arr = {};
for(var row = 0; row < n; row++) {
arr[row] = [];
for(var col = 0; col < row+1; col++) {
if(col === 0 || col === row) {
arr[row][col] = 1;
} else {
arr[row][col] = arr[row-1][col-1] + arr[row-1][col];
}
}
}
return arr;
}
console.log(getPascalsTriangle(5));
Floyd triangle
You can try the following code for a Floyd triangle
var prevNumber=1,i,depth=10;
for(i=0;i<depth;i++){
tempStr = "";j=0;
while(j<= i){
tempStr = tempStr + " " + prevNumber;
j++;
prevNumber++;
}
console.log(tempStr);
}
You can create arbitrary 2d arrays and store it in there and return the correct Pascal.
JavaScript does not have a special syntax for creating multidimensional arrays. A common workaround is to create an array of arrays in nested loops.
source
Here is my version of the solution
function pascal(input) {
var result = [[1], [1,1]];
if (input < 0) {
return [];
}
if (input === 0) {
return result[0];
}
for(var j = result.length-1; j < input; j++) {
var newArray = [];
var firstItem = result[j][0];
var lastItem = result[j][result[j].length -1];
newArray.push(firstItem);
for (var i =1; i <= j; i++) {
console.log(result[j][i-1], result[j][i]);
newArray.push(sum(result[j][i-1], result[j][i]));
}
newArray.push(lastItem);
result.push(newArray);
}
return result[input];
}
function sum(one, two) {
return one + two;
}
Here is the code i created for pascal triangle in javascript
'use strict'
let noOfCoinFlipped = 5
let probabiltyOfnoOfHead = 2
var dataStorer = [];
for(let i=0;i<=noOfCoinFlipped;i++){
dataStorer[i]=[];
for(let j=0;j<=i;j++){
if(i==0){
dataStorer[i][j] = 1;
}
else{
let param1 = (j==0)?0:dataStorer[i-1][j-1];
let param2 = dataStorer[i-1][j]?dataStorer[i-1][j]:0;
dataStorer[i][j] = param1+param2;
}
}
}
let totalPoints = dataStorer[noOfCoinFlipped].reduce((s,n)=>{return s+n;})
let successPoints = dataStorer[noOfCoinFlipped][probabiltyOfnoOfHead];
console.log(successPoints*100/totalPoints)
Here is the link as well
http://rextester.com/TZX59990
This is my solve:
function pascalTri(n){
let arr=[];
let c=0;
for(let i=1;i<=n;i++){
arr.push(1);
let len=arr.length;
if(i>1){
if(i>2){
for(let j=1;j<=(i-2);j++){
let idx=(len-(2*i)+j+2+c);
let val=arr[idx]+arr[idx+1];
arr.push(val);
}
c++;
}
arr.push(1);
}
}
return arr;
}
let pascalArr=pascalTri(7);
console.log(pascalArr);
here is the pattern for n = 3
#
##
###
here is js code to print this.
function staircase(n) {
for(var i=0 ; i<n ; i++) {
for(var j=n-1 ; j>i ; j--)
process.stdout.write(" ");
for(var k=0 ; k<=i; k++) {
process.stdout.write("#");
}
process.stdout.write("\n");
}
}
class PascalTriangle {
constructor(n) {
this.n = n;
}
factoriel(m) {
let result = 1;
if (m === 0) {
return 1;
}
while (m > 0) {
result *= m;
m--;
}
return result;
}
fill() {
let arr = [];
for (let i = 0; i < this.n; i++) {
arr.push([]);
}
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j <= i; j++) {
arr[i].push(this.factoriel(i) / (this.factoriel(j) * this.factoriel(i - j)));
}
}
return arr;
}
}
var m = prompt("enter number:");
var arrMain = new Array();
for (var i = 0; i < m; i++) {
arrMain[i] = [];
}
for (var i = 0; i < m; i++) {
if (i == 0) {
arrMain[i] = [1];
} else if (i == 1) {
(arrMain[i]) = [1, 1];
} else {
for (var j = 0; j <= i; j++) {
if (j == 0 || j == arrMain[i - 1].length) {
arrMain[i][j] = 1;
} else {
arrMain[i][j] = arrMain[i - 1][j] + arrMain[i - 1][j - 1];
}
}
}
document.write(arrMain[i] + "<br>");
}
This is my take on this problem by gaining access to the previous row.
const generate = numRows => {
const triangle = [[1]]
for (let i = 1; i < numRows; i++) {
// Previous row
const previous = triangle[i - 1]
// Current row
const current = new Array(i + 1).fill(1)
// Populate the current row with the previous
// row's values
for (let j = 1; j < i; j++) {
current[j] = previous[j - 1] + previous[j]
}
// Add to triangle result
triangle.push(current)
}
return triangle
}

push() a two-dimensional array

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>

Categories

Resources