Skip to content

Instantly share code, notes, and snippets.

@lachlan
Created September 28, 2012 00:35
Show Gist options
  • Save lachlan/3797288 to your computer and use it in GitHub Desktop.
Save lachlan/3797288 to your computer and use it in GitHub Desktop.

Revisions

  1. lachlan created this gist Sep 28, 2012.
    56 changes: 56 additions & 0 deletions anagrams.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,56 @@
    var fs = require('fs'),
    filename = 'words.txt',
    encoding = 'utf-8';

    fs.readFile(filename, encoding, function(err, data) {
    if (err) throw err;

    var lines = data.split('\n');

    // trim whitespace, and convert to lower case
    for (var i = 0; i < lines.length; i++) {
    lines[i] = lines[i].trim().toLowerCase();
    }

    // remove all duplicate lines
    lines = lines.filter(function(item, index, array) {
    return index == array.indexOf(item);
    });

    // for each word sort the characters alphabetically to create
    // a hash key (all anagrams will generate the same key!)
    // and then append this word to the list of all other words
    // with the same key
    var words = {};

    for (var i = 0; i < lines.length; i++) {
    var word = lines[i];
    if (word !== '') {
    // generate an anagram key by sorting all characters alphabetically
    var key = word.split('').sort().join('');
    // get the list of anagrams that match this word from the hash table
    var list = words[key] || [];
    // add this word to the other anagrams with this key
    list.push(word);
    // assign the list back to the anagram hash table
    words[key] = list;
    }
    }

    // create a list of anagrams from the hash table, exclude words with no anagrams
    var anagrams = [];
    for (var key in words) {
    if (words.hasOwnProperty(key)) {
    if (words[key].length > 1) anagrams.push(words[key]);
    }
    }

    // sort the list by the number of anagrams descending
    anagrams.sort(function(a, b) {
    return (b.length - a.length);
    });

    // print results
    console.log("# anagrams found: " + anagrams.length);
    console.log(anagrams.join("\n"));
    });