I need to do a simple diagonal matrix in JS, which should look like this one:
[
[4, 7, 9],
[2, 5, 8],
[1, 3, 6]
]
My idea is to use a 2-d array and two loops, but the result I get is an empty array.You'll see below what my code looks like, but obviously I have a problem with the values.
function fillMatrix(n) {
var matrix = [];
var rows = 0;
var cols = 0;
var startCount = 1;
for (var i = (n - 1); i >= 0; i--) {
rows = i;
cols = 0;
matrix[rows] = [];
while (rows < n && cols < n) {
matrix[rows++][cols++] = startCount++;
}
for (var j = 0; j < n; j++) {
rows = j;
cols = 0;
matrix[rows] = [];
while (rows < n && cols < n) {
matrix[cols++][cols++] = startCount++;
}
}
}
return matrix;
}
n = +prompt();
console.log(fillMatrix(n));
The logic for creating a diagonal matrix can be greatly simplified if one looks at the patterns between rows. (I won't go through all of the math here, but feel free to ask me questions in the comments about any specific sections you find confusing.)
Take, for example, the 4x4 diagonal matrix:
Successive differences between elements in a row form the pattern below:
I might still work on shortening the method below, but right now it works and is fairly concise.
Demo:
function diagonalMatrix (n) {
var matrix = [], row
for (var i = n; i > 0; i--) {
var x = i*(i-1)/2 + 1, dx = i
matrix.push(row = [])
for (var j = n; j > 0; j--) {
row.push(x)
x += (i < j ? ++dx : dx--)
}
}
return matrix
}
var matrix = diagonalMatrix(+prompt('Diagonal Matrix Order:'))
console.log(beautify(matrix))
console.log(matrix)
// For visualization purposes
function beautify (matrix) {
return matrix.map(function (e) {
return e.join('\t')
}).join('\n\n\n\n')
}
.as-console-wrapper { min-height: 100vh; }
Related
Please help me to solve this leetcode problem using javascript as I am a beginner and dont know why this code is not working
Ques: Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
var findDisappearedNumbers = function (nums) {
var numLength = nums.length;
nums.sort(function (a, b) { return a - b });
for (var i = 0; i < nums.length - 1; i++) {
if (nums[i + 1] === nums[i]) {
nums.splice(i, 1);
}
}
for (var k = 0; k < nums.length; k++) {
for (var j = 1; j <= numLength; j++) {
if (nums[k] !== j) {
return j;
}
}
}
};
if there is any error in my code please let me know;
i have done the following thing
first i have sorted the array in ascending order
then i have cut all the duplicate elements
then i have created loop that will check if nums[k] !== j ;
and it will return j which is the missing number;
for example this is the testcase [4,3,2,7,8,2,3,1]
first my code will sort this in ascending order [1,2,2,3,3,4,7,8]
then it will remove all duplicate elements and it will return [1,2,3,4,,7,8]
and then it will check nums[k] is not equal to j and it will print j
I think it'd be easier to create a Set of numbers from 1 to n, then just iterate through the array and delete every found item from the set:
var findDisappearedNumbers = function(nums) {
const set = new Set();
for (let i = 0; i < nums.length; i++) {
set.add(i + 1);
}
for (const num of nums) {
set.delete(num);
}
return [...set];
};
console.log(findDisappearedNumbers([4,3,2,7,8,2,3,1]));
To fix your existing code, I'm not sure what the logic you're trying to implement in the lower section, but you can iterate from 1 to numLength (in the outer loop, not the inner loop) and check to see if the given number is anywhere in the array. Also, since you're mutating the array with splice while iterating over it in the upper loop, make sure to subtract one from i at the same time so you don't skip an element.
var findDisappearedNumbers = function(nums) {
var numLength = nums.length;
nums.sort(function(a, b) {
return a - b
});
for (var i = 0; i < nums.length - 1; i++) {
if (nums[i + 1] === nums[i]) {
nums.splice(i, 1);
i--;
}
}
const notFound = [];
outer:
for (var j = 1; j < numLength; j++) {
for (var k = 0; k < nums.length; k++) {
if (nums[k] === j) {
continue outer;
}
}
notFound.push(j);
}
return notFound;
};
console.log(findDisappearedNumbers([4, 3, 2, 7, 8, 2, 3, 1]));
#CertainPerformance certainly cracked it again using the modern Set class. Here is a slighly more conservative approach using an old fashioned object:
console.log(missingIn([4,3,2,7,8,2,3,1]));
function missingIn(arr){
const o={};
arr.forEach((n,i)=>o[i+1]=1 );
arr.forEach((n) =>delete o[n] );
return Object.keys(o).map(v=>+v);
}
My solution for the problem to find the missing element
var findDisappearedNumbers = function(nums) {
const map={};
const result=[];
for(let a=0;a<nums.length;a++){
map[nums[a]]=a;
}
for(let b=0;b<nums.length;b++){
if(map[b+1]===undefined){
result.push(b+1)
}
}
return result;
};
Example 1:
Input: nums = [4,3,2,7,8,2,3,1]
Output: [5,6]
Example 2:
Input: nums = [1,1]
Output: [2]
Base point: I'm looking for help on how to use Dynamic programming to solve the following problem. My current solution is a little out of control.
Problem: find the maximum sum from an NxN matrix combining only one element from each subarray, must choose elements from each of the columns.
For example:
[[1,2],
[3,4]]
The max sum would be 5. So either matrix[0][0] + matrix[1][1] or matrix[0][1] + matrix[1][0].
Should be able to run for n = 0...30.
I wrote the following function with sub-optimal time complexity:
var perm = function (values, currentCombo = [], allPerm = []) {
if (values.length < 1) {
allPerm.push(currentCombo);
return allPerm;
}
for (var i = 0; i < values.length; i++) {
var copy = values.slice(0);
var value = copy.splice(i, 1);
perm(copy, currentCombo.concat(value), allPerm);
}
return allPerm;
};
var maxSumMatrix = function(matrix){
var n = matrix.length;
var options = [];
for(let i = 0; i < n; i++){
let row = new Array(n).fill(0);
row[i] = 1;
options.push(row);
}
var paths = perm(options);
var accumMax = null;
for(var i = 0; i < paths.length; i++){
var sum = null;
for(var j = 0; j < paths[i].length; j++){
for(var k = 0; k < paths[i][j].length; k++){
sum += paths[i][j][k] * matrix[j][k];
}
if(accumMax === null || accumMax < sum){
accumMax = sum;
}
}
}
return accumMax;
}
So "perm" finds all 0,1 permutations of solutions, then I multiply each possible solution to the input matrix and find the max answer.
Thank you!
EDIT
So for the following matrix: [[1,2,4], [2,-1,0], [2,20,6]];
The greatest sum would be 26.
From: matrix[0][2] + matrix[1][0] + matrix[2][1]
Here's how I would approach it:
const remove = (start, count, list) => {
var result = list.slice(0);
result.splice(start, count);
return result;
}
const removeRow = (row, matrix) => remove(row, 1, matrix);
const removeCol = (col, matrix) => matrix.map(row => remove(col, 1, row));
const max = (xs) => Math.max.apply(null, xs);
const maxSum = (matrix) => matrix.length === 1
? max(matrix[0])
: max(matrix[0].map((col, idx) => col + maxSum(removeCol(idx, removeRow(0, matrix)))));
maxSum([
[1, 2, 4],
[2, -1, 0],
[2, 20, 6]
]); //=> 26
This would run into recursion depth problems if you are working with very large matrices.
This makes all sorts of simplifying assumptions. They boil down to the requirement that the input is a square matrix of numbers. Bad things might happen if it isn't.
If it interests you, I did this first in Ramda, because that's how I think. (I'm one of the authors.) And then I translated it to the above.
In Ramda, it might look like this:
const removeRow = curry((row, matrix) => remove(row, 1, matrix));
const removeCol = curry((col, matrix) => map(remove(col, 1), matrix));
const highest = (xs) => Math.max.apply(null, xs);
const maxSum = (matrix) => matrix.length == 1
? highest(matrix[0])
: highest(addIndex(map)((col, idx) => col + maxSum(removeCol(idx, removeRow(0, matrix))), matrix[0]));
...which you can see on the Ramda REPL.
I have an issue with getting the sum of two arrays and combining their averages while rounding off.
I don't want to hardcode but rather pass two random arrays. so here is the code but it keeps returning NaN
function sumAverage(arr) {
var result = 0;
// Your code here
// set an array
arr = [];
a = [];
b = [];
arr[0] = a;
arr[1] = b;
var sum = 0;
// compute sum of elements in the array
for (var j = 0; j < a.length; j++) {
sum += a[j];
}
// get the average of elements in the array
var total = 0;
total += sum / a.length;
var add = 0;
for (var i = 0; i < b.length; i++)
add += b[i];
var math = 0;
math += add / b.length;
result += math + total;
Math.round(result);
return result;
}
console.log(sumAverage([
[2, 3, 4, 5],
[6, 7, 8, 9]
]));
If you wanted to do it a bit more functionally, you could do something like this:
function sumAverage(arrays) {
const average = arrays.reduce((acc, arr) => {
const total = arr.reduce((total, num) => total += num, 0);
return acc += total / arr.length;
}, 0);
return Math.round(average);
}
console.log('sum average:', sumAverage([[1,2,3], [4,5,6]]));
Just try this method..this kind of issues sometimes occured for me.
For example
var total = 0;
total = total + sum / a.length;
And every concat use this method..
Because you are assigning the value [] with the same name as the argument? This works, see jFiddle
function sumAverage(arr) {
var result = 0;
//arr = [];
//a = [];
//b = [];
a = arr[0];
b = arr[1];
var sum = 0;
// compute sum of elements in the array
for(var j = 0; j < a.length; j++ ){
sum += a[j] ;
}
// get the average of elements in the array
var total = 0;
total += sum / a.length;
var add = 0;
for(var i = 0; i < b.length; i++)
add += b[i];
var math = 0;
math += add / b.length;
result += math + total;
Math.round(result);
return result;
}
document.write(sumAverage([[2,3,4,5], [6,7,8,9]]));
As said in comments, you reset your arguments...
Use the variable "arguments" for dynamic function parameters.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
I suggest to use two nested loops, one for the outer array and one for the inner arrays. Then sum values, calculate the average and add averages.
function sumAverage(array) {
var result = 0,
sum,
i, j;
for (i = 0; i < array.length; i++) {
sum = 0;
for (j = 0; j < array[i].length; j++) {
sum += array[i][j];
}
result += Math.round(sum / array[i].length);
}
return result;
}
console.log(sumAverage([[2, 3, 4, 5], [6, 7, 8, 9]])); // 12
The problem is that you are emptying arr by saying arr = [].
Later, you are iterating over a which is empty too.
Again when you say total += sum / a.length;, sum is 0 and a.length is 0 so 0/0 becomes NaN. Similarly for math. Adding Nan to NaN is again NaN and that's what you get.
Solution is to not empty passed arr and modify your code like below:
function sumAverage(arr) {
var result = 0;
// Your code here
// set an array
//arr = [];
//a = [];
//b = [];
a = arr[0];
b = arr[1];
var sum = 0;
// compute sum of elements in the array
for (var j = 0; j < a.length; j++) {
sum += a[j];
}
// get the average of elements in the array
var total = 0;
total = sum / a.length;
var add = 0;
for (var i = 0; i < b.length; i++)
add += b[i];
var math = 0;
math = add / b.length;
result = math + total;
result = Math.round(result);
return result;
}
console.log(sumAverage([
[2, 3, 4, 5],
[6, 7, 8, 9]
]));
Basically I see a mistake here:
arr[0] = a; arr[1] = b;
That should be
a= arr[0]; b= arr[1];
and then remove:
arr = [];
I suggest you write your function like this:
function sum(arr) {
var arr1 = arr[0]
var sum1 = 0;
arr1.map(function(e){sum1+=e});
var arr2 = arr[1]
var sum2 = 0;
arr2.map(function(e){sum2+=e});
return Math.round(sum1/arr1.length + sum2/arr2.length);
}
The following code will generate 10 arrays, each with 10 subarrays, each with 10 subarrays, each with 10 subarrays.
paths = [];
for (var i = 0, len_i = 10; i < len_i; ++i) { // 1st dimension
paths.push([]);
for (var j = 0, len_j = 10; j < len_j; ++j) { // 2nd dimension
paths[i].push([]);
for (var k = 0, len_k = 10; k < len_k; ++k) { // 3rd dimension
paths[i][j].push([]);
for (var l = 0, len_l = 10; l < len_l; ++l) { // 4th dimension
paths[i][j][k].push([]);
paths[i][j][k][l] = [];
}
}
}
}
I will eventually need to do this with more dimensions and am curious to know if any ingenious developers out there can accomplish this with a function of the form:
function makePaths(quantityInEachArray, dimensions) {
paths = [];
quantityInEachArray = (typeof quantityInEachArray === "undefined") ? 10 : quantityInEachArray;
dimensions = (typeof dimensions === "undefined") ? 4 : dimensions;
// Do some magic
return paths;
}
That function, in its default form, would return the same thing as the for loops I demonstrated above.
I understand that this is not a standard practice but I am doing it for a very specific reason and need to test the performance of it.
How do I modify this code to produce nth dimensional arrays?
You can use recursive function:
function nthArray(n, l) {
if(n < 1) return;
var arr = new Array(l);
for(var i=0; i<l; ++i)
arr[i] = nthArray(n-1, l);
return arr;
}
A simple magic would be (without recursion):
paths = []
arrays = [paths]
for (var i = 0; i < dimensions; i++) {
tmpArr = []
for (var k = 0; k < arrays.length; k++) {
for (var j = 0; j < size; j++) {
val = []
tmpArr.push(val)
arrays[k].push(val)
}
}
arrays = tmpArr
}
(I am not very fluent in javascript, you probably need to declare vars at the beginning and every thing, but that's the idea)
I have got a little function in javascript and I want to split an array A into a 2d array.
I will be used for square matrices. Obviously,I want it to be 2x2 if a square matrix of 2x2 is in the input and so on for 3x3 and. But I'm stuck after having read a first row.So my arr rows are repeated. Does anyone have any ideas about how I can get the next rows read properly.So,for instance,lets say I do have an array
A = [2,1,4,5,1,2,3,1,9]
Then I want my array arr to look like this:
arr = [[2,1,4],[5,1,2],[3,1,9]]
This will later be used for calculation a determinant of a matrix.
function create2Darray(clname) {
var A = document.getElementsByClassName(clname);
var arr = new Array();
var rows = Math.sqrt(A.length);
for (var i = 0; i < rows; i++) {
arr[i] = new Array();
for (var j = 0; j < rows; j++) {
arr[i][j] = A[j].value;
}
}
}
You are assigning always the same value. It should be something like:
arr[i][j] = A[i*rows+j].value;
EDIT: Here's a complete function without the DOM manipulation (that is, A is a simple array of integers):
function create2Darray(A) {
var arr = [];
var rows = Math.sqrt(A.length);
for (var i = 0; i < rows; i++) {
arr[i] = [];
for (var j = 0; j < rows; j++) {
arr[i][j] = A[i * rows + j];
}
}
return arr;
}
console.log(create2Darray([1, 2, 3, 4, 5, 6, 7, 8, 9]))