Whats wrong with my palindrome? (javascript) - javascript

I have written this js code for palindrome, I know there are better and more efficient palindrome methods online but I want to know why I am unable to get my palindrome function to work properly?
CODE:
var pal = function(str) {
var len = str.length;
for (var i = 0; i < len; i++) {
var comp1 = str.substring(i, i + 1);
for (var j = len; j > 0; j--) {
var comp2 = str.substring(j - 1, j);
}
if (comp1 != comp2) {
console.log("not palindrome")
break;
} else {
console.log('palindrome')
}
}
}
pal('maddog');
OUTPUT :
palindrome
not palindrome

There are lot of better algorithms to check Palindrome. Let use the similar algorithm that you are using.
We basically use two pointers - left and right, and move to middle at the same time. In the original question, left pointer and right pointer doesn't move at the same time.
Pointers should move like this -
a b c b a
^ ^
a b c b a
^ ^
a b c b a
^
var isPalindrome = function (str) {
for (var i = 0, j = str.length-1; i < j; i++ , j--) {
if (str[i] != str[j]) {
return false;
}
}
return true;
}
console.log('maddog : ' + isPalindrome('maddog'));
console.log('abcba : ' + isPalindrome('abcba'));
console.log('deed : ' + isPalindrome('deed'));
console.log('a : ' + isPalindrome('a'));

Try the following code. It works by dividing the string length by 2, and then iterating up, checking mirroring characters against each other:
var pal = function(str){
var len = str.length;
for(var i = 0; i < Math.floor(len/2); i++){
if(str[i] != str[(len-1)-i]){
return false;
}
}
return true;
}
console.log(pal("bunny"));
console.log(pal("amoreroma"));

The inner loop is totally unnecessary. It does the same thing every time -- it loops through the whole string, starting from the end, repeatedly setting comp2 to the character; when it's done, comp2 always contains the first character. So your function just tests whether every character in the string is the same as the first character.
To test if something is a palindrome, you need to compare each character with the corresponding character from the other end of the string. You don't need two loops for this. You also only need to loop through the first half of the string, not the whole string.
Finally, you should only echo Palindrome at the end of the loop. Inside the loop you only know that one character matches, not all of them.
var pal = function(str) {
var len = str.length;
var half = Math.floor(len / 2);
var isPal = true;
for (var i = 0; i < half; i++) {
var comp1 = str[i];
var comp2 = str[len - i - 1];
if (comp1 != comp2) {
console.log("not palindrome")
isPal = false;
break;
}
}
if (isPal) {
console.log('palindrome')
}
}
pal('maddog');
pal('maddam');

You don't really need the nested loops, you can just loop backwards through the string to invert the string and then compare it to the original string. I updated the Snippet to work.
Before, your code was not inverting the string but rather just iterating through the characters and assigning them to the comp1 and comp1 variables. You need to concatenate the strings in order to build the new string backwards comp = comp + str.substring(j-1, j);
var pal = function(str) {
var len = str.length;
var comp = '';
for (var j = len; j > 0; j--) {
comp = comp + str.substring(j - 1, j);
}
if (str !== comp) {
console.log("not palindrome")
return;
}
console.log('palindrome')
}
pal('arepera');

Related

Perform a merge on two strings

