Skip to content

Instantly share code, notes, and snippets.

@laras126
Created November 9, 2017 04:02
Show Gist options
  • Save laras126/fbc4c0900e093003fd4a78b00df0d488 to your computer and use it in GitHub Desktop.
Save laras126/fbc4c0900e093003fd4a78b00df0d488 to your computer and use it in GitHub Desktop.
Annotated Algorithm: Check if two strings are an anagram
// Task at hand:
// Write a function that determines if two strings are anagrams.
// Yikes!
// Note: Another way to solve this would be to sort each string alphabetically
// and then see if they are the same...but that's too easy!
const checkIfContains = (char, array) => {
let count = 0;
// Note: this loop could be accomplished with a while loop
// and flag as the one in detectAnagram is, but I think since
// this is the incrementor, it makes more semantic sense to use
// a for loop with [i] as it is more literal and not
// dependent on an abstraction
for (let i = 0; i < array.length; i++) {
if(array[i] === char) {
console.log(`${char} found at index ${i}`);
return true;
} else {
count++;
}
// If count is same as array, exit the loop (using some shorthad syntax here)
if(count === array.length) return false;
}
};
// Function to detect the anagram. Takes arguments for a
// "reference string" (refString) and a "secondary string" (secString)
const detectAnagram = function(refString, secString) {
// If strings are not the same length, they are not anagarams
if (refString.length !== secString.length) return false;
// Note: this loop could be accomplished with a while loop
// and flag as the one in detectAnagram is, but I think since
// this is the incrementor, it makes more semantic sense to use
// a for loop with [i] as it is more literal and not
// dependent on an abstraction
// Base case - if there is one letter, check if they are equal
if(refString.length === 1 && secString.length === 1) {
if(refString[0] === secString[0]) return true;
else return false;
}
// Create a flag for exiting the while loop
let isAnagram = false;
// Use a counter to track iterating through the array
let count = 0;
// While not an anagram (this is swapped in the loop, if it is one)
while(!isAnagram) {
// If the character in refString[count] exists in the second string,
// increment the counter, and check again
// If it doesn't contain the character, it's not an anagram and return false
if(checkIfContains(refString[count], secString)) {
count++;
} else {
return false;
}
// If count has reached length of second string, it's an anagram!
if(count === secString.length) {
isAnagram = true; // Exit the loop
}
}
// Return true if we make it past the while loop!
return true;
};
console.log(detectAnagram('listen', 'silent')); // Returns true
console.log(detectAnagram('jumbo', 'jumbs')); // Returns false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment