Skip to content

Instantly share code, notes, and snippets.

@JessicaGreben
Created April 17, 2017 03:41
Show Gist options
  • Save JessicaGreben/a448deed618c671770fcafb01e49e948 to your computer and use it in GitHub Desktop.
Save JessicaGreben/a448deed618c671770fcafb01e49e948 to your computer and use it in GitHub Desktop.
anagram and palindrome algorithms
// Problem 1 - Palindrome
// Write a function that takes a string as an input
// and returns true if the string is the same string forwards
// and backwards
String.prototype.reverse = function() {
return this.split("").reverse().join("");
}
const isPalindrome = function(str) {
if (str.reverse() === str) {
return true;
}
return false;
};
// Problem 2 - Anagram
// Write a function that takes two strings as input and
// returns true if they contain the exact same characters
/**
* @param string str1
* @param string str2
* @return boolean
*/
// Solution 1
const isAnagram = function(str1, str2) {
let sameCharCount;
let stringContainsChar;
if (str1.length !== str2.length) {
return false;
}
for (let i=0; i<str1.length; i++) {
sameCharCount = str2.split(str1[i]).length-1 === str1.split(str1[i]).length-1;
stringContainsChar = str2.indexOf(str1[i]) !== -1;
if (stringContainsChar && sameCharCount) {
return true;
} else {
return false;
}
}
};
// Solution 2
const isAnagram = function(str1, str2) {
let sortedStr1 = str1.split("").sort().join("");
let sortedStr2 = str2.split("").sort().join("");
if (sortedStr1 === sortedStr2) {
return true;
} else {
return false;
}
};
// Problem 3 - Another Anagram
// Write a function that takes a single string as input
// and returns a list of all the permutations of that string.
/**
* @param string word
* @return array
*/
// My first solution - solved with my own brain
// but only returns a portion of all the anagrams so
// its actually broken
var findAllAnagrams = function(word) {
let result = [];
for (let i=0; i<=word.length; i++) {
for (let j=0; j<=word.length; j++) {
flipped = flipLetters(word, i, j);
if (result.indexOf(flipped) === -1) {
result.push(flipped);
}
}
}
return result;
};
var flipLetters = function(string, i, j) {
let tmp = string[i];
let arr = string.split('');
arr[i] = arr[j];
arr[j] = tmp;
return arr.join('');
};
// Solution 2 - had to get help to solve this
const anagrams = function(word) {
let result = [];
if (word.length === 1) {
result.push(word);
return result;
}
for (let i=0; i<word.length; i++) {
let currentChar = word[i];
let remain = word.slice(0, i) + word.slice(i + 1);
let subResult = anagrams(remain);
for (let j=0; j<subResult.length;j++) {
result.push(currentChar + subResult[j]);
}
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment