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.
Hi I have an array of numbers and a K number which is the number of numbers on each line. I want to display numbers like this:
+---+---+
|123| 5|
+---+---+
| 6| 14|
+---+---+
so array = [123, 5, 6, 14] and K = 2, and there are pluses and minuses and pipes. The number of minuses is equal to number of digits in biggest number.
How can I write this in Javascript?
I have:
let res = ""
let max = Math.max(null, A)
let digits = max.toString().length;
function line(numPlus, numMinus) {
let string = "";
for (let i = 0; i < numPlus; i++) {
string += "+"
for(let j = 0; j < numMinus; j++) {
string += "-"
}
string += "+"
}
}
line(K+1, digits);
let array = [123, 5, 6, 14];
let k = 2;
let m = Math.max(...(array.map(e => e.toString().length)));
let t = new Array(k+1).fill("+").join("-".repeat(m));
let pa = array.map(e => e.toString().padStart(m, " "));
let str = "";
for (let i = 0; i < array.length/k; i++) {
let s = pa.slice(k*i, k*i+k);
while (s.length < k) s.push(" ".repeat(m));
str += t + "\n|" + s.join("|") + "|\n";
}
console.log(str + t);
Something Like This Maybe
let numbers = [100,25555,60,21,456,789,231,54,2,4,13,6,579,4562156, -5, 0.5, -1.5]
let maxLength = 0;
for(let i = 0; i < numbers.length; i++){
if(maxLength < numbers[i].toString().length){
maxLength = numbers[i].toString().length
}
}
function printDivider(cells){
let row = '+';
for(let i = 0; i < cells; i++){
for(let j = 0; j < maxLength; j++){
row+= '-'
}
row += '+';
}
console.log(row)
}
function printNumberRow(cells){
let row = '|'
for(let i = 0; i< cells; i++){
if(numbers.length !== 0){
let currentNumber = numbers.shift().toString();
currentNumber = currentNumber.padStart(maxLength, ' ');
row+=currentNumber;
}
else{
row+= ''.padStart(maxLength, ' ');
}
row += '|';
}
console.log(row);
}
function printGraph(numbersPerRow){
let maxRows = Math.round(numbers.length / numbersPerRow)
if(numbers.length % numbersPerRow >= 1){
maxRows++;
}
for(let i = 0; i < maxRows; i++){
printDivider(numbersPerRow)
printNumberRow(numbersPerRow)
printDivider(numbersPerRow)
}
}
printGraph(5)
+-------+-------+-------+-------+-------+
| 100| 25555| 60| 21| 456|
+-------+-------+-------+-------+-------+
+-------+-------+-------+-------+-------+
| 789| 231| 54| 2| 4|
+-------+-------+-------+-------+-------+
+-------+-------+-------+-------+-------+
| 13| 6| 579|4562156| -5|
+-------+-------+-------+-------+-------+
+-------+-------+-------+-------+-------+
| 0.5| -1.5| | | |
+-------+-------+-------+-------+-------+
//A simple and effective solution for exact result
import java.util.*;
class Solution {
public void solution(int[] A, int K) {
int maxLength = 0;
ArrayList<Integer> arr = new ArrayList<>();
for(int x :A){
arr.add(x);
}
for(int i = 0; i < A.length; i++){
if(maxLength < Integer.toString(A[i]).length()){
maxLength = Integer.toString(A[i]).length();
}
}
int completeRow = A.length / K;
int iRow = A.length % K;
if(completeRow>0){
printDivider(K, maxLength,arr);
}
else{
printDivider(iRow,maxLength,arr);
}
System.out.println();
for(int i=0;i<completeRow;i++){
printNumberRow(K, maxLength,arr);
System.out.println();
printDivider(K, maxLength,arr);
System.out.println();
}
if(iRow > 0){
printNumberRow(iRow, maxLength,arr);
System.out.println();
printDivider(iRow, maxLength,arr);
System.out.println();
}
}
void printDivider(int cells, int maxLength ,ArrayList<Integer> A){
String row = "+";
for(int i = 0; i < cells; i++){
for(int j = 0; j < maxLength; j++){
row+="-";
}
row += "+";
}
System.out.print(row);
}
public void printNumberRow(int cells,int maxLength, ArrayList A){
String row = "|";
for(int i = 0; i< cells; i++){
if(A.size() != 0){
int num=A.get(0);
A.remove(0);
// String currentNumber = Integer.toString(num);
String aa = "" ;
int intlength = Integer.toString(num).length() ;
for(int j = 0 ; j < maxLength-intlength ; j++ ) {
aa = aa+" " ;
}
aa =aa + Integer.toString(num) ;
row+=aa;
}
// else{
// row+= ''.padStart(maxLength, ' ');
// }
row += '|';
}
System.out.print(row);
}
}
Here is the Java solution. I am just formatting #user17315860 answer.
His answer is correct but not at all ridable.
import java.util.ArrayList;
class Solution {
static void solution(int[] A, int K) {
int maxLength = 0;
ArrayList<Integer> arr = new ArrayList<>();
for (int x : A) {
arr.add(x);
}
for (int i = 0; i < A.length; i++) {
if (maxLength < Integer.toString(A[i]).length()) {
maxLength = Integer.toString(A[i]).length();
}
}
int completeRow = A.length / K;
int iRow = A.length % K;
if (completeRow > 0) {
printDivider(K, maxLength, arr);
} else {
printDivider(iRow, maxLength, arr);
}
System.out.println();
for (int i = 0; i < completeRow; i++) {
printNumberRow(K, maxLength, arr);
System.out.println();
printDivider(K, maxLength, arr);
System.out.println();
}
if (iRow > 0) {
printNumberRow(iRow, maxLength, arr);
System.out.println();
printDivider(iRow, maxLength, arr);
System.out.println();
}
}
static void printDivider(int cells, int maxLength, ArrayList<Integer> A) {
String row = "+";
for (int i = 0; i < cells; i++) {
for (int j = 0; j < maxLength; j++) {
row += "-";
}
row += "+";
}
System.out.print(row);
}
static public void printNumberRow(int cells, int maxLength, ArrayList<Integer> A) {
String row = "|";
for (int i = 0; i < cells; i++) {
if (A.size() != 0) {
int num = A.get(0);
A.remove(0);
// String currentNumber = Integer.toString(num);
String aa = "";
int intlength = Integer.toString(num).length();
for (int j = 0; j < maxLength - intlength; j++) {
aa = aa + " ";
}
aa = aa + Integer.toString(num);
row += aa;
}
// else{
// row+= ''.padStart(maxLength, ' ');
// }
row += '|';
}
System.out.print(row);
}
public static void main(String[] args) {
int[] A = new int[] { 4, 35, 80, 123, 12345, 44, 8, 5, 24, 3,22,35 };
solution(A, 4);
}
}
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");
}
}
I recently raised a question about implementing sieve of eratosthenes in Javascript on SO and here's the working answer I got:
function sieve(low, high) {
var primeArray = [], ll = Math.sqrt(high), output = [];
for (var i = 2; i <= high; i++) {
primeArray[i] = true;
}
for (var i = 2; i <= ll; i++) {
if (primeArray[i]) {
for (var j = i * i; j <= high; j += i) {
primeArray[j] = false;
}
}
}
for (var i = 2; i <= ll; i++) {
if(primeArray[i]) {
var segmentStart = Math.ceil(low/i) * i;
// need this test to ensure we are not deleting primes
if (primeArray[segmentStart]) segmentStart += i;
for(var j = segmentStart; j <= high; j+=i) {
primeArray[j] = false;
}
}
}
for(var i = low; i <= high; i++) {
if(primeArray[i]) {
output.push(i);
}
}
return output;
}
console.log(sieve(1, 20));
I tried implementing the same in C++
However the end result is quite different.
My C++ program is somehow ignoring the first 2 prime numbers while maintaining 1 as a prime.
Here's the same program in C++
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int low, high;
cout << "Enter lower bound: ";
cin >> low;
cout << "Enter upper bound: ";
cin >> high;
int root = floor(sqrt(high));
int primes[high];
for(int i = 2; i <= high; i++)
{
primes[i] = true;
}
for (int i = 2; i <= root; i++) {
if (primes[i]) {
for (int j = i * i; j <= high; j += i) {
primes[j] = false;
}
}
}
for (int i = 2; i <= root; i++) {
if(primes[i]) {
int segmentStart = ceil(low/i) * i;
if (primes[segmentStart]) segmentStart += i;
for(int j = segmentStart; j <= high; j+=i) {
primes[j] = false;
}
}
}
for(int i = low; i <= high; i++) {
if(primes[i]) {
cout << i;
}
}
return 0;
}
Found the solution.
low/i division operation in int segmentStart = ceil(low/i) * i; was returning an integer and hence it was ignoring results < 1;
I typecasted i as a double to solve this problem like this:
int segmentStart = ceil(low/(double)i) * i;
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!