Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //anagram
- //iceman is an anagram of cinema
- /*
- thinking out loud...
- reduce each word to an object.
- problem, JSON stringify doesn't understand order doesn't matter.
- double for loop
- sweep through a word, see if it occurs again.
- splicing things...
- push and splice
- ////////////////////////////////
- condense both words to have no spaces, all lowercase.
- then check that word1 and word2 are equal lengths.
- then we can check to see if these are anagrams.
- split each word to be arrays.
- double for loop
- iterate through word1
- if you find that character in word2, splice it out of word2.
- if it truly was an anagram,
- word2 will just be an empty array.
- */
- function isAnagram(word1, word2) {
- var word1 = word1.toLowerCase().split(' ').join('').split('');
- var word2 = word2.toLowerCase().split(' ').join('').split('');
- if (word1.length !== word2.length) {
- return false;
- }
- for (var i = 0; i < word1.length; i++) {
- for (var j = 0; j < word2.length; j++) {
- if (word1[i] === word2[j]) {
- word2.splice(j, 1);
- }
- }
- }
- return word2.length === 0;
- }
- //console.log('sTring Cheese'.toLowerCase().split(' ').join('').split(''));
- console.log(isAnagram('iceman', 'cinema'));
- console.log(isAnagram('Rocket Boys', 'October Sky'));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement