How to check if the input matrix is symmetric? - javascript

The code below takes in a matrix (MAT) and transposes the matrix, calls it array. The definition of the symmetrical matrix is that it should be a square matrix and the elements in the given matrix compared to the transposed one should be the same.
The given matrix below and transposed matrix should output false if checked for symmetry.
I did create an if statement at first to check whether MAT[j][i] and array[j][i] are the same but keep getting the wrong answer. It's not properly checking all the elements together. Could someone help with that?
Thanks!
const symmetricMatrix = function (MAT) {
let array = [];
for (let i = 0; i < MAT.length; i++) {
array.push([]);
for (let j = 0; j < MAT.length; j++) {
array[i].push(MAT[j][i]);
}
}
return array;
};
console.log(
symmetricMatrix(
(MAT = [
[1, 3, 1],
[-1, 1, 4],
[2, 1, 0],
])
)
);

First you can create a copy of matrix and then transpose it and then check if it has same element at that index.
const symmetricMatrix = function (mat) {
const copy = Array.from(mat, (_) => []);
for (let i = 0; i < mat.length; i++)
for (let j = 0; j < mat.length; j++)
copy[i][j] = mat[j][i];
for (let i = 0; i < mat.length; i++)
for (let j = 0; j < mat.length; j++)
if (copy[i][j] != mat[i][j]) return false;
return true;
};
const matrix = [
[1, 3, 1],
[-1, 1, 4],
[2, 1, 0],
];
const matrix2 = [
[1, -1, 2],
[-1, 1, 1],
[2, 1, 0],
];
console.log(symmetricMatrix(matrix));
console.log(symmetricMatrix(matrix2));

Related

How to create nested array of different length from a multidimensional array

I have an array that looks like this:
arr = [[1,2,3],
[4,5,6],
[7,8,9]]
I have initialized an empty array and I want put the diagonals of the arr inside the new array. So i've tried this:
arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
new_arr = [];
tail = arr.length - 1;
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
if (j == i) {
new_arr.push(arr[i][j]);
}
if (j == tail) {
new_arr.push(arr[i][j]);
tail--;
}
}
}
console.log(new_arr)
The logic seems to work but I can't seem to get the structure right. What I want is to nest two arrays inside the new array like this:
[[1,5,9],[3,5,7]]
But what I get is one array with the right values unordered. How to get the expected output? Any help is appreciated. Thanks!
You need to have 2 separate temporary arrays. And you don't need nested loops. You can optimize the code like this with a single loop if you understand the math.
arr = [[1,2,3],
[4,5,6],
[7,8,9]];
function findDiagonals(arr) {
const diagonal_1 = [];
const diagonal_2 = [];
for( let i = 0; i < arr.length; i++ ) {
diagonal_1.push(arr[i][i]);
diagonal_2.push(arr[i][arr.length - (i+1)]);
}
return [diagonal_1, diagonal_2];
}
console.log(findDiagonals(arr));
var arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
var diagonal1 = [];
var diagonal2 = [];
for (var i = 0; i < arr.length; i++) {
diagonal1.push(arr[i][i]);
diagonal2.push(arr[i][arr.length - i - 1]);
}
var new_arr = [diagonal1, diagonal2];
console.log(new_arr)
The following solution would work for you if the width and height of the number matrix is always equal.
const arr = [[1,2,3],
[4,5,6],
[7,8,9]];
const result = [[],[]];
arr.map((row,index) => {
result[0].push(row[0+index]);
result[1].push(row[row.length - index - 1]);
});
console.log(result); // [[1,5,9],[3,5,7]]
This is a O(n) approach by using the function Array.prototype.reduce.
const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
const result = arr.reduce(([left, right], array, row, {length}) => {
return [[...left, array[row]], [...right, array[length - row - 1]]];
}, [[],[]]);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
the difficulty is low:
const
arr = [[1,2,3],[4,5,6],[7,8,9]]
, new_arr = [[],[]]
;
let p0 = 0, p1 = arr.length
for( let inArr of arr)
{
new_arr[0].push( inArr[p0++] )
new_arr[1].push( inArr[--p1] )
}
console.log( JSON.stringify( new_arr ))
in a one Line code:
const
arr = [[1,2,3],[4,5,6],[7,8,9]]
, new_arr = arr.reduce(([lft,rgt],A,i,{length:Sz})=>([[...lft,A[i]],[...rgt,A[Sz-i-1]]]),[[],[]])
;
console.log( JSON.stringify( new_arr )) // [[1,5,9],[3,5,7]]

How to get the position of element index of an array in an ascending order?

let a=[4, 3, 2, 2, 0, 1]
let b=[0, 1, 2, 2, 3, 4]; //My code demo below help to sort a into ascending order.
Output=[4, 5, 2, 3, 1, 0];
// Get the position of element index in a ascending order. For example, 0 is in index 4, 1 is in index 5, 2 is in index 2,2 is in index 3, and 4 is in index 0. Please Provide a demo. Thank you
var Arr = [4, 3, 2, 2, 0, 1];
for (var i = 1; i < Arr.length; i++) {
for (var j = 0; j < i; j++) {
if (Arr[i] < Arr[j]) {
var x = Arr[i];
Arr[i] = Arr[j];
Arr[j] = x;
}
}
}
console.log(Arr);
You could get the indices of the unsorted array and sort the indices by the values of the array.
const
array = [4, 3, 2, 2, 0, 1],
indices = [...array.keys()];
indices.sort((a, b) => array[a] - array[b]);
console.log(...indices);
you can use Object.entries :
let a=[4, 3, 2, 2, 0, 1]
let result = Object.entries(a).sort((a,b) => a[1]-b[1]).map(e => +e[0])
console.log(result)
i guess this is what you want
and also i change some other thing in code to be cleaner and readable
you can ask me anything if you want
function sortWithIndex (self) {
let Arr = [4, 3, 2, 2, 0, 1];
let result = [];
let ArrLength = Arr.length;
for (let i = 0; i < ArrLength; i++) {
number = Arr[i];
indexOfNumber = i;
result.push ('index ' + indexOfNumber + ' is ' + number);
};
return result
};
console.log(sortWithIndex());
Mostafa.T 🐍

For loops seems to run double than what is expected

