Identify palindromes in a sentence - javascript

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/

Related

How do you iterate over an array every x spots and replace with letter?

/Write a function called weave that accepts an input string and number. The function should return the string with every xth character replaced with an 'x'./
function weave(word,numSkip) {
let myString = word.split("");
numSkip -= 1;
for(let i = 0; i < myString.length; i++)
{
numSkip += numSkip;
myString[numSkip] = "x";
}
let newString = myString.join();
console.log(newString);
}
weave("weave",2);
I keep getting an infinite loop. I believe the answer I am looking for is "wxaxe".
Here's another solution, incrementing the for loop by the numToSkip parameter.
function weave(word, numToSkip) {
let letters = word.split("");
for (let i=numToSkip - 1; i < letters.length; i = i + numToSkip) {
letters[i] = "x"
}
return letters.join("");
}
Well you need to test each loop to check if it's a skip or not. Something as simple as the following will do:
function weave(word,numSkip) {
var arr = word.split("");
for(var i = 0; i < arr.length; i++)
{
if((i+1) % numSkip == 0) {
arr[i] = "x";
}
}
return arr.join("");
}
Here is a working example
Alternatively, you could use the map function:
function weave(word, numSkip) {
var arr = word.split("");
arr = arr.map(function(letter, index) {
return (index + 1) % numSkip ? letter : 'x';
});
return arr.join("");
}
Here is a working example
Here is a more re-usable function that allows specifying the character used for substitution:
function weave(input, skip, substitute) {
return input.split("").map(function(letter, index) {
return (index + 1) % skip ? letter : substitute;
}).join("");
}
Called like:
var result = weave('weave', 2, 'x');
Here is a working example
You dont need an array, string concatenation will do it, as well as the modulo operator:
function weave(str,x){
var result = "";
for(var i = 0; i < str.length; i++){
result += (i && (i+1)%x === 0)?"x":str[i];
}
return result;
}
With arrays:
const weave = (str,x) => str.split("").map((c,i)=>(i&&!((i+1)%x))?"x":c).join("");
You're getting your word greater in your loop every time, so your loop is infinite.
Try something like this :
for(let k = 1; k <= myString.length; k++)
{
if(k % numSkip == 0){
myString[k-1]='x';
}
}
Looking at what you have, I believe the reason you are getting an error is because the way you update numSkip, it eventually becomes larger than
myString.length. In my code snippet, I make i increment by numSkip which prevents the loop from ever executing when i is greater than myString.length. Please feel free to ask questions, and I will do my best to clarify!
JSFiddle of my solution (view the developer console to see the output.
function weave(word,numSkip) {
let myString = word.split("");
for(let i = numSkip - 1; i < myString.length; i += numSkip)
{
myString[i] = "x";
}
let newString = myString.join();
console.log(newString);
}
weave("weave",2);
Strings are immutable, you need a new string for the result and concat the actual character or the replacement.
function weave(word, numSkip) {
var i, result = '';
for (i = 0; i < word.length; i++) {
result += (i + 1) % numSkip ? word[i] : 'x';
}
return result;
}
console.log(weave("weave", 2));
console.log(weave("abcd efgh ijkl m", 5));
You can do this with fewer lines of code:
function weave(word, numSkip) {
word = word.split("");
for (i = 0; i < word.length; i++) {
word[i] = ((i + 1) % numSkip == 0) ? "x" : word[i];
}
return word.join("");
}
var result = weave("weave", 2);
console.log(result);

Using Modulus to loop through

I've been stuck on this last part of my assignment for the longest time. I'm trying to loop through the alphabet using modulus. delta is the number of letters you have to move forward or backwards to get the real letter. SO if given getchars("H",-2), the function is supposed to return F. A problem arises however if the chars.charAt(chars.getIndexOf(data.charAt(i))) ever equals a number less than 0. I want to be able to give my function ("A", -1) or any negative number and have it return "Z".
This is an assignment for class so if possible please keep it to just modulus. I've been working on this last part for like 2 hours now.
function getChars(data,delta)
{
var chars;
var i;
var foundAt;
var newString;
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
data = data.toUpperCase();
delta = Math.min(chars.length, delta);
i = 0;
newString = "";
while (i < data.length)
{
if(delta <= 0)
{
foundAt = (chars.indexOf(data.charAt(i)) + delta) ;window.alert(foundAt)
//newString = newString + chars.charAt(foundAt);
//i = i + 1;
}
else if((chars.indexOf(data.charAt(i)) < 0))
{
foundAt = data.charAt(i);
newString = newString + foundAt;
i = i + 1;
}
else
{
foundAt = ((chars.indexOf(data.charAt(0 + i)) + delta)) % chars.length;window.alert(foundAt);
newString = newString + chars.charAt(foundAt);window.alert(newString);
i = i + 1;
}
}
//return newString;
}
To be flexible, you can use i = chars.length - 1; and first after that do the found at.
You have to use you own modulus function :
function modulus(n,m) {
return ((n%m)+m)%m;
};
With your following code :
function getChars(data,delta)
{
var chars;
var i;
var foundAt;
var newString;
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
data = data.toUpperCase();
i = 0;
newString = "";
while (i < data.length)
{
newString += chars.charAt(modulus(chars.indexOf(data[i])+delta,26))
i++;
}
return newString;
}

all valid combinations of n-pair of parenthesis

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 ())(()

how to increment the value of a char in Javascript

How do I increment a string "A" to get "B" in Javascript?
function incrementChar(c)
{
}
You could try
var yourChar = 'A'
var newChar = String.fromCharCode(yourChar.charCodeAt(0) + 1) // 'B'
So, in a function:
function incrementChar(c) {
return String.fromCharCode(c.charCodeAt(0) + 1)
}
Note that this goes in ASCII order, for example 'Z' -> '['. If you want Z to go back to A, try something slightly more complicated:
var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
function incrementChar(c) {
var index = alphabet.indexOf(c)
if (index == -1) return -1 // or whatever error value you want
return alphabet[index + 1 % alphabet.length]
}
var incrementString = function(string, count){
var newString = [];
for(var i = 0; i < string.length; i++){
newString[i] = String.fromCharCode(string[i].charCodeAt() + count);
}
newString = newString.join('');
console.log(newString);
return newString;
}
this function also can help you if you have a loop to go through

Insert dashes into a number

Any ideas on the following? I want to input a number into a function and insert dashes "-" between the odd digits. So 4567897 would become "456789-7". What I have so far is to convert the number into a string and then an array, then look for two odd numbers in a row and use the .splice() method to add the dashes where appropriate. It does not work and I figure I may not be on the right track anyway, and that there has to be a simpler solution.
function DashInsert(num) {
var numArr = num.toString().split('');
for (var i = 0; i < numArr.length; i++){
if (numArr[i]%2 != 0){
if (numArr[i+1]%2 != 0) {
numArr.splice(i, 0, "-");
}
}
}
return numArr;
}
The problem is you're changing the thing you're iterating over. If instead you maintain a separate output and input...
function insertDashes(num) {
var inStr = String(num);
var outStr = inStr[0], ii;
for (ii = 1; ii < inStr.length; ii++) {
if (inStr[ii-1] % 2 !== 0 && inStr[ii] % 2 !== 0) {
outStr += '-';
}
outStr += inStr[ii];
}
return outStr;
}
You can try using regular expressions
'4567897'.replace(/([13579])(?=[13579])/g, '$1-')
Regex Explained
So, we find an odd number (([13579]) is a capturing group meaning we can use it as a reference in the replacement $1) ensure that it is followed by another odd number in the non-capturing positive lookahead ((?=[13579])) and replace the matched odd number adding the - prefix
Here is the function to do it:
function dashes(number){
var numString = '';
var numArr = number.toString().split('');
console.log(numArr);
for(i = 0; i < numArr.length; i++){
if(numArr[i] % 2 === 1 && numArr[i+1] % 2 === 1){
numString += numArr[i] + '-';
}else{
numString += numArr[i];
}
}
console.log(numString);
}
dashes(456379);
Tested and everything.
Edit: OrangeDog's answer was posted earlier (by nearly a full half hour), I just wanted to make an answer which uses your code since you're almost there.
Using another array instead of splicing into one you were looping through (this happens to return a string using join):
var num = 4567897;
function DashInsert(num) {
var numArr = num.toString().split('');
var len = numArr.length;
var final = [];
for (var i = 0; i < len; i++){
final.push(numArr[i]);
if (numArr[i]%2 != 0){
if (i+1 < len && numArr[i+1]%2 != 0) {
final.push("-")
}
}
}
return final.join("");
}
alert(DashInsert(num));
function dashInsert(str) {
var arrayNumbers = str.split("");
var newString = "";
for (var i = 0; i < arrayNumbers.length; i++){
if(arrayNumbers[i] % 2 === 1 && arrayNumbers[i + 1] % 2 === 1){
newString = newString + arrayNumbers[i] + "-";
} else {
newString = newString + arrayNumbers[i];
}
}
return newString;
}
var result = dashInsert("3453246");
console.log(result);

Categories

Resources