longest common substring Multiple Input in JS - javascript

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.

Related

Tic-Tac-Toe in JavaScript with minimax algorithm

I'm trying to implement a Tic-Tac-Toe game using a minimax algorithm for n number of grid size in Javascript.
I have copied the algorithm from geeksforgeeks exactly, but in Javascript the result is not expected and something weird is happening beyond my understanding.
I'm calling the function computerTurn(moves) to make the computer move, and inside it calling the function getBestMove(gridArr, depth, isMax, moves) to get the best move via the minimax algorithm.
In both functions, I'm first checking the empty cell in the grid then assigning it with a specific turn, and then calling the getBestMove function with the new grid. However sometimes the assignment of the grid does not take place and the getBestMove method is called.
Secondly, when I'm printing the grid array in the getBestMove method, it's always printing the same array with only two elements like...
gridArr:- 0:-[1,2,0], 1:-[0,0,0], 2:-[0,0,0]
... and every time the next empty cell is returned as bestMove.
At first, I thought that the same array has been passed to every getBestMove function but when I log the score I'm getting results from the evaluateScore(grid) method (which returns 10 for win, -10 to lose and 0 for draw) returning 10 and -10 as well.
See code below.
In any case, what needs to happen is in each iteration of both functions, when an empty cell is detected the function makes a move i.e assignment of turn into the grid and then pass that grid into the function call.
I'm using 1 for 'X', 2 for '0' and 0 for empty cells in the grid. GRID_LENGTH is the size of row of Tic-Tac-Toe which is 3 for now, and grid is the 2d array for storing X and 0. In the evaluateScore function, WIN_LENGTH is the length to decide winning state, which 3 in this case
This is git repository, which creates the error(s) in question
Thank You all!!
function computerTurn(moves) {
let bestValue = -1000,
bestMove = [];
for (let row = 0; row < GRID_LENGTH; row++) {
for (let col = 0; col < GRID_LENGTH; col++) {
if (grid[row][col] == 0) {
// searching for empty cell
grid[row][col] = 2; // making move
moves++; // increment moves count
let moveValue = getBestMove(grid, 0, false, moves); // checking is this is the best move
moves--;
grid[row][col] = 0;
if (moveValue > bestValue) {
// updating values
bestMove[0] = row;
bestMove[1] = col;
bestValue = moveValue;
}
}
}
}
grid[bestMove[0]][bestMove[1]] = 2;
turn = 'X';
return bestMove;
}
function getBestMove(gridArr, depth, isMax, moves) {
let score = evaluateScore(gridArr);
let arr = gridArr;
if (score == 10 || score == -10) {
return score;
}
if (moves == totalMoves) {
return 0;
}
if (isMax) {
let best = -1000;
for (let i = 0; i < GRID_LENGTH; i++) {
for (let j = 0; j < GRID_LENGTH; j++) {
if (arr[i][j] == 0) {
arr[i][j] = 2;
moves++;
best = Math.max(best, getBestMove(arr, depth + 1, !isMax, moves));
arr[i][j] = 0;
moves--;
}
}
}
return best;
} else {
let best = 1000;
for (let i = 0; i < GRID_LENGTH; i++) {
for (let j = 0; j < GRID_LENGTH; j++) {
if (arr[i][j] == 0) {
arr[i][j] = 1;
moves++;
best = Math.min(best, getBestMove(arr, depth + 1, !isMax, moves));
arr[i][j] = 0;
moves--;
}
}
}
return best;
}
}
function evaluateScore(gridArr) {
let diff = GRID_LENGTH - WIN_LENGTH;
let len = WIN_LENGTH - 1;
for (let i = 0; i < GRID_LENGTH; i++) { // check win for different rows
if (diff == 0) {
let win = true;
for (let j = 0; j < len; j++) {
if (gridArr[i][j] != gridArr[i][j + 1]) {
win = false;
break;
}
}
if (win) {
if (gridArr[i][0] == 1) {
return -10;
} else if (gridArr[i][0] == 2) {
return 10;
}
}
} else {
for (let j = 0; j <= diff; j++) {
let count = 0;
for (let k = j; k < len; k++) {
if ((gridArr[i][k] != gridArr[i][k + 1])) {
count++;
}
if (count == len) {
if (gridArr[i][k] == 1) {
return -10;
} else if (gridArr[i][k] == 2) {
return 10;
}
}
}
}
}
}
for (let i = 0; i < GRID_LENGTH; i++) { // check win for different cols
if (diff == 0) {
let win = true;
for (let j = 0; j < len; j++) {
if (gridArr[j][i] != gridArr[j][i + 1]) {
win = false;
break;
}
}
if (win) {
if (gridArr[0][i] == 1) {
return -10;
} else if (gridArr[0][i] == 2) {
return 10;
}
}
} else {
for (let j = 0; j <= diff; j++) {
let count = 0;
for (let k = j; k < len; k++) {
if ((gridArr[k][i] != gridArr[k][i + 1])) {
count++;
}
if (count == len) {
if (gridArr[k][i] == 1) {
return -10;
} else if (gridArr[k][i] == 2) {
return 10;
}
}
}
}
}
}
let diagonalLength = GRID_LENGTH - WIN_LENGTH;
for (let i = 0; i <= diagonalLength; i++) { // diagonals from left to right
for (let j = 0; j <= diagonalLength; j++) {
let row = i,
col = j;
let win = true;
for (let k = 0; k < len; k++) {
if (gridArr[row][col] != gridArr[row + 1][col + 1]) {
win = false;
break;
}
row++;
col++;
}
if (win) {
if (gridArr[i][j] == 1) {
return -10;
} else if (gridArr[i][j] == 2) {
return 10;
}
}
}
}
let compLen = GRID_LENGTH - diagonalLength - 1;
for (let i = 0; i >= diagonalLength; i--) { // diagonals from right to left
for (let j = GRID_LENGTH - 1; j >= compLen; j--) {
let row = i,
col = j;
let win = true;
for (let k = 0; k < len; k++) {
if (gridArr[row][col] != gridArr[row + 1][col - 1]) {
win = false;
break;
}
row++;
col--;
}
if (win) {
if (gridArr[i][j] == 1) {
return -10;
} else if (gridArr[i][j] == 2) {
return 10;
}
}
}
}
return 0;
}

Game of Life in P5.js

Ok so i tried to make conway's game of life in p5.js and i am stuck in some wierd bug .
function make2DArray(cols, rows) {
let arr = new Array(cols);
for (let i = 0; i < arr.length; i++) {
arr[i] = new Array(rows);
}
return arr;
}
function countNeighbors(grid, x, y) {
let sum = 0;
for (let i = -1; i < 2; i++) {
for (let j = -1; j < 2; j++) {
let col = x + i;
let row = y + i;
if (grid[col][row] === undefined){
sum += grid[col][row];
}
}
}
sum-=grid[x][y]
return sum;
}
let grid;
let next;
let cols;
let rows;
let resolution = 20;
let fr = 15;
function setup() {
createCanvas(600, 400);
frameRate(fr);
cols = width / resolution;
rows = height / resolution;
next = make2DArray(cols, rows);
grid = make2DArray(cols, rows);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
grid[i][j] = floor(random(2));
}
}
}
function draw() {
background(0);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let x = i * resolution;
let y = j * resolution;
if (grid[i][j] == 1) {
fill(0);
stroke(150);
rect(x, y, resolution - 1, resolution - 1);
} else {
fill(255);
stroke(150);
rect(x, y, resolution - 1, resolution - 1);
}
}
}
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let state = grid[i][j];
let neighbors = countNeighbors(grid, i, j);
if (state == 0 && neighbors == 3) {
next[i][j] = 1;
} else if (state == 1 && (neighbors < 2 || neighbors > 3)) {
next[i][j] = 0;
} else {
next[i][j] = state;
}
}
}
grid = next;
}
Soo basically i have function countNeighbors and i think that bug is in there , i tried checking if col and row are i boundaries of array
like this
if (col>-1 && col <grid.length && row>-1 && row < grid[0].length){
//increase sum
}
but its even worse. I am new to js so i figured out that if for example
let x=new Array(10);
//and then when i try this
console.log(c[-1])
//it should give undefined
but program still wont work :(
Thanks!
With a few changes you can make it work:
1) Replace let row = y + i; by let row = y + j; That typo was making most of the counts off.
2) Replace the condition
if (grid[col][row] === undefined){
by
if (0 <= col && col < cols && 0 <= row && row < rows){
The problem with your original condition is that if grid[col] is undefined then grid[col][row] is undefined[row], which doesn't make sense.
3) For consistency sake, add a semicolon to the end of sum-=grid[x][y]
4) Finally, so as to not create an unintended alias, you need to replace grid = next by something like:
for(let i = 0; i < grid.length; i++){
grid[i] = next[i].slice();
}
Alternatively, make next a variable which is local to draw() and place the line let next = make2DArray(cols, rows); to the beginning of draw().

finding number of changes to make 2 strings anagram

I want to find the minimum number of characters of the first string that needs to be changed to enable me to make it an anagram of the second string.
1st problem it always return -1
function anagram(s) {
if (s % 2 == 0) {
var len = s.legnth;
var diff = [];
for (var x = 0; x < len / 2; x++) {
var y = s[x]++;
}
for (var x = len / 2; x < s.legnth; x++) {
var z = s[x]++;
}
y = y.sort().splice(",").tostring();
z = y.sort().splice(",").tostring();
for (var x = 0; i < z.length; x++) {
if (y[x] != z[x]) {
diff.push(y[x]);
}
}
return diff.length;
} else {
return -1;
}
}
function main() {
var q = parseInt(readLine());
for (var a0 = 0; a0 < q; a0++) {
var s = readLine();
var result = anagram(s);
process.stdout.write("" + result + "\n");
}
}

javascript - missing ) after for-loop control

Im trying to solve problem #4 on project Euler,im using a simple for-loop to sift through each element of the array and "missing ) after for-loop control"
Code below
var palidrome = function (num) {
var numstr = (num).toString().split("");
var count = 0;
for (var i = 0, i2 = numstr.length - 1; i < numstr.length / 2 && i2 >= numstr.length / 2; i++, i2--) {
if (numstr[i] !== numstr[i2]) {
return 0;
} else {
if (count == 3) {
return numstr.join("");
}
}
count++;
}
};
for (var i = 999; i >= 100; i--) {
for (var j = 100; j = < i; j++) {
if (palidrome(i * j) !== 0) {
alert(palidrome(i * j));
break;
}
}
}
Thank you for the assistance,much appreciated.
In for loop you have error: j = < i must be j <= i
for (var i = 999; i >= 100; i--) {
for (var j = 100; j <= i; j++) {
if (palidrome(i * j) !== 0) {
alert(palidrome(i * j));
break;
}
}
}

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