I'm having issues with leetcode algo question 1252. I'm not sure why but my for loop seems to run twice. The question is:
"Given n and m which are the dimensions of a matrix initialized by zeros and given an array indices where indices[i] = [ri, ci]. For each pair of [ri, ci] you have to increment all cells in row ri and column ci by 1.
Return the number of cells with odd values in the matrix after applying the increment to all indices."
var oddCells = function(n, m, indices) {
let matrix = [];
let array = Array(m).fill(0);
let k = 0;
while (k < n) {
matrix.push(array);
k++;
}
for (let i = 0; i < indices.length; i++) {
const row = indices[i][0];
const col = indices[i][1];
for (let j = 0; j < n; j++) {
matrix[j][col]++;
}
for (let i = 0; i < m; i++) {
matrix[row][i]++;
}
}
return matrix.flat().filter(number => number % 2 !== 0).length;
}
console.log(oddCells(2, 3, [
[0, 1],
[1, 1]
]));
The specific input I am testing is n = 2, m = 3, indices = [[0,1],[1,1]].
I've tried to follow my code manually but I can't figure out why the two inner for loops are iterating over the nested arrays twice rather than each one once. After the first loop[ the matrix is supposed to be [[1, 2, 1], [0, 1, 0]] but instead I end up with [[1, 3, 1], [1, 3, 1]].
This is a basic problem of reusing mutable reference values.
You are repeatedly pushing the same array to the matrix, so when you modify any value in that array, you are modifying multiple areas of the matrix.
So use separate arrays:
var oddCells = function(n, m, indices) {
let matrix = [];
let k = 0;
while (k < n) {
matrix.push(Array(m).fill(0));
k++;
}
for (let i = 0; i < indices.length; i++) {
const row = indices[i][0];
const col = indices[i][1];
for (let ri = 0; ri < n; ri++) {
matrix[ri][col]++;
}
for (let ci = 0; ci < m; ci++) {
matrix[row][ci]++;
}
}
return matrix.flat().filter(number => number % 2 !== 0).length;
}
console.log(oddCells(2, 3, [
[0, 1],
[1, 1]
]));

How to get all substrings (contiguous subsequences) of my JavaScript array?

My task is to split the given array into smaller arrays using JavaScript. For example [1, 2, 3, 4] should be split to [1] [1, 2] [1, 2, 3] [1, 2, 3, 4] [2] [2, 3] [2, 3, 4] [3] [3, 4] [4].
I am using this code:
let arr = [1, 2, 3, 4];
for (let i = 1; i <= arr.length; i++) {
let a = [];
for (let j = 0; j < arr.length; j++) {
a.push(arr[j]);
if (a.length === i) {
break;
}
}
console.log(a);
}
And I get the following result: [1] [1, 2] [1, 2, 3] [1, 2, 3, 4] undefined
What am I missing/doing wrong?
For the inner array, you could just start with the index of the outer array.
var array = [1, 2, 3, 4],
i, j, l = array.length,
result = [];
for (i = 0; i < l; i++) {
for (j = i; j < l; j++) {
result.push(array.slice(i, j + 1));
}
}
console.log(result.map(a => a.join(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You have two issues in your code:
You need to have loop to initialize with the value of i for the inner loop so that it consider the next index for new iteration of i
You need to remove that break on the length which you have in inner loop.
let arr = [1, 2, 3, 4];
for (let i = 0; i <= arr.length; i++) {
let a = [];
for (let j = i; j < arr.length; j++) {
a.push(arr[j]);
console.log(a);
}
}
Try this
let arr = [1, 2, 3, 4];
for (let i = 0; i <= arr.length; i++) {
let a = [];
for (let j = i; j < arr.length; j++) {
a.push(arr[j]);
console.log(a);
}
}
If you don't want to mutate your array.
let arr = [1, 2, 3, 4];
let res = [];
for (let i = 0; i <= arr.length; i++) {
let a = [];
for (let j = i; j < arr.length; j++) {
a = [...a, arr[j]];
res = [...res, a];
}
}
console.log(res);
i have prepare stackblitz for this case.
let source = [1,2,3,4];
const output = [];
const arrayMultiplier = (source) => {
const eachValueArray = [];
source.forEach((item, index) => {
// Will push new array who will be sliced source array.
eachValueArray.push(source.slice(0, source.length - index));
});
//We reverse array to have right order.
return eachValueArray.reverse();
};
for(let i = 0; i <= source.length; i++) {
output.push(...arrayMultiplier(source));
source.shift(); // Will recraft source array by removing first index.
}
//Don't forget last item.
output.push(source);
console.log(output);
Is not the most shorten solution but do the job
== update after code review ==
// [...]
const arrayMultiplier = (source) => {
// Will push new array who will be sliced source array.
// We reverse array to have right order.
return source.map((item, index) => source.slice(0, source.length - index)).reverse();
};
// [...]
Use two iteration
get slice array based on loop index.
use sliced array and combine array element.
var arr = [1, 2, 3, 4];
let newArra =[];
arr.map((x,i)=> {
let remainArr = arr.slice(i);
return remainArr.forEach((y, r) => newArra.push(remainArr.slice(0, r+1)))
})
newArra.forEach(x=> console.log(x))

Create 2D array from 1D array using loop (JavaScript)

I have an array: [1, 2, 3, 4, 5, 6, 7, 8, 9]
I want to create a 2D array with three 1D arrays. Each NUM in the function variables is the length of each 1D array.
The result should be [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
But all I get is ,,3,,,6,,,9. What am I doing wrong?
function infiniteLoop(arr, num) {
var answer = [];
var count = 0;
for (let i = 0; i < num.length; i++) {
for (let j = 0; j < num[i]; j++, count++) {
answer[i] = [];
answer[i][j] = arr[count];
}
}
return answer;
}
document.write(infiniteLoop([1, 2, 3, 4, 5, 6, 7, 8, 9], [3, 3, 3]));
JavaScript doesn't have multidimensional arrays per se, what it has is arrays of arrays.
When you try to use answer[i][j] the answer[i] part of that is undefined because you haven't set it to anything yet - at that point answer is just an empty array. You need to set answer[i] = []; to set the first element of answer to be an empty array, and then you can use answer[i][j].
That will fit in your existing loop like this:
for (let i = 0; i < num.length; i++) {
answer[i] = []; // <--- add this
for (let j = 0; j < num[i]; j++, count++) {
answer[i][j] = arr[count];
}
}
Without testing it I believe you need to set answer[i] = [] before you loop your next array
answer[i] hasn't been created. You are trying to assign a value to something that doesn't exist. You need to create answer[i] like this:
answer[i] = new Array(num[i]);
So, the full code:
function infiniteLoop(arr, num) {
var answer = [];
var count = 0;
for (var i = 0; i < num.length; i++) {
answer[i] = new Array(num[i]);
for (var j = 0; j < num[i]; j++, count++) {
answer[i][j] = arr[count];
}
}
return answer;
}
document.write(infiniteLoop([1, 2, 3, 4, 5, 6, 7, 8, 9], [3, 3, 3]));
The problem is that answer[i] is undefined. The solution would be to add the following statement to the beginning of the first for loop:
answer[i] = [];
This should initialize answer[i] as an array, thus allowing you to set individual indices for it.

Categories

Resources