I'm trying to build a collaborative doc editor and implement operational transformation. Imagine we have a string that is manipulated simultaneously by 2 users. They can only add characters, not remove them. We want to incorporate both of their changes.
The original string is: catspider
The first user does this: cat<span id>spider</span>
The second user does this: c<span id>atspi</span>der
I'm trying to write a function that will produce: c<span id>at<span id>spi</span>der</span>
The function I've written is close, but it produces c<span id>at<span i</span>d>spider</span> codepen here
String.prototype.splice = function(start, newSubStr) {
return this.slice(0, start) + newSubStr + this.slice(start);
};
function merge(saved, working, requested) {
if (!saved || !working || !requested) {
return false;
}
var diffSavedWorking = createDiff(working, saved);
var diffRequestedWorking = createDiff(working, requested);
var newStr = working;
for (var i = 0; i < Math.max(diffRequestedWorking.length, diffSavedWorking.length); i++) {
//splice does an insert `before` -- we will assume that the saved document characters
//should always appear before the requested document characters in this merger operation
//so we first insert requested and then saved, which means that the final string will have the
//original characters first.
if (diffRequestedWorking[i]) {
newStr = newStr.splice(i, diffRequestedWorking[i]);
//we need to update the merge arrays by the number of
//inserted characters.
var length = diffRequestedWorking[i].length;
insertNatX(diffSavedWorking, length, i + 1);
insertNatX(diffRequestedWorking, length, i + 1);
}
if (diffSavedWorking[i]) {
newStr = newStr.splice(i, diffSavedWorking[i]);
//we need to update the merge arrays by the number of
//inserted characters.
var length = diffSavedWorking[i].length;
insertNatX(diffSavedWorking, length, i + 1);
insertNatX(diffRequestedWorking, length, i + 1);
}
}
return newStr;
}
//arr1 should be the shorter array.
//returns inserted characters at their
//insertion index.
function createDiff(arr1, arr2) {
var diff = [];
var j = 0;
for (var i = 0; i < arr1.length; i++) {
diff[i] = "";
while (arr2[j] !== arr1[i]) {
diff[i] += arr2[j];
j++;
}
j++;
}
var remainder = arr2.substr(j);
if (remainder) diff[i] = remainder;
return diff;
}
function insertNatX(arr, length, pos) {
for (var j = 0; j < length; j++) {
arr.splice(pos, 0, "");
}
}
var saved = 'cat<span id>spider</span>';
var working = 'catspider';
var requested = 'c<span id>atspi</span>der';
console.log(merge(saved, working, requested));
Would appreciate any thoughts on a better / simpler way to achieve this.

How to reverse a string in a specific way

This is a very specific question and I want to reverse a string in this way however I don't know how to go about it.
What i want to do is take a word lets say 'hello'. olleh
and take the first and last letters and output 'oellh' then doing the same thing for the next two characters so 'e' and 'l' which would then output 'olleh'.
So to summaries this I need to reverse the first and last character and then the same thing for the second characters until i get to the middle character.
This must use a for loop.
reverse('hello');
function reverse(string) {
var character = [];
for (var i = string.length -1; i >= 0; i--) {
character.push(string[i]);
}
console.log(character.join(""));
}
Let me know if this needs further explanation
This might do the trick:
function replaceAt(string, index, character){
return string.substr(0, index) + character + string.substr(index+character.length);
}
function reverse(string) {
var len = string.length;
len = len/2;
var s = string;
for (var i = 0; i < len ; i++)
{
var m = s[string.length-i-1];
var k = s[i];
s = replaceAt(s,i, m);
s = replaceAt(s, string.length-i-1, k);
}
return s;
}
You can easily reverse a string doing:
"hello".split("").reverse().join("")

Return the first word with the greatest number of repeated letters

This is a question from coderbyte’s easy set. Many people asked about it already, but I’m really curious about what’s wrong with my particular solution (I know it’s a pretty dumb and inefficient one..)
Original question:
Have the function LetterCountI(str) take the str parameter being passed and return the first word with the greatest number of repeated letters. For example: "Today, is the greatest day ever!" should return greatest because it has 2 e's (and 2 t's) and it comes before ever which also has 2 e's. If there are no words with repeating letters return -1. Words will be separated by spaces.
My solution works most of the time. But if it seems the last word of the input isn’t valued by my code. For example, for “a bb ccc”, “bb” will be returned instead of “ccc”. But the funny thing here is if the string only contains one word, the result is correct. For example, “ccc” returns “ccc”.
Please tell me where I was wrong. Thank you in advance!
function LetterCountI(str) {
str.toLowerCase();
var arr = str.split(" ");
var count = 0;
var word = "-1";
for (var i = 0; i < arr.length; i++) {
for (var a = 0; a < arr[i].length; a++) {
var countNew = 0;
for (var b = a + 1; b < arr[i].length; b++) {
if(arr[i][a] === arr[i][b])
countNew += 1;
}
if (countNew > count) {
count = countNew;
word = arr[i];
}
}
return word;
}
}
Please find below the workable version of your code:
function LetterCountI(str) {
str = str.toLowerCase();
var arr = str.split(" ");
var count = 0;
var word = "-1";
for (var i = 0; i < arr.length; i++) {
for (var a = 0; a < arr[i].length; a++) {
var countNew = 0;
for (var b = a + 1; b < arr[i].length; b++) {
if (arr[i][a] === arr[i][b])
countNew += 1;
}
if (countNew > count) {
count = countNew;
word = arr[i];
}
}
}
return word;
}
Here is the Java code soln for your problem.
You have returned your answer incorrectly. You should have returned word/Answer/res out of "for loops".
Check my chode here.
public static String StringChallenge( String str) {
String[] arr = str.split(" ");
int count = 0; String res = "-1";
for (int i = 0; i < arr.length ; i++) {
for (int j = 0; j < arr[i].length() ; j++) {
int counter = 0;
for (int k = j + 1; k < arr[i].length() ; k++) {
if(arr[i].charAt(j) === arr[i].charAt(k) )
counter ++;
}
if (counter > count) {
count = counter; res = arr[i];
}
}
return res;
}
}
I think the problem is that you're placing the return statement inside your outermost loop. It should be inside your inner loop.
So you have to place the return statement within the inner loop.
Correct use of return
if (countNew > count) {
count = countNew;
word = arr[i];
}
return word;
}
}
}
You need to move the return word; statement outside of the loop to fix your version.
I also put together another take on the algorithm that relies on a few built in javascript methods like Array.map and Math.max, just for reference. I ran a few tests and it seems to be a few milliseconds faster, but not by much.
function LetterCountI(str) {
var maxCount = 0;
var word = '-1';
//split string into words based on spaces and count repeated characters
str.toLowerCase().split(" ").forEach(function(currentWord){
var hash = {};
//split word into characters and increment a hash map for repeated values
currentWord.split('').forEach(function(letter){
if (hash.hasOwnProperty(letter)) {
hash[letter]++;
} else {
hash[letter] = 1;
}
});
//covert the hash map to an array of character counts
var characterCounts = Object.keys(hash).map(function(key){ return hash[key]; });
//find the maximum value in the squashed array
var currentMaxRepeatedCount = Math.max.apply(null, characterCounts);
//if the current word has a higher repeat count than previous max, replace it
if (currentMaxRepeatedCount > maxCount) {
maxCount = currentMaxRepeatedCount;
word = currentWord;
}
});
return word;
}
Yet another solution in a more functional programming style:
JavaScript
function LetterCountI(str) {
return ((str = str.split(' ').map(function(word) {
var letters = word.split('').reduce(function(map, letter) {
map[letter] = map.hasOwnProperty(letter) ? map[letter] + 1 : 1;
return map;
}, {}); // map of letters to number of occurrences in the word
return {
word: word,
count: Object.keys(letters).filter(function(letter) {
return letters[letter] > 1;
}).length // number of repeated letters
};
}).sort(function(a, b) { // Sort words by number of repeated letters
return b.count - a.count;
}).shift()) && str.count && str.word) || -1; // return first word with maximum repeated letters or -1
}
console.log(LetterCountI('Today, is the greatest day ever!')); // => greatest
Plunker
http://plnkr.co/edit/BRywasUkQ3KYdhRpBfU2?p=preview
I recommend use regular expression: /a+/g to find a list of letter with a key word a.
My example :
var str = aa yyyyy bb cccc cc dd bbb;
Fist, find a list of different word :
>>> ["a", "y", "b", "c", "d"]
Use regular expression for each word in list of different word :
var word = lstDiffWord[1];
var
wordcount = str.match(new RegExp(word+'+','g'));
console.log(wordcount);
>>>>["yyyyy"]
Here is full example: http://jsfiddle.net/sxro0sLq/4/

How can I shortened this?

I am trying to self teach myself programming and started with javascript. To learn more I have been completing challenges to practice and one challenge was to write a script that would determine the first case of the word in a string with the most repeated letters. I was able to complete it with this code I made:
string = "Hey i believe";
string = string.split(" ");
stringarray = [];
longestlength = 0;
for (i = 0; i < string.length; i++) {
stringarray.push(0);
}
for (i = 0; i < string.length; i++) {
if (string[i].length > longestlength) {
longestlength = string[i].length;
longestword = string[i];
}
}
for (x = 0; x < string.length; x++) {
y = 0;
z = 0;
while (z < string[x].length) {
if (string[x].substr(z,1) == string[x].substr(y,1) && z !== y) {
stringarray[x] += 1;
y = string[x].length -1;
}
y++;
if (y == string[x].length) {
z++;
y = z;
}
}
}
if (Math.max.apply(null,stringarray) === 0) {
mostrptltword = -1;
}
else {
mostrptltword = string[stringarray.indexOf(Math.max.apply(null,stringarray))];
}
console.log(mostrptltword);
But to get all the points possible for the challenge it must be completed in less than 10 minutes this took me 25 mins. So my question is am I over complicating things; causing me to write a much longer script than needed? I have read a little bit about things like Regular Expressions and how they can really shortened script lengths and the time it takes to write them would that or maybe another technique of been more useful than all the loops I had to make?
var words = "Heyyyyy I believe".split(' '); // split the words into an array
var values = [], // total of times that a letter appears
k = 0, // 'global' counter. I'm using this to iterate over the values array
heigher = 0, // holds de heigher occurrence of a letter
letter = ""; // the letter that most appears in that word
word = ""; // the word
// iterate over all the words
for(var i = 0; i < words.length; i++) {
// iterate over each letter in each word
for(var j = 0; j < words[i].length; j++) {
// holds the occurrence time
// RegEx: get the word in the position 'i' and check how many times the letter appears on the position [j] appears
values[k] = words[i].match(new RegExp(words[i][j],'g')).length;
// check if the next letter appears more times than the previous one
if(values[k] > heigher) {
// hold the values of interest
heigher = values[k];
letter = words[i][j];
word = words[i];
}
k++;
}
}
console.log("word: " + word + " letter: " + letter + " total: " + heigher);
jsfiddle: http://jsfiddle.net/felipemiosso/FyCHG/
The is commented. Hope it helps :)

Counting vowels in javascript

I use this code to search and count vowels in the string,
a = "run forest, run";
a = a.split(" ");
var syl = 0;
for (var i = 0; i < a.length - 1; i++) {
for (var i2 = 0; i2 < a[i].length - 1; i2++) {
if ('aouie'.search(a[i][i2]) > -1) {
syl++;
}
}
}
alert(syl + " vowels")
Obviously it should alert up 4 vowels, but it returns 3.
What's wrong and how you can simplify it?
Try this:
var syl = ("|"+a+"|").split(/[aeiou]/i).length-1;
The | ensures there are no edge cases, such as having a vowel at the start or end of the string.
Regarding your code, your if condition needs no i2
if('aouie'.search(a[i]) > -1){
I wonder, why all that use of arrays and nested loops, the below regex could do it better,
var str = "run forest, run";
var matches = str.match(/[aeiou]/gi);
var count = matches ? matches.length : 0;
alert(count + " vowel(s)");
Demo
Try:
a = "run forest, run";
var syl = 0;
for(var i=0; i<a.length; i++) {
if('aouie'.search(a[i]) > -1){
syl++;
}
}
alert(syl+" vowels")
First, the split is useless since you can already cycle through every character.
Second: you need to use i<a.length, this gets the last character in the string, too.
The simplest way is
s.match(/[aeiou]/gi).length
You can use the .match to compare a string to a regular expression. g is global which will run through the entire string. i makes the string readable as upper and lower case.
function getVowels(str) {
var m = str.match(/[aeiou]/gi);
return m === null ? 0 : m.length;
}

Categories

Resources