How to produce a n by n matrix in JavaScript - javascript

Write the following function:
generateInput(n: number): number[][]
This function should produce an n by n array of preferences for companies or candidates. The
input generated will be used for testing a given solution. Above, we have described only the
shapes of the inputs; you will have to infer the constraints we’ve left out. Make sure that your
function always generates random values as it will be helpful to test a given solution with a
broad spectrum of input.
function generateInput(n) {
let matrix = [];
for (let i = 0; i < n; ++i) {
matrix[i] = [];
for (let j = 0; j < n; ++j) {
matrix[i][j] = [];
}
}
}
I'm a newbie of learning JavaScript, so could someone please check whether my code produce a n by n matrix or not?

You can run this in a node environment, or in the browser console, or even in a snippet on StackOverflow. In your case the code is failing to return the matrix when completed. I added that line and called it with a few different values in the snippet below, so you can see what it returns.
function generateInput(n){
let matrix = [];
for(let i=0; i<n; ++i) {
matrix[i] = [];
for(let j=0; j<n; ++j) {
matrix[i][j] = [];
}
}
return matrix;
}
console.log(generateInput(1));
console.log(generateInput(2));
console.log(generateInput(3));
console.log(generateInput(4));

Yes, it produces a matrix with empty arrays. To get access to matrix variable from outside you need to return this value. See example below.
function generateInput(n){
let matrix = [];
for (let i=0; i<n; i++) {
matrix[i] = [];
for (let j=0; j<n; j++) {
matrix[i][j] = [];
}
}
return matrix; // here
}
const result = generateInput(5);
console.log(result);

Related

Quick sorting array in JavaScript

const arr = [5,3,2,6,1];
const quickSort = (arr) => {
for(let j = 0; j < arr.length; j++) {
let index = null;
let min = arr[0];
for(let i = 0; i < arr.length; i++) {
if(arr[i] < min) {
min = arr[i]
index = i
}
}
const tmp = arr[j]
arr[0] = min;
arr[index] = tmp
}
return arr;
}
console.log(quickSort(arr), 'res')
In the code above i try to sort the array using the next logic:
i compare each array element with the first one and if it is lower than the first then i swap the array elements.
Doing this i don't get the sorted array. Question: What is the issue with my code and how to fix it?
const arr = [5,3,2,6,1];
const quickSort = (arr) => {
for(let j = 0; j < arr.length; j++) {
let index = j;
let min = arr[j];
for(let i = j+1; i < arr.length; i++) {
if(arr[i] < min) {
min = arr[i]
index = i
}
}
let tmp = arr[j]
arr[j] = min;
arr[index] = tmp
}
return arr;
}
Quick sort is a divide and conquer algorithm used for sorting. If you want to view more information about it visit the wikipedia site for quick sort. Your current code does what you told it to do, which is not sorting but as you said it is comparing each element with the first one and if it is smaller it swaps them. Now, if you want to sort an array just use the built-in sort function
arr.sort();
That should sort the array. If you want to built one on your own I would suggest to pick one that best suits you from the long list of sorts.
If you are a beginner, I would suggest you to try Bubble Sort or Selection Sort, but if you feel comfortable with writing code then Quick Sort or even Merge Sort could potentially be more suitable for you.
Revieing your code, it appears that you were trying to implement a Selection sort. This code should help:
const arr = [5,3,2,6,1];
const SelectionSort = (arr) => {
for(let j = 0; j < arr.length; j++) {
let index = null;
let min = arr[j];
for(let i = j; i < arr.length; i++) {
if(arr[i] < min) {
min = arr[i]
index = i
}
}
const tmp = arr[j]
arr[j] = min;
arr[index] = tmp
}
return arr;
}
console.log(SelectionSort(arr), 'res')
Your main mistake in the code was that you started everything from index 0, but you should have initialised everything from j because you are in a loop.

unable to loop the object in Angular

I have a data like below
data = ["I253,J665,l2575"]
and I need the the results like
I253,
J665,
l2575
when i tried to use for in i am getting like I253,J665,l2575 and I tried for loops also but not getting the result
let data = ["I253,J665,l2575"]
for (let i = 0; i > this.data.length; i++) {
console.log(i)
}
for (let x of this.data) {
console.log(x)
}
tried converting the data in to string and then using split changed into array but then also i am getting typeof object only
below is my stack blitz url =: https://stackblitz.com/edit/angular-ivy-drf1dk?file=src/app/app.component.ts
Modify your data variable like below:
data = ["I253", "J665", "l2575"];
for(let i = 0; i < this.data.length; i++){
console.log(this.data[i]);
}
If you have data variable as data = ["I253,J665,l2575"];
Then split it first and then loop through the generated array:
const arr = data[0].split(',');
for(let i = 0; i < arr.length; i++){
console.log(arr[i] + ',');
}
You were having multiple mistakes. First one was with for condition it should be i < this.data.length not i > this.data.length. Then you need to split and loop over it with for (let j = 0; j < data[i].split(',').length; j++) so data[i].split(',')[j] will return expected value.
In case of 2nd for...of loop you were simply logging whole value. Here also you need to split inside for...of and use one more loop to log.
Alternatively you can also use flatMap and loop over it like for (let m of data.flatMap(x => x.split(','))).
Try it below. You can use this.data, but it won't work in below example so it is used as simply data.
let data = ["I253,J665,l2575"];
console.log("Using for loop");
for (let i = 0; i < data.length; i++) {
for (let j = 0; j < data[i].split(',').length; j++) {
console.log(data[i].split(',')[j]);
}
}
console.log("Using for...of loop");
for (let x of data) {
for (let y of x.split(',')) {
console.log(y);
}
}
console.log("Using flatMap");
for (let m of data.flatMap(x => x.split(','))) {
console.log(m);
}
Two ways to solve this.
Also note that your loop is wrong SHOULD NOT BE '>' and Should Be '<'
1. Your data is at array index zero so if you are to keep the data as is
let data = ["I253,J665,l2575"]
let splits = data[0].split(',')
for (let i = 0; i < splits.length; i++) {
console.log(splits[i])
}
or
let data = ["I253,J665,l2575"]
let splits = data[0].split(',')
for (let element of splits) {
console.log(element )
}
2. Fix the data string
let dataString = "I253,J665,l2575"
let splits = dataString.split(',')
for (let i = 0; i < splits.length; i++) {
console.log(splits[i])
}
or
let dataString = "I253,J665,l2575"
let splits = dataString.split(',')
for (let element of splits) {
console.log(i)
}
Clone of the example provided in question
https://stackblitz.com/edit/angular-ivy-izj7up

How do i split up an array that holds an array?

Hello my fellow JS friends,
I am letting a user import a csv file (excel sheet) and i convert that into
an array. which has 472 rows and 87 columns in this case.
so my array looks like this:
and everything is separated by commas like a usual array.
The issue is I need to separate the array within the array and when i do that i get an array with the length of 9 million, which i think is wrong
vm.allTextLines = files.split(/\r\n|\n/);
var headers = vm.allTextLines[0].split(',');
vm.columnCount = headers.length;
vm.rowCount = vm.allTextLines.length - 1;
for (var i = 0; i < vm.allTextLines.length; i++) {
// split content based on comma
var data = vm.allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for (var j = 0; j < headers.length; j++) {
tarr.push(data[j]);
}
vm.lines.push(tarr);
}
}
//this is where i split the array that contains the csv
//data and put it into its own array I believe this is
//where the issue is.
for(var i=1;i<vm.allTextLines.length; i++){
vm.uniqueAll.push(vm.allTextLines[i].split(','));
for(var j=0; j < vm.uniqueAll.length; j++){
for(var r =0; r < vm.uniqueAll[j].length; r++){
vm.arrayOfValuesOfFile.push(vm.uniqueAll[j][r]);
}
}
}
If you can help me correct this for each I would appreciate it alot.
Thank you in advance guys!
I agree with you about the place of error, because it seems you nested the loop in a wrong way. Following a snippet where you can check what I mean.
i.e:
let vm = {
allTextLines:['h1,h2,h3','row1val1,row1val2,row1val3', 'row2val1,row2val2,row2val3'],
uniqueAll: [],
arrayOfValuesOfFile:[]
}
// Here you should not nest the loop
for(var i=1;i<vm.allTextLines.length; i++){
vm.uniqueAll.push(vm.allTextLines[i].split(','));
}
for(var j=0; j < vm.uniqueAll.length; j++){
for(var r =0; r < vm.uniqueAll[j].length; r++){
vm.arrayOfValuesOfFile.push(vm.uniqueAll[j][r]);
}
}
console.log('allTextLines', vm.allTextLines);
console.log('uniqueAll', vm.uniqueAll);
console.log('arrayOfValuesOfFile', vm.arrayOfValuesOfFile);
Of Course you could easily optimize the algorithm:
let vm = {
allTextLines:['h1,h2,h3','row1val1,row1val2,row1val3', 'row2val1,row2val2,row2val3'],
uniqueAll: [],
arrayOfValuesOfFile:[]
}
for(var i=1;i<vm.allTextLines.length; i++){
let currentLinesValue = vm.allTextLines[i].split(',');
vm.uniqueAll.push(currentLinesValue);
for(var r =0; r < currentLinesValue.length; r++){
vm.arrayOfValuesOfFile.push(currentLinesValue[r]);
}
}
console.log('allTextLines', vm.allTextLines);
console.log('uniqueAll', vm.uniqueAll);
console.log('arrayOfValuesOfFile', vm.arrayOfValuesOfFile);
First you should transform you bidimensional array into a one-dimension array.
var allTogether = []; // Array with all your CSV (no matter from which file it came from)
for (var i = 0; vm.allTextLines.length; i++) {
allTogether.push(vm.allTextLines[i]); // Gets the CSV line an adds to a one-dimension array
}
// Now you can iterate over the one-dimension array
for (var i = 0; allTogether.length; i++) {
var csvFields = allTogether[i].split(',');
// Here goes your code that works with the CSV fields.
}

Get cell of 2D Matrix in Google Spreadsheet

I have this function as a custom function in Google Apps Script being used in a spreadsheet:
function MultiplyMatrix(m2, m1) {
var result = [];
for(var j = 0; j < m2.length; j++) {
result[j] = [];
for(var k = 0; k < m1[0].length; k++) {
var sum = 0;
for(var i = 0; i < m1.length; i++) {
sum += m1[i][k] * m2[j][i];
}
result[j].push(sum);
}
}
return result;
}
Is there a way to get a specific index of the array without getting the whole result matrix input into the spreadsheet, If so what is the syntax?
I have this:
I want just this:
As I cannot comment, I'll use an answer. Given how your question is formulated, a simple answer can be to change your custom function definition so that it takes two extra parameters, the row index and column index of the result you're interested in; hence your code becomes:
function MultiplyMatrix(m2, m1, row, col) {
var result = [];
for(var j = 0; j < m2.length; j++) {
result[j] = [];
for(var k = 0; k < m1[0].length; k++) {
var sum = 0;
for(var i = 0; i < m1.length; i++) {
sum += m1[i][k] * m2[j][i];
}
result[j].push(sum);
}
}
return result[row][col];
}
You can then call your function as =MultiplyMatrix(A1:B2, C3:D4, 1, 1) to get the value of the intersection of the second row and second column.
If that is not the answer you expect, I suggest you edit your question, tag it also as google-spreadsheet (javascript custom functions are specific to that), and clarify the requirements. A spreadsheet example could be useful for us all to help.

Referencing Javascript array element via loop variable

I've come across writing a piece of code where I wanted to reference the 2D array d2_arr[][] in a loop like so.
for (var i=0; i<d2_arr[i].length; i++) {
//do something
}
Google Script compiler throws an error "cannot read length property from undefined". When I changed [i] for [1], it worked just fine. Could anyone please explain why this is wrong? And a related question: Can a 2D array have a different number of elements in a row? theoretically. An example would be:
[[1,2],[3,4,5],[6,7,8,9],[10,11]]
EDIT. Full code part.
var ids = [];
var j = 0;
for (var i=0; i<d2_arr[i].length; i++){
if (d2_arr[i][2]<=0.05){
ids[j]=d2_arr[i][0];
j++;
}
}
I understood the mistake. Thank you!
You typically need a nested for loop to traverse a 2-D array
var d2_arr = [[1,2],[3,4,5],[6,7,8,9],[10,11]]
for (var i=0; i<d2_arr.length; i++){
for (var j=0; j<d2_arr[i].length; j++){
console.log(d2_arr[i][j] + ' ')
}
}
It is perfectly fine for arrays to be "jagged" and contain uneven sized arrays in the main array.
Here is a fiddle http://jsfiddle.net/7Lr4542s/
Arrays in JS can be of any size and any type. You can combine number and strings in array.
var twoDArray = [[1], ["one", "two"], ["i", "ii", "iii"]];
for(var i = 0; i < twoDArray.length; i++) {
for(var j = 0; j < twoDArray[i].length; j++) {
print(twoDArray[i][j]);
}
}
var threeDArray = [[["1.1.1", "1.1.2"], ["1.2.1", "1.2.2"]], [["1.2.1", "1.2.2"], ["1.2.1", "1.2.2"]], [["2.1.1", "2.1.2"], ["2.2.1", "2.2.2"]], [["2.2.1", "2.2.2"], ["2.2.1", "2.2.2"]]];
for(var i = 0; i < threeDArray.length; i++) {
for(var j = 0; j < threeDArray[i].length; j++) {
for(var k = 0; k < threeDArray[i][j].length; k++) {
print(twoDArray[i][j][k]);
}
}
}

Categories

Resources