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;
}
}
}
Related
I watched a coding train video about the game of life and i tried making a program but it doesn't work. It just generates random squares on the screen as a first image (the starting position) and then just generates another frame with the positive squares (white) disappearing and that's it. Only 2 frames. And it doesn't show an error. Can someone explain why?
function make2D(x, y) {
let arr = new Array(x);
for (let i = 0; i < x; i++) {
arr[i] = new Array(y);
}
return arr;
}
let grid;
let col;
let row;
let resolution = 20;
function setup() {
createCanvas(500, 500);
col = width / resolution;
row = height / resolution;
grid = make2D(col, row);
for (let i = 0; i < col; i++) {
for (let j = 0; j < row; j++) {
grid[i][j] = floor(random(2));
}
}
}
function draw() {
frameRate(1);
background(0);
//drawing
for (let i = 0; i < col; i++) {
for (let j = 0; j < row; j++) {
let x = i * resolution;
let y = j * resolution;
if (grid[i][j]) {
fill(255);
} else {
fill(0);
}
rect(x, y, resolution, resolution);
}
}
//processing
let next = make2D(col, row);
for (let i = 0; i < col; i++) {
for (let j = 0; j < row; j++) {
let nb = calculatePosition(grid, i, j);
//fill(255,0,0);
//text(grid[i][j],i*resolution+6,j*resolution+15);
if (grid[i][j] == 0 && nb == 3) {
next[i][j] == 1;
} else if (grid[i][j] == 1 && (nb > 3 || nb < 2)) {
next[i][j] == 0;
} else {
next[i][j] = grid[i][j];
}
}
}
grid = next;
}
function calculatePosition(grid, x, y) {
let sum = 0;
for (let i = -1; i < 2; i++) {
for (let j = -1; j < 2; j++) {
let cols = (x + i + col) % col;
let rows = (y + j + row) % row;
sum += grid[cols][rows];
}
}
sum -= grid[x][y];
console.log(sum);
return sum;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js"></script>
You accidentally are using equality (==) instead of assignment (=) here
if (grid[i][j] == 0 && nb == 3) {
next[i][j] == 1;
} else if (grid[i][j] == 1 && (nb > 3 || nb < 2)) {
next[i][j] == 0;
} else {
next[i][j] = grid[i][j];
}
You should also move your frameRate call to setup().
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.
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;
}
I want to print the following star pattern using JavaScript:
*****
***
*
***
*****
And I am trying this code, where I am getting off a triangle:
for (i = 3; i >= 1; i--) {
/* Printing spaces */
for (j = 0; j <= 3 - i; j++) {
document.write(" ");
}
/* Printing stars */
k = 0;
while (k != (2 * i - 1)) {
document.write("*");
k++;
}
document.write("<br/>")
}
try this code
after i==1 create new pattern inside it
for (i = 3; i >= 1; i--) {
/* Printing spaces */
for (j = 0; j <= 3 - i; j++) {
document.write(" ");
}
/* Printing stars */
k = 0;
while (k != (2 * i - 1)) {
document.write("*");
k++;
}
document.write("<br/>")
if (i == 1) {
for (t = 2; t <= 3; t++) {
for (j = 0; j <= 3 - t; j++) {
document.write(" ");
}
/* Printing stars */
k = 0;
while (k != (2 * t - 1)) {
document.write("*");
k++;
}
document.write("<br/>")
}
}
}
Try this code:-
In this we use outer loop and inner loop.
var i, j;
//outer loop
for(i=1; i <= 5; i++)
{
//inner loop
for(j=1; j<=i; j++)
{
document.write('*');
}
document.write('<br/>');
}
Iteration:-
i j(Repeat)
1 1
2 2
3 3
4 4
5 5
const n = 5
for (var i = 0; i < n; i++) {
var star = '';
for (var j = 0; j < n - i; j++) {
star += ' ';
}
for (var k = 0; k < i; k++) {
star += '* ';
}
console.log(star);
}
for (var i = 0; i < n; i++) {
var star = '';
for (var b = 0; b < i; b++) {
star += ' ';
}
for (var a = 0; a < n - i; a++) {
star += '* ';
}
console.log(star);
}
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!