print array in transpose format using jquery - javascript

I am little bit stuck in the below logic.
var t = new Array(),
i = 1;
for (var s = 0; s < 7; s++) {
t[s] = [];
for (j = 0; j < 7; j++) {
t[s][j] = i;
if (i === 6) {
i = 0;
}
i++;
}
}
console.log(t);
In my tried logic i am getting array like below
0: [1,2,3,4,5,6,1]
1: [2,3,4,5,6,1,2]
2: [3,4,5,6,1,2,3]
3: [4,5,6,1,2,3,4]
4: [5,6,1,2,3,4,5]
5: [6,1,2,3,4,5,6]
6: [1,2,3,4,5,6,1]
But I want output
0: [1,2,3,4,5,6,0]
1: [2,3,4,5,6,0,1]
2: [3,4,5,6,0,1,2]
3: [4,5,6,0,1,2,3]
4: [5,6,0,1,2,3,4]
5: [6,0,1,2,3,4,5]
6: [0,1,2,3,4,5,6]
Looking for help.

You can achieve it by rotating array.
let len = 7;
let a = Array.from(Array(len).keys());
let ans = [];
for(let i = 0; i < len; i++){
a = a.slice(1,a.length).concat(a.slice(0,1));
ans.push(a);
}
console.log(ans);

I would solve it in a different approach - You are building a two dimensional array that each new element (or row) is shifted or incremented by one (6 is the max value)
So increment each value by one and store the result.
$column = [1,2,3,4,5,6,0];
$max = 6;
$rows = 7;
$result = [];
for ($i = 0; $i < $rows; $i++) {
$result[$i] = [...$column];
for ($j = 0; $j < $column.length; $j++) {
if ($column[$j] == $max) $column[$j] = 0;
else $column[$j]++;
}
}
console.log($result);

reason of your bug
when doing so for the case i == 6
i = 0
i++
You are incrementing i twice... (from 6 to 1 instead of from 6 to 0)
You can:
if (i === 6) {
i = 0;
} else {
i++;
}
or more elegantly
i = (i + 1) % 7
Now you want i to be valid before assignment
t[s][j] = i will be not good if i == 7
so modulo it before
t[s][j] = i % 7
i++
let t = []
let i = 1
for (let s = 0; s < 7; s++) {
t[s] = []
i = s + 1 // start of your row
for (let j = 0; j < 7; j++) {
t[s][j] = i % 7
++i
}
}
console.log(t.map(r=>r.join(',')).join('\n'))
finally you can shorten your code by using map
let t = Array(7).fill(0).map( (r, i) => {
return Array(7).fill(0).map( (c, j) => ((i + 1) + j) % 7)
})
console.log(t.map(r=>r.join(',')).join('\n'))

Another approach is to use modulo. Using k % n will make the number rotate to 0 with every n
Also, you don't need the variable i. You could calculate it using s + j + 1 instead.
function p(a)
{
let str="";
for(i of a)
{
for(j of i)
{
str += j + " ";
}
str += "\n";
}
console.log(str);
}
var t = new Array();
var arraySize = 7;
var rotateEvery = 7;
for (var s = 0; s < arraySize; s++) {
t[s] = [];
for (j = 0; j < arraySize; j++) {
t[s][j] = (s + j + 1) % rotateEvery;
}
}
p(t);

Related

longest common substring Multiple Input in JS

function LCSubStr(X, Y) {
let m = X.length;
let n = Y.length;
let result = 0;
let end;
let len = new Array(4);
for (let i = 0; i < len.length; i++) {
len[i] = new Array(n);
for (let j = 0; j < n; j++) {
len[i][j] = 0;
}
}
let currRow = 0;
for (let i = 0; i <= m; i++) {
for (let j = 0; j <= n; j++) {
if (i == 0 || j == 0) {
len[currRow][j] = 0;
}
else if (X[i - 1] == Y[j - 1]) {
len[currRow][j] = len[1 - currRow][j - 1] + 1;
if (len[currRow][j] > result) {
result = len[currRow][j];
end = i - 1;
}
}
else {
len[currRow][j] = 0;
}
}
currRow = 1 - currRow;
}
if (result == 0) {
return "-1";
}
return X.substr(end - result + 1, result);
}
// Driver Code
let X = "GeeksforGeeks";
let Y = "GeeksQuiz";
// function call
document.write(LCSubStr(X, Y));
How can I convert this code for multiple input?
I checked many lcs code but no one works with
ABCQEFDEFGHIJ BCXEFGYZBCDEWEFGHU > EFGH
This one just works good without any problem. I should convert this one for multiple input in Javascript.
Now we have X,Y but it shoulde be with multiple inputs.

How do I make this JavaScript console.log into 6 rows with 6 indexes? [duplicate]

This question already has answers here:
Print an output in one line using console.log()
(13 answers)
Closed last year.
Instead of 1 index on each row, I want horizontal not vertical returns.
let n = [6];
function staircase() {
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= n - i; j++) {
console.log("0");
}
for (let k = 1; k <= i; k++) {
console.log('#');
}
}
}
staircase();
But I need it to render like this. (This works using Java; it's the same logic, but renders differently.)
#
##
###
####
#####
######
console.log prints one line each therefore i put 2 variables to keep the empty string and hash string and after the loops logged the concatenation of the strings
let n = 6
function staircase() {
for (let i = 1; i <= n; i++) {
let emptyString = '';
let hashString = '';
for (let j = 1; j <= n - i; j++) {
emptyString += " ";
}
for (let k = 1; k <= i; k++) {
hashString += '#'
}
console.log(emptyString + hashString)
}
}
staircase();
const n = [6]
for (let i = 1; i <= n; i++) {
//
// this array stores the results;
//
const array = [];
//
for (let j = 1; j <= n - i; j++) {
array.push("0");
}
for (let k = 1; k <= i; k++) {
array.push('#');
}
// adding `toString`, does the magic
console.log(array.toString())
}

Why is my program not working?

I'm trying to write a simple program to calculate the biggest even number from an array.
An array of 10 elements is used.
function biggestEven(array) {
var numberOfNumbers = array.length;
var biggestYet = 0;
var theNumber;
for (var i = 0; i < numberOfNumbers; i++) {
if(array[i] % 2 = 0) {
biggestYet = array[i];
}
if(array[i] % 2 = 0 && array[i] > biggestYet) {
theNumber = biggestYet;
}
}
return theNumber;
}
var myArray = [];
for (var i = 0; i < 10; i++) {
myArray[i] = window.prompt("Enter number " + (i+1) + "of 10:");
}
console.log("The biggest even number is: " + biggestEven(myArray));
Please help I am stuck. The program won't lead in chrome.
You're giving a value, not comparing:
if(array[i] % 2 = 0) {
biggestYet = array[i];
}
And also you were returning the wrong element:
function biggestEven(array) {
var numberOfNumbers = array.length;
var biggestYet = 0;
var theNumber = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] % 2 === 0) {
biggestYet = array[i];
}
if (array[i] % 2 === 0 && array[i] > biggestYet) {
theNumber = biggestYet;
}
}
return biggestYet;
}
var myArray = [];
for (var i = 0; i < 2; i++) {
myArray[i] = window.prompt("Enter number " + (i+1) + " of 10:");
}
console.log("The biggest even number is: " + biggestEven(myArray));
This might help:
console.log(Math.max(...[267, 306, 108, 307].filter(function(value) { return value % 2 === 0 })));
You need to change
if(array[i] % 2 = 0) {
biggestYet = array[i];
}
to
if(array[i] % 2 == 0) {
biggestYet = array[i];
}
Here is a solution for your problem
function biggestEven(array) {
return Math.max(...array.filter(function(num){
return num%2==0;
}));
}
var myArray = [1,2,36,45,51,16,7];
alert(biggestEven(myArray));

There's a bug in my code

My code isn't working . I'm trying to figure out what the bug is . Can someone help ? ! It's a function that is supposed to return an array of the first n triangular numbers.
For example, listTriangularNumbers(5) returns [1,3,6,10,15].
function listTriangularNumbers(n) {
var num;
var array = [];
for (i = 1; i <= n; ++i) {
num = i;
for (j = i; j >= 1; --j) {
num = num + j;
}
array.push(num);
}
return array;
}
Your initial initialization of j is wrong, it's starting at i so it's going too high. Also switched the operators around to make sure the conditions work.
function listTriangularNumbers(n) {
var num;
var array = [];
for (i = 1; i <= n; i++) {
num = i;
for (j = i-1; j >= 1; j--) {
num = num + j;
}
array.push(num);
}
return array;
}
You can try below code to get help:
a = listTriangularNumbers(8);
console.log(a);
function listTriangularNumbers(n) {
var num;
var array = [0];
for (i = 1; i <= n; i++) {
num = 0;
for (j = 1; j <= i; j++) {
num = num + j;
}
array.push(num);
}
return array;
}
You actually don't need 2 for-loops to do this operation. A single for-loop would suffice.
function listTriangularNumbers(n) {
// Initialize result array with first element already inserted
var result = [1];
// Starting the loop from i=2, we sum the value of i
// with the last inserted element in the array.
// Then we push the result in the array
for (i = 2; i <= n; i++) {
result.push(result[result.length - 1] + i);
}
// Return the result
return result;
}
console.log(listTriangularNumbers(5));
function listTriangularNumbers(n) {
var num;
var array = [];
for (i = 1; i <= n; ++i) {
num = i;
for (j = i-1; j >= 1; --j) {
num = num + j;
}
array.push(num);
}
return array;
}
var print=listTriangularNumbers(5);
console.log(print);

Got 90% of the JavaScript code - can't figure out the rest

So I am trying to model Gram-Schmidt for any size N×N matrix, and I have officially hit a roadblock I can't get past. I know it's a matter of looping this correctly, but I can't figure out what the problem is. Remember I do not want to just pass in a 3×3 matrix, but any size N×N.
The course notes QR Decomposition with Gram-Schmidt explains exactly what I want to do. Very simple calculation by the way. In the course notes ||u|| means that it is the sum of the square of the elements, so sqrt(x12 + x22 + x32 + .... + xn2).
The multiplication symbol is actually the dot product.
The code I wrote so far is listed below. What is wrong with it?
function qrProjection(arr) {
var qProjected = [];
var tempArray = [];
var aTemp = arr;
var uTemp = new Array(arr.length);
var uSquareSqrt = new Array(arr.length);
var eTemp = [];
var sum = 0;
var sumOfSquares = 0;
var breakCondition = 0;
var secondBreakCondition = 0;
var iterationCounter = 0;
//Build uTemp Array
for (i = 0; i < arr.length; i++) {
uTemp[i] = new Array(arr[i].length);
}
for (i = 0; i < arr.length; i++) {
eTemp[i] = new Array(arr[i].length);
}
uTemp[0] = aTemp[0];
for (j = 0; j <= arr.length; j++) {
for (l = 0; l < arr[j].length; l++) {
if (breakCondition == 1) break;
sumOfSquares = Math.pow(uTemp[j][l], 2) + sumOfSquares;
}
if (breakCondition == 0) {
uSquareSqrt[j] = Math.sqrt(sumOfSquares);
sumOfSquares = 0;
}
for (i = 0; i < arr[j].length; i++) {
if (breakCondition == 1) break;
eTemp[j][i] = (1 / (uSquareSqrt[j])) * (uTemp[j][i]);
}
breakCondition = 1;
if (iterationCounter == 0) {
for (m = 0; m < arr[j].length; m++) {
matrixDotProduct = aTemp[j + 1][m] * eTemp[j][m] + matrixDotProduct;
}
}
else {
for (m = 0; m < arr[j].length; m++) {
for (s = 0; s <= iterationCounter; s++) {
matrixDotProduct = aTemp[j + 1][s] * eTemp[m][s] + matrixDotProduct;
}
for (t = 0; t < arr[j].length; t++) {
uTemp[j + 1][t] = aTemp[j + 1][t] - eTemp[j][t] * matrixDotProduct;
}
}
}
if (iterationCounter == 0) {
for (m = 0; m < arr[j].length; m++) {
uTemp[j + 1][m] = aTemp[j + 1][m] - eTemp[j][m] * matrixDotProduct;
}
}
matrixDotProduct = 0;
for (l = 0; l < arr[j].length; l++) {
sumOfSquares = Math.pow(uTemp[j + 1][l], 2) + sumOfSquares;
}
uSquareSqrt[j + 1] = Math.sqrt(sumOfSquares);
sumOfSquares = 0;
for (i = 0; i < arr[j].length; i++) {
eTemp[j + 1][i] = (1 / (uSquareSqrt[j + 1])) * (uTemp[j + 1][i]);
}
iterationCounter++;
}
qProjected = eTemp;
return qProjected;
}
I must apologize that instead of tweaking your code, I wrote my own from scratch:
/* Main function of interest */
// Each entry of a matrix object represents a column
function gramSchmidt(matrixA, n) {
var totalVectors = matrixA.length;
for (var i = 0; i < totalVectors; i++) {
var tempVector = matrixA[i];
for (var j = 0; j < i; j++) {
var dotProd = dot(matrixA[i], matrixA[j], n);
var toSubtract = multiply(dotProd, matrixA[j], n);
tempVector = subtract(tempVector, toSubtract, n);
}
var nrm = norm(tempVector, n);
matrixA[i] = multiply(1 / nrm, tempVector, n);
}
}
/*
* Example usage:
* var myMatrix = [[1,0,0],[2,3,0],[5,4,7]];
* gramSchmidt(myMatrix, 3);
* ==> myMatrix now equals [[1,0,0],[0,1,0],[0,0,1]]
* 3 here equals the number of dimensions per vector
*/
/* Simple vector arithmetic */
function subtract(vectorX, vectorY, n) {
var result = new Array(n);
for (var i = 0; i < n; i++)
result[i] = vectorX[i] - vectorY[i];
return result;
}
function multiply(scalarC, vectorX, n) {
var result = new Array(n);
for (var i = 0; i < n; i++)
result[i] = scalarC * vectorX[i];
return result;
}
function dot(vectorX, vectorY, n) {
var sum = 0;
for (var i = 0; i < n; i++)
sum += vectorX[i] * vectorY[i];
return sum;
}
function norm(vectorX, n) {
return Math.sqrt(dot(vectorX, vectorX, n));
}
Note that the algorithm above computes the Gram-Schmidt orthogonalization, which is the matrix [e1 | e2 | ... | en], not the QR factorization!

Categories