Write palindrome in JavaScript [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
How to write a JavaScript program that returns the largest number-palindrome, which is the product of two prime five-digit numbers and returns the multipliers themselves ?
My head feel empty...

Just for kicks,
if you're looking for an answer, it's 30109 * 33211 = 999949999
if you're looking for an excessively long, slow and generally unoptimized program, here you go:
function prime(n) {
if (n < 2 || n == 4) return false;
if (n < 4) return true;
for (j = 2; j <= Math.sqrt(n); j++) {
if (n % j == 0) return false;
}
return true;
}
function palindrome(n) {
n = String(n);
return n == n.split('').reverse().join('');
}
function f(n) {
primes = [];
for (i = Math.pow(10, n-1); i < Math.pow(10, n) - 1; i++)
if (prime(i)) primes.push(i);
console.log(primes.length, 'primes found');
primes.reverse();
p = a = b = 0;
for (i = 0; i < primes.length; i++) {
// if (i % 100 == 0) console.log(i); // prints a sort of progress (gets faster over time)
for (j = i; j < primes.length; j++) {
c = primes[i];
d = primes[j];
k = c * d;
if (k < p) break;
if (palindrome(k)) {
// console.log('new: ', k); // prints when a new, largest palindrome is found
p = k;
a = c;
b = d;
}
}
}
return [b, a];
}
result = f(prompt('Size of the primes (careful if >4):'));
console.log(result[0], ' * ', result[1], ' = ', result[0] * result[1]);

Related

Count the number of subset with given diff [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 days ago.
Improve this question
getting RangeError error while compiling
error:-
RangeError: Maximum call stack size exceeded
code:-
var dp = new Array(10000);
for (var i = 0; i < dp.length; i++) {
dp[i] = new Array(1001);
}
function countSubsets(v, i, S2, currentSum) {
if (currentSum == S2) {
return 1;
}
if (i >= v.length) {
return 0;
}
if (dp[i][currentSum] != -1) {
return dp[i][currentSum];
}
if (currentSum + v[i] > S2) {
return (dp[i][currentSum] = countSubsets(v, i, S2, currentSum));
} else {
return (dp[i][currentSum] =
countSubsets(v, i + 1, S2, currentSum + v[i]) +
countSubsets(v, i + 1, S2, currentSum));
}
}
function countSub(vp, N, diff) {
let sum = 0;
for (let value in vp) sum += vp[value];
if (sum - diff < 0 || (sum - diff) % 2 == 1) return 0
else return countSubsets(vp, 0, Math.floor((sum - diff) / 2), 0);
}
let N = 5;
arr = [1, 2, 3, 1, 2] ;
let diff = 1;
for (i = 0; i < 1001; i++) {
for (let j = 0; j < 10000; j++) {
dp[i][j] = -1;
}
}
console.log(countSub(arr, N, diff));
I want to run this DP snippet but not able to IDK why seems to me that everything is fine but really need a hand here

How to fill in holes on randomly generated maze? [duplicate]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I understand the "Depth-First" maze geerating algorithm but I need a little help implementing it with Javascript.
Maze Generation at Rosetta Code contains many implementations to generate and show a maze, using the simple Depth-first search algorithm:
Code in JavaScript:
function maze(x,y) {
var n=x*y-1;
if (n<0) {alert("illegal maze dimensions");return;}
var horiz=[]; for (var j= 0; j<x+1; j++) horiz[j]= [];
var verti=[]; for (var j= 0; j<y+1; j++) verti[j]= [];
var here= [Math.floor(Math.random()*x), Math.floor(Math.random()*y)];
var path= [here];
var unvisited= [];
for (var j= 0; j<x+2; j++) {
unvisited[j]= [];
for (var k= 0; k<y+1; k++)
unvisited[j].push(j>0 && j<x+1 && k>0 && (j != here[0]+1 || k != here[1]+1));
}
while (0<n) {
var potential= [[here[0]+1, here[1]], [here[0],here[1]+1],
[here[0]-1, here[1]], [here[0],here[1]-1]];
var neighbors= [];
for (var j= 0; j < 4; j++)
if (unvisited[potential[j][0]+1][potential[j][1]+1])
neighbors.push(potential[j]);
if (neighbors.length) {
n= n-1;
next= neighbors[Math.floor(Math.random()*neighbors.length)];
unvisited[next[0]+1][next[1]+1]= false;
if (next[0] == here[0])
horiz[next[0]][(next[1]+here[1]-1)/2]= true;
else
verti[(next[0]+here[0]-1)/2][next[1]]= true;
path.push(here= next);
} else
here= path.pop();
}
return ({x: x, y: y, horiz: horiz, verti: verti});
}
function display(m) {
var text= [];
for (var j= 0; j<m.x*2+1; j++) {
var line= [];
if (0 == j%2)
for (var k=0; k<m.y*4+1; k++)
if (0 == k%4)
line[k]= '+';
else
if (j>0 && m.verti[j/2-1][Math.floor(k/4)])
line[k]= ' ';
else
line[k]= '-';
else
for (var k=0; k<m.y*4+1; k++)
if (0 == k%4)
if (k>0 && m.horiz[(j-1)/2][k/4-1])
line[k]= ' ';
else
line[k]= '|';
else
line[k]= ' ';
if (0 == j) line[1]= line[2]= line[3]= ' ';
if (m.x*2-1 == j) line[4*m.y]= ' ';
text.push(line.join('')+'\r\n');
}
return text.join('');
}
Code in Java:
public int[][] generateMaze() {
int[][] maze = new int[height][width];
// Initialize
for (int i = 0; i < height; i++)
for (int j = 0; j < width; j++)
maze[i][j] = 1;
Random rand = new Random();
// r for row、c for column
// Generate random r
int r = rand.nextInt(height);
while (r % 2 == 0) {
r = rand.nextInt(height);
}
// Generate random c
int c = rand.nextInt(width);
while (c % 2 == 0) {
c = rand.nextInt(width);
}
// Starting cell
maze[r][c] = 0;
// Allocate the maze with recursive method
recursion(r, c);
return maze;
}
public void recursion(int r, int c) {
// 4 random directions
int[] randDirs = generateRandomDirections();
// Examine each direction
for (int i = 0; i < randDirs.length; i++) {
switch(randDirs[i]){
case 1: // Up
// Whether 2 cells up is out or not
if (r - 2 <= 0)
continue;
if (maze[r - 2][c] != 0) {
maze[r-2][c] = 0;
maze[r-1][c] = 0;
recursion(r - 2, c);
}
break;
case 2: // Right
// Whether 2 cells to the right is out or not
if (c + 2 >= width - 1)
continue;
if (maze[r][c + 2] != 0) {
maze[r][c + 2] = 0;
maze[r][c + 1] = 0;
recursion(r, c + 2);
}
break;
case 3: // Down
// Whether 2 cells down is out or not
if (r + 2 >= height - 1)
continue;
if (maze[r + 2][c] != 0) {
maze[r+2][c] = 0;
maze[r+1][c] = 0;
recursion(r + 2, c);
}
break;
case 4: // Left
// Whether 2 cells to the left is out or not
if (c - 2 <= 0)
continue;
if (maze[r][c - 2] != 0) {
maze[r][c - 2] = 0;
maze[r][c - 1] = 0;
recursion(r, c - 2);
}
break;
}
}
}
/**
* Generate an array with random directions 1-4
* #return Array containing 4 directions in random order
*/
public Integer[] generateRandomDirections() {
ArrayList<Integer> randoms = new ArrayList<Integer>();
for (int i = 0; i < 4; i++)
randoms.add(i + 1);
Collections.shuffle(randoms);
return randoms.toArray(new Integer[4]);
}
Source, demo and some more explanations

I wanna make my code better but don't know how at this point. I'd like someone else's opnion to tell me how can I improve [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 months ago.
Improve this question
So a friend of mine asked if I could do a function that compresses strings. That function compresses a string if one character repeats itself more than four times, like: "abbbbbbcccdddd" will turn into "a#6bccc#4d". I'm noob and I wanna improve. Thank u for who is answering me :).
let text = '92HSSSS9U27888YSGGGGGG28SLKHFKLSPPPPSKWWW'
function compressText(text){
return searchIqualLetters(text)
}
function searchIqualLetters(originalText){
let modifyedText = ''
for(let i = 0; i < originalText.length - 1; i++){
for(let j = i + 1; j < originalText.length; j++){
modifyedText = repeatFourTimes(i, j, originalText)
if(modifyedText !== undefined && modifyedText !== ''){
originalText = modifyedText
}
}
}
return originalText
}
function checkTextModifyed(){
}
function repeatFourTimes(i, j, text){
if(text[i] == text[j] && text[i] == text[j + 1] && text[i] == text[j + 2]){
return getLastIqualLetter(i, j, text)
}
}
function getLastIqualLetter(i, j, text){
let lastIqualLetterPosition = 0
for(let k = 0; text[i] == text[j + k]; k++){
lastIqualLetterPosition = j + k
}
return makeNewText(i, lastIqualLetterPosition, text)
}
function makeNewText(i, lastLetter, text){
let cutedPart = text.slice(i, lastLetter + 1)
let startPart = text.slice(0, i)
let centerPart = '#' + cutedPart.length + cutedPart[0]
let endPart = text.slice(lastLetter + 1, text.length)
return startPart + centerPart + endPart
}
console.log(compressText(text)) // Result: 92H#4S9U27888YS#6G28SLKHFKLS#4PSKWWW
Here's my take on the problem:
function condense(text) {
let count = 0;
let out = "";
text.split("").forEach((el, i, arr) => { // el = current letter, i = index of letter, arr = the input text as an array
if (arr[i + 1] != el) { // if the next letter is not the same as the current one
if (count < 3) {
out += el.repeat(count + 1) // if the sequence is less than 3 letters, then just do it normally
} else {
out += "#" + (count + 1) + el; // else, condense it
}
count = 0; // reset sequence length
} else {
count += 1; // increase count of repeated letter sequence length
}
})
return out;
}
console.log(condense("aaabbbbcdddddee")); // Output: "aaab#4cd#5ee"
console.log(condense('92HSSSS9U27888YSGGGGGG28SLKHFKLSPPPPSKWWW'));
console.log("92H#4S9U27888YS#6G28SLKHFKLS#4PSKWWW (reference)");
Here is my take on it:
const text = '92HSSSS9U27888YSGGGGGG28SLKHFKLSPPPPSKWWW';
function compr(txt){
let cnt=1,arr=[];
txt.split("").reduce((p,c,i)=>{
if(c==p) cnt++;
if(c!=p || i==txt.length-1) {
arr.push(cnt>3?`#${cnt}${p}`:p.repeat(cnt));
cnt=1;
}
return c;
});
return arr.join("");
}
console.log(compr(text));
console.log("92H#4S9U27888YS#6G28SLKHFKLS#4PSKWWW (reference)");
The core of the action happens in the .reduce() loop. Here I compare the current character c with the previous one(p). If it is the same I simply increase the counter cnt otherwise - or in case I have reached the end of the string (i==txt.length-1) - I add the latest group of character in its suitable form to arr and reset cnt to 1. The arr array is eventually .join()ed and returned as the resulting string.

Trying to multiply the first two numbers that results to a particular number, is there way i can do this without using nested loops?

Here is the full solution, please is there much better ways to go about this
the question is getting total number of squares in a box but in the inverse way, for example the normal question is 2,9 and the total number of available squares will be 26. but i was given the question in another way such that 26 will be given and im to find all the possible ways m and n can be arranged so the total number of squares will be the given question, which is 26
The code actually works but i need a faster way to do this.
const n = 26;
function count(m, n) {
if (n < m) {
const temp = n;
n = m;
m = temp;
}
return m * (m + 1) * (2 * m + 1) /
6 + (n - m) * m * (m + 1) / 2;
}
const arr = [];
const len = n + 1;
for (let i = 1; i < len; i++) {
if(i<len/2) {
}
for (let b = 1; b < len; b++) {
if (i === 1) {
arr.push(`${i} ${n}`);
break;
} else if (i === n) {
arr.push(`${n} 1`);
break;
} else {
const sum = count(i, b);
if (sum == n) {
arr.push(`${i} ${b}`);
break;
}
}
}
}
const arrLength = arr.length;
console.log(arrLength); //shows the length of the array
for (let g = 0; g < arrLength; g++) {
console.log(arr[g]); // shows each ways it can be arranged to give 26
}

Compare strings with 'similar' letters [duplicate]

So I have a random javascript array of names...
[#larry,#nicholas,#notch] etc.
They all start with the # symbol. I'd like to sort them by the Levenshtein Distance so that the the ones at the top of the list are closest to the search term. At the moment, I have some javascript that uses jQuery's .grep() on it using javascript .match() method around the entered search term on key press:
(code edited since first publish)
limitArr = $.grep(imTheCallback, function(n){
return n.match(searchy.toLowerCase())
});
modArr = limitArr.sort(levenshtein(searchy.toLowerCase(), 50))
if (modArr[0].substr(0, 1) == '#') {
if (atRes.childred('div').length < 6) {
modArr.forEach(function(i){
atRes.append('<div class="oneResult">' + i + '</div>');
});
}
} else if (modArr[0].substr(0, 1) == '#') {
if (tagRes.children('div').length < 6) {
modArr.forEach(function(i){
tagRes.append('<div class="oneResult">' + i + '</div>');
});
}
}
$('.oneResult:first-child').addClass('active');
$('.oneResult').click(function(){
window.location.href = 'http://hashtag.ly/' + $(this).html();
});
It also has some if statements detecting if the array contains hashtags (#) or mentions (#). Ignore that. The imTheCallback is the array of names, either hashtags or mentions, then modArr is the array sorted. Then the .atResults and .tagResults elements are the elements that it appends each time in the array to, this forms a list of names based on the entered search terms.
I also have the Levenshtein Distance algorithm:
var levenshtein = function(min, split) {
// Levenshtein Algorithm Revisited - WebReflection
try {
split = !("0")[0]
} catch(i) {
split = true
};
return function(a, b) {
if (a == b)
return 0;
if (!a.length || !b.length)
return b.length || a.length;
if (split) {
a = a.split("");
b = b.split("")
};
var len1 = a.length + 1,
len2 = b.length + 1,
I = 0,
i = 0,
d = [[0]],
c, j, J;
while (++i < len2)
d[0][i] = i;
i = 0;
while (++i < len1) {
J = j = 0;
c = a[I];
d[i] = [i];
while(++j < len2) {
d[i][j] = min(d[I][j] + 1, d[i][J] + 1, d[I][J] + (c != b[J]));
++J;
};
++I;
};
return d[len1 - 1][len2 - 1];
}
}(Math.min, false);
How can I work with algorithm (or a similar one) into my current code to sort it without bad performance?
UPDATE:
So I'm now using James Westgate's Lev Dist function. Works WAYYYY fast. So performance is solved, the issue now is using it with source...
modArr = limitArr.sort(function(a, b){
levDist(a, searchy)
levDist(b, searchy)
});
My problem now is general understanding on using the .sort() method. Help is appreciated, thanks.
Thanks!
I wrote an inline spell checker a few years ago and implemented a Levenshtein algorithm - since it was inline and for IE8 I did quite a lot of performance optimisation.
var levDist = function(s, t) {
var d = []; //2d matrix
// Step 1
var n = s.length;
var m = t.length;
if (n == 0) return m;
if (m == 0) return n;
//Create an array of arrays in javascript (a descending loop is quicker)
for (var i = n; i >= 0; i--) d[i] = [];
// Step 2
for (var i = n; i >= 0; i--) d[i][0] = i;
for (var j = m; j >= 0; j--) d[0][j] = j;
// Step 3
for (var i = 1; i <= n; i++) {
var s_i = s.charAt(i - 1);
// Step 4
for (var j = 1; j <= m; j++) {
//Check the jagged ld total so far
if (i == j && d[i][j] > 4) return n;
var t_j = t.charAt(j - 1);
var cost = (s_i == t_j) ? 0 : 1; // Step 5
//Calculate the minimum
var mi = d[i - 1][j] + 1;
var b = d[i][j - 1] + 1;
var c = d[i - 1][j - 1] + cost;
if (b < mi) mi = b;
if (c < mi) mi = c;
d[i][j] = mi; // Step 6
//Damerau transposition
if (i > 1 && j > 1 && s_i == t.charAt(j - 2) && s.charAt(i - 2) == t_j) {
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost);
}
}
}
// Step 7
return d[n][m];
}
I came to this solution:
var levenshtein = (function() {
var row2 = [];
return function(s1, s2) {
if (s1 === s2) {
return 0;
} else {
var s1_len = s1.length, s2_len = s2.length;
if (s1_len && s2_len) {
var i1 = 0, i2 = 0, a, b, c, c2, row = row2;
while (i1 < s1_len)
row[i1] = ++i1;
while (i2 < s2_len) {
c2 = s2.charCodeAt(i2);
a = i2;
++i2;
b = i2;
for (i1 = 0; i1 < s1_len; ++i1) {
c = a + (s1.charCodeAt(i1) === c2 ? 0 : 1);
a = row[i1];
b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c);
row[i1] = b;
}
}
return b;
} else {
return s1_len + s2_len;
}
}
};
})();
See also http://jsperf.com/levenshtein-distance/12
Most speed was gained by eliminating some array usages.
Updated: http://jsperf.com/levenshtein-distance/5
The new Revision annihilates all other benchmarks. I was specifically chasing Chromium/Firefox performance as I don't have an IE8/9/10 test environment, but the optimisations made should apply in general to most browsers.
Levenshtein Distance
The matrix to perform Levenshtein Distance can be reused again and again. This was an obvious target for optimisation (but be careful, this now imposes a limit on string length (unless you were to resize the matrix dynamically)).
The only option for optimisation not pursued in jsPerf Revision 5 is memoisation. Depending on your use of Levenshtein Distance, this could help drastically but was omitted due to its implementation specific nature.
// Cache the matrix. Note this implementation is limited to
// strings of 64 char or less. This could be altered to update
// dynamically, or a larger value could be used.
var matrix = [];
for (var i = 0; i < 64; i++) {
matrix[i] = [i];
matrix[i].length = 64;
}
for (var i = 0; i < 64; i++) {
matrix[0][i] = i;
}
// Functional implementation of Levenshtein Distance.
String.levenshteinDistance = function(__this, that, limit) {
var thisLength = __this.length, thatLength = that.length;
if (Math.abs(thisLength - thatLength) > (limit || 32)) return limit || 32;
if (thisLength === 0) return thatLength;
if (thatLength === 0) return thisLength;
// Calculate matrix.
var this_i, that_j, cost, min, t;
for (i = 1; i <= thisLength; ++i) {
this_i = __this[i-1];
for (j = 1; j <= thatLength; ++j) {
// Check the jagged ld total so far
if (i === j && matrix[i][j] > 4) return thisLength;
that_j = that[j-1];
cost = (this_i === that_j) ? 0 : 1; // Chars already match, no ++op to count.
// Calculate the minimum (much faster than Math.min(...)).
min = matrix[i - 1][j ] + 1; // Deletion.
if ((t = matrix[i ][j - 1] + 1 ) < min) min = t; // Insertion.
if ((t = matrix[i - 1][j - 1] + cost) < min) min = t; // Substitution.
matrix[i][j] = min; // Update matrix.
}
}
return matrix[thisLength][thatLength];
};
Damerau-Levenshtein Distance
jsperf.com/damerau-levenshtein-distance
Damerau-Levenshtein Distance is a small modification to Levenshtein Distance to include transpositions. There is very little to optimise.
// Damerau transposition.
if (i > 1 && j > 1 && this_i === that[j-2] && this[i-2] === that_j
&& (t = matrix[i-2][j-2]+cost) < matrix[i][j]) matrix[i][j] = t;
Sorting Algorithm
The second part of this answer is to choose an appropriate sort function. I will upload optimised sort functions to http://jsperf.com/sort soon.
I implemented a very performant implementation of levenshtein distance calculation if you still need this.
function levenshtein(s, t) {
if (s === t) {
return 0;
}
var n = s.length, m = t.length;
if (n === 0 || m === 0) {
return n + m;
}
var x = 0, y, a, b, c, d, g, h, k;
var p = new Array(n);
for (y = 0; y < n;) {
p[y] = ++y;
}
for (; (x + 3) < m; x += 4) {
var e1 = t.charCodeAt(x);
var e2 = t.charCodeAt(x + 1);
var e3 = t.charCodeAt(x + 2);
var e4 = t.charCodeAt(x + 3);
c = x;
b = x + 1;
d = x + 2;
g = x + 3;
h = x + 4;
for (y = 0; y < n; y++) {
k = s.charCodeAt(y);
a = p[y];
if (a < c || b < c) {
c = (a > b ? b + 1 : a + 1);
}
else {
if (e1 !== k) {
c++;
}
}
if (c < b || d < b) {
b = (c > d ? d + 1 : c + 1);
}
else {
if (e2 !== k) {
b++;
}
}
if (b < d || g < d) {
d = (b > g ? g + 1 : b + 1);
}
else {
if (e3 !== k) {
d++;
}
}
if (d < g || h < g) {
g = (d > h ? h + 1 : d + 1);
}
else {
if (e4 !== k) {
g++;
}
}
p[y] = h = g;
g = d;
d = b;
b = c;
c = a;
}
}
for (; x < m;) {
var e = t.charCodeAt(x);
c = x;
d = ++x;
for (y = 0; y < n; y++) {
a = p[y];
if (a < c || d < c) {
d = (a > d ? d + 1 : a + 1);
}
else {
if (e !== s.charCodeAt(y)) {
d = c + 1;
}
else {
d = c;
}
}
p[y] = d;
c = a;
}
h = d;
}
return h;
}
It was my answer to a similar SO question
Fastest general purpose Levenshtein Javascript implementation
Update
A improved version of the above is now on github/npm see
https://github.com/gustf/js-levenshtein
The obvious way of doing this is to map each string to a (distance, string) pair, then sort this list, then drop the distances again. This way you ensure the levenstein distance only has to be computed once. Maybe merge duplicates first, too.
I would definitely suggest using a better Levenshtein method like the one in #James Westgate's answer.
That said, DOM manipulations are often a great expense. You can certainly improve your jQuery usage.
Your loops are rather small in the example above, but concatenating the generated html for each oneResult into a single string and doing one append at the end of the loop will be much more efficient.
Your selectors are slow. $('.oneResult') will search all elements in the DOM and test their className in older IE browsers. You may want to consider something like atRes.find('.oneResult') to scope the search.
In the case of adding the click handlers, we may want to do one better avoid setting handlers on every keyup. You could leverage event delegation by setting a single handler on atRest for all results in the same block you are setting the keyup handler:
atRest.on('click', '.oneResult', function(){
window.location.href = 'http://hashtag.ly/' + $(this).html();
});
See http://api.jquery.com/on/ for more info.
I just wrote an new revision: http://jsperf.com/levenshtein-algorithms/16
function levenshtein(a, b) {
if (a === b) return 0;
var aLen = a.length;
var bLen = b.length;
if (0 === aLen) return bLen;
if (0 === bLen) return aLen;
var len = aLen + 1;
var v0 = new Array(len);
var v1 = new Array(len);
var i = 0;
var j = 0;
var c2, min, tmp;
while (i < len) v0[i] = i++;
while (j < bLen) {
c2 = b.charAt(j++);
v1[0] = j;
i = 0;
while (i < aLen) {
min = v0[i] - (a.charAt(i) === c2 ? 1 : 0);
if (v1[i] < min) min = v1[i];
if (v0[++i] < min) min = v0[i];
v1[i] = min + 1;
}
tmp = v0;
v0 = v1;
v1 = tmp;
}
return v0[aLen];
}
This revision is faster than the other ones. Works even on IE =)

Categories

Resources