Anagrams finder in javascript

2020-05-20 07:10发布

I am supposed to write a program in JavaScript to find all the anagrams within a series of words provided. e.g.: "monk, konm, nkom, bbc, cbb, dell, ledl, llde" The output should be categorised into rows: 1. monk konm, nkom; 2. bbc cbb; 3. dell ledl, llde;

I already sorted them into alphabetical order i.e.: "kmno kmno bbc bbc dell dell" and put them into an array.

However I am stuck in comparing and finding the matching anagram within the array.

Any help will be greatly appreciated.

20条回答
Summer. ? 凉城
2楼-- · 2020-05-20 07:40

Maybe this?

function anagram (array) {
    var organized = {};
    for (var i = 0; i < array.length; i++) {
        var word = array[i].split('').sort().join('');
        if (!organized.hasOwnProperty(word)) {
            organized[word] = [];
        }
        organized[word].push(array[i]);
    }    
    return organized;
}


anagram(['kmno', 'okmn', 'omkn', 'dell', 'ledl', 'ok', 'ko']) // Example

It'd return something like

{
    dell: ['dell', 'ledl'],
    kmno: ['kmno', okmn', 'omkn'],
    ko: ['ok', ko']
}

It's a simple version of what you wanted and certainly it could be improved avoiding duplicates for example.

查看更多
ら.Afraid
3楼-- · 2020-05-20 07:40

My two cents.

This approach uses XOR on each character in both words. If the result is 0, then you have an anagram. This solution assumes case sensitivity.

let first = ['Sower', 'dad', 'drown', 'elbow']
let second = ['Swore', 'add', 'down', 'below']

// XOR all characters in both words
function isAnagram(first, second) {
  // Word lengths must be equal for anagram to exist
  if (first.length !== second.length) {
    return false
  }

  let a = first.charCodeAt(0) ^ second.charCodeAt(0)

  for (let i = 1; i < first.length; i++) {
    a ^= first.charCodeAt(i) ^ second.charCodeAt(i)
  }

  // If a is 0 then both words have exact matching characters
  return a ? false : true
}

// Check each pair of words for anagram match
for (let i = 0; i < first.length; i++) {
  if (isAnagram(first[i], second[i])) {
    console.log(`'${first[i]}' and '${second[i]}' are anagrams`)
  } else {
    console.log(`'${first[i]}' and '${second[i]}' are NOT anagrams`)
  }
}
查看更多
戒情不戒烟
4楼-- · 2020-05-20 07:41

Best and simple way to solve is using for loops and traversing it to each string and then store their result in object.

Here is the solution :-

function anagram(str1, str2) {
    if (str1.length !== str2.length) {
        return false;
    }
    const result = {};
    for (let i=0;i<str1.length;i++) {
        let char = str1[i];
        result[char] = result[char] ? result[char] += 1 : result[char] = 1;
    }

    for (let i=0;i<str2.length;i++) {
        let char = str2[i];
        if (!result[char]) {
            return false;
        }
        else {
            result[char] = -1;
        }
    }
    return true;
}

console.log(anagram('ronak','konar'));

查看更多
Root(大扎)
5楼-- · 2020-05-20 07:42
function isAnagram(str1, str2) {
  var str1 = str1.toLowerCase();
  var str2 = str2.toLowerCase();

  if (str1 === str2)
    return true;

  var dict = {};

  for(var i = 0; i < str1.length; i++) {
    if (dict[str1[i]])
      dict[str1[i]] = dict[str1[i]] + 1;
    else
      dict[str1[i]] = 1;
  }

  for(var j = 0; j < str2.length; j++) {
    if (dict[str2[j]])
      dict[str2[j]] = dict[str2[j]] - 1;
    else
      dict[str2[j]] = 1;
  }

  for (var key in dict) {
    if (dict[key] !== 0) 
      return false;
  }

  return true;
}

console.log(isAnagram("hello", "olleh"));
查看更多
混吃等死
6楼-- · 2020-05-20 07:42
function checkAnagram(str1, str2) {
    str1 = str1.toLowerCase();
    str2 = str2.toLowerCase();
    let sum1 = 0;
    let sum2 = 0;
    for (let i = 0; i < str1.length; i++) {
        sum1 = sum1 + str1.charCodeAt(i);
    }
    for (let j = 0; j < str2.length; j++) {
        sum2 = sum2 + str2.charCodeAt(j);
    }
    if (sum1 === sum2) {
        return "Anagram";
    } else {
        return "Not Anagram";
    }
}
查看更多
啃猪蹄的小仙女
7楼-- · 2020-05-20 07:45

Probably not the most efficient way, but a clear way around using es6

function sortStrChars(str) {
    if (!str) {
        return;
    }
    str = str.split('');
    str = str.sort();
    str = str.join('');
    return str;
}

const words = ["dell", "ledl", "abc", "cba", 'boo'];

function getGroupedAnagrams(words){
    const anagrams = {}; // {abc:[abc,cba], dell:[dell, ledl]}
    words.forEach((word)=>{
        const sortedWord = sortStrChars(word);
        if (anagrams[sortedWord]) {
            return anagrams[sortedWord].push(word);
        }
        anagrams[sortedWord] = [word];
    });
    return anagrams;
}

const groupedAnagrams = getGroupedAnagrams(words);
for(const sortedWord in groupedAnagrams){
    console.log(groupedAnagrams[sortedWord].toString());
}
查看更多
登录 后发表回答