Want to know if the substring of string is in the another string.
For eg..
var firstString= test123;
var secondString= nest145;
var thirdString= test456;
var fourString= teating456;
Result should be after comparing firstString and secondString
est1 is matched.
Result should be after comparing firstString and thirdString
test is matched.
Result should be after comparing firstString and fourString
No match found.
Limit to check the word-length can be decided.For the above example it is 4
Here is a simple sample, where the matched letters needs to be next after each other.
var firstString = 'test123';
var secondString = 'nest145';
var thirdString = 'test456';
var fourString = 'teating456';
function findMatchedChars(str1, str2, limit) {
var result = '', s1 = str1, s2 = str2;
if (str2.length > str1.length) {
s1 = str2;
s2 = str1;
}
for (var x = 0; x < s1.length; x++) {
if (s1[x] == s2[x]) {
result += s1[x];
} else {
if (result.length > 0 && result.length >= limit) return result;
result = '';
}
}
if (result.length > 0 && result.length >= limit) return result;
return 'No matches';
}
alert(findMatchedChars(firstString,secondString,4));
alert(findMatchedChars(firstString,thirdString,4));
alert(findMatchedChars(firstString,fourString,4));
This is LCS problem with tow string...
LCS
Here is the regex version:
var firstString = 'test123';
var secondString = 'nest145';
var thirdString = 'test456';
var fourString = 'teating456';
function findDups(str1, str2, limit) {
var re = '.*([^\\s]{' + limit + '}).*\\s+.*\\1.*'
var m = (str1 + " " + str2).match(re)
if (m != null) {
alert(m[1])
} else
alert('No matches')
}
findDups(firstString, secondString, 4)
findDups(firstString, thirdString, 4)
findDups(firstString, fourString, 4)
Related
This is project from freecodecamp where a string is encrypt by the values of the letters are shifted by 13 places
All letters will be uppercase. Do not transform any non-alphabetic character (i.e. spaces, punctuation), but do pass them on.
i test numadd by regex numadd is either equal to num+13 or numadd-26. some letter went wrong and do not return an uppercase letter
please someone explain whats wrong
function rot13(str) {
var str2 = '';
var arr1 = []
var arr2 = []
var reg = /[^A-Z]/
// var char
if (str.includes(' ') == false) {
for (let i = 0; i < str.length; i++) {
var char = '';
var numres
let num = str.charCodeAt(i)
// console.log(num)
// var numadd = num + 13;
// if num+13 not uppercase
if (reg.test(num + 13)) {
numres = num - 13
}
// if num+13 is uppercase
else {
numres = num + 13
}
char = String.fromCharCode(numres)
str2 += char
}
console.log(str2);
}
}
rot13("SERRPBQRPNZC");
reg.test(num + 13) checks the textual representation of the number num + 13 (applying implicit type conversion) so it always says True (do not match an uppercase letter) and always is computed numres = num - 13.
Use reg.test(String.fromCharCode(num + 13)) instead as follows:
function rot13(str) {
var str2 = '';
var arr1 = []
var arr2 = []
var reg = /[^A-Z]/
// var char
if (str.includes(' ') == false) {
for (let i = 0; i < str.length; i++) {
var char = '';
var numres
let num = str.charCodeAt(i)
// console.log(num)
// var numadd = num + 13;
// if num+13 not uppercase
// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
if (reg.test(String.fromCharCode(num + 13))) {
numres = num - 13
}
// if num+13 is uppercase
else {
numres = num + 13
}
char = String.fromCharCode(numres)
str2 += char
}
console.log(str2);
}
}
rot13("SERRPBQRPNZC");
function expandedForm(num) {
let len = num.toString().length;
let n = num.toString().split("");
let result = "";
for (let i = 0; i < len; i++) {
result += n[i] + "0".repeat(len -1 -i).join(" + ");
}
return result;
}
What I am trying to do is to separate numbers like this:
1220 = "1000 + 200 + 20"
221 = "200 + 20 + 1"
I have written the code (not the perfect one) where it gets me all the necessary values but I struggle with joining them together with "+". I tried using .join() but it did not work.
.join works on arrays only
function expandedForm(num) {
let len = num.toString().length;
let n = num.toString().split("");
let result = "";
let arr=[];
for (let i = 0; i < len; i++) {
arr[i] = n[i] + '0'.repeat(len-1-i);
console.log(arr[i]);
}
let ans=arr.join('+');
return ans;
}
console.log(expandedForm(1220))
Although there are a variety of approaches, here are some general tips for you:
Probably don't want to output a 0 term unless the input number is exactly 0 (only a leading 0 term is relevant, because it will be the only such term)
str.split('') can also be [...str]
No need to split a string into an array to access a character str.split('')[0] can also be just str[0]
Might want to assert that num is a whole number.
Make sure you provide enough test cases in your question to fully define the behaviour of your function. (How to handle trailing zeros, interstitial zeros, leading zeros, etc. Whether the input can be a string.)
function expandedForm(num) {
const s = num.toString();
const n = s.length - 1;
const result = [...s]
.map((char, index) => char + '0'.repeat(n - index))
.filter((str, index) => !index || +str)
.join(' + ');
return result;
}
console.log(expandedForm(1220));
console.log(expandedForm(221));
console.log(expandedForm(10203));
console.log(expandedForm(0));
console.log(expandedForm(2n**64n));
Join works with an array, not string. It stringifies two subsequent indexes for all indexes and you can decide what to add between them.
function expandedForm(num) { // num = 321
let len = num.toString().length; // len = 3
let n = num.toString().split(""); // [3,2,1]
let result = [];
for (let i = 0; i < len; i++) {
result.push(n[i] + "0".repeat(len -1 -i)); // pushing till result = ['300','20','10']
}
return num + ' = ' + result.join(' + ');
// connection result[0] + ' + ' result[1] + ' + ' result[2]
}
expandedForm(321); // output: "321 = 300 + 20 + 1"
Here's one way of doing it
let num = 221;
function expandedForm(num) {
let len = num.toString().length;
let n = num.toString().split("");
let result = "";
for (let i = 0; i < len; i++) {
let t = "0"
t = t.repeat(len-1-i)
if(result.length > 0){
n[i] !== '0'? result += '+'+ n[i] + t : result
} else {
n[i] !== '0'? result += n[i] + t : result
}
}
return result;
}
console.log(expandedForm(2200))
console.log(expandedForm(num))
below would be my approach in a more mathimatical but clean code that you can adjust to your needs.
let result = parseInt(num / 1000);
return result ;
}
function x100( num ) {
num = num % 1000;
let result = parseInt( num / 100);
return result;
}
function x10(num ) {
num = num % 1000;
num = num % 100;
let result = parseInt(num /10);
return result;
}
function x1( num ) {
num = num % 1000;
num = num % 100;
num = num % 10;
return num
}
num = 12150
console.log(num = `1000 x ${x1000(num)}, 100 x ${x100(num)}, 10 x ${x10(num)}`)```
A lot of solutions I found here are giving true or false after checking if a string is a palindrome. I have a function that checks if a string is a palindrome or not:
function palindrome(myString){
/* remove special characters, spaces and make lowercase*/
var removeChar = myString.replace(/[^A-Z0-9]/ig, "").toLowerCase();
/* reverse removeChar for comparison*/
var checkPalindrome = removeChar.split('').reverse().join('');
/* Check to see if myString is a Palindrome*/
if(removeChar === checkPalindrome){
document.write("<div>"+ myString + " is a Palindrome <div>");
}else{
document.write("<div>" + myString + " is not a Palindrome </div>");
}
}
palindrome("Oh who was it I saw, oh who?")
palindrome("Madam")
palindrome("Star Wars")
But this is not quite what I want. It's just checking if the string is a palindrome or not. I want to update the function so that it identifies all of the palindromes in a sentence instead of giving it true or false. So if there's a sentence like this - "Madam and John went out at noon" It will list the palindromes in that sentence - "Madam, noon"
Any help in this would be appreciated!
function findPalindromes(str, min) {
min = min || 3;
var result = [];
var reg = str.toLowerCase();
var reg = reg.replace(/[^a-z]/g, ''); // remove if you want spaces
var rev = reg.split("").reverse().join("");
var l = reg.length;
for (var i = 0; i < l; i++) {
for (var j = i + min; j <= l; j++) {
var regs = reg.substring(i, j);
var revs = rev.substring(l - j, l - i);
if (regs == revs) {
result.push(regs);
}
}
}
return result;
}
var str1 = "Madam and John went out at noon";
console.log(str1, findPalindromes(str1));
var str2 = "\"Amore, Roma\" and \"There's no 'x' in Nixon\" are palindromes.";
console.log(str2, findPalindromes(str2));
function findPalindromes(sentence) {
const words = sentence.replace(/[^\w\s]/gi, '').split(' ');
const palindromes = words.filter(isPalindrome);
return palindromes;
}
function isPalindrome(word) {
if (word.length <= 0) return false;
word = word.toLowerCase();
for (let i = 0; i < word.length / 2; i++) {
if (word[i] !== word[word.length - 1 - i]) return false;
}
return true;
}
https://jsfiddle.net/ewezbz22/1/
I am learning js now..
I am trying to write a simple js programme..
what I am trying to do is to print all valid combinations of n-pair
of parenthesis(properly opened and closed)
eg (), (()()),(())
i have written the logic can you tell me whether its correct or not
https://jsfiddle.net/e7mcp6xb/
module.exports = Parentheses = (function() {
var _isParenthesesMatch = function(str) {
var parentheses = str.length;
var rightParentheses = '(';
var leftParentheses = ')';
var rightCount = 0;
var leftCount = 0;
for(i=0;i<=str.length;i++){
if(rightParentheses == str.charAt(i))
{
rightCount++;
}
else if(leftParentheses == str.charAt(i))
{
leftCount++;
}
}
if(rightCount == leftCount){
return true;
}
else(rightCount != leftCount){
return false;
}
}
}());
The check is wrong, but You can fix it easily: In each step of the for loop the number of opening parenthesis cannot be smaller than the number of closing ones:
if (rightCount < leftCount)
return false;
The whole function should look like this:
function(str) {
var rightParentheses = '(';
var leftParentheses = ')';
var rightCount = 0;
var leftCount = 0;
for (var i = 0; i <= str.length; i++) {
if (rightParentheses == str.charAt(i))
rightCount++;
else if (leftParentheses == str.charAt(i))
leftCount++;
if (rightCount < leftCount)
return false;
}
return rightCount == leftCount;
}
If You'd like to generate all valid strings, you can use this function:
function nPair(n) {
if (n == 0)
return [""];
var result = [];
for (var i = 0; i < n; ++i) {
var lefts = nPair(i);
var rights = nPair(n - i - 1);
for (var l = 0; l < lefts.length; ++l)
for (var r = 0; r < rights.length; ++r)
result.push("(" + lefts[l] + ")" + rights[r]);
}
return result;
}
// result of nPair(3):
// ["()()()", "()(())", "(())()", "(()())", "((()))"]
Try this, i have modified your code a little bit. Modification and its explanation is marked in comments.
module.exports = Parentheses = (function() {
var _isParenthesesMatch = function(str) {
var parentheses = str.length;
var rightParentheses = '(';
var leftParentheses = ')';
var count=0;
for(i=0;i<str.length;i++){
//this is to check valid combination start always from ( and end with )
if(str.charAt(0)==rightParentheses && str.length-1==leftParentheses)
{
if(rightParentheses == str.charAt(i))
{
count++; //this will calculate how many times rightParentheses is present & increment count by 1
}
else if(leftParentheses == str.charAt(i))
{
count--; //this will simply decrement count to match valid sequence
}
}
if(count==0){
return true;
}
}
}());
Your function is wrong, try checking if left and right parenthesis and balanced:
function isValid(str){
var stripedStr = str.replace(/[^\(\)]+/g, '');
return stripedStr.split('').reduce(function(a, b){
return a > -1 ? b === '(' ? a + 1 : a - 1 : -1;
}, 0) === 0;
}
stripedStr - use replace() to remove any characters that are not ( or ).
split('') - returns an array so we can use reduce.
reduce() - applies a function against an accumulator and each value of the array (from left-to-right) has to reduce it to a single value.
The reduce starts with 0 as initial value and in the reduce function we count parenthesis
(+1 for (, -1 for ) )
Our string is valid if our counter never goes below 0 and we end up with 0.
You can write the reduce function like this too:
function(previousValue, currentValue){
if (previousValue > -1){
if (currentValue === '('){
return previousValue + 1;
} else {
return previousValue - 1;
}
}
return -1;
}
This is equivalent to:
function(a, b){
return a > -1 ? b === '(' ? a + 1 : a - 1 : -1;
}
It is wrong, because your function will return true for this example ))(( or this ())(()
So it I have the string:
var str = "blue,red,green,orange,yellow,brown,black,teal,purple,gold,silver"
How would you replace every 3rd comma with an ! (For example)? It would look something like:
var str = "blue,red,green!orange,yellow,brown!black,teal,purple!gold,silver,white"
After scrapping together some things I found, I came up with this:
var str = "blue,red,green,orange,yellow,brown,black,teal,purple,gold,silver"
function replaceIndex(string, at, repl) {
return string.replace(/\S/g, function(match, u) {
if( u === at ) return repl;
return match;
});
var total_items = str.split(",").length - 1;
var counter = 1;
for (var i = 0; i < str.length; i++){
if (str.charAt(i) == ","){
if (total_items%counter == 0){
replaceIndex(str, i, "},{");
}
counter++;
}
}
}
You can do this with some regex magic:
str = str.replace(/([^,],[^,]*?,[^,]*?),/g, '$1!');
Try
var str = "blue,red,green,orange,yellow,brown,black,teal,purple,gold,silver"
str = str.replace(/(([^,]*,){2}([^,]*)),/g, '$1!')