Skip to content

Instantly share code, notes, and snippets.

@kirkhunter
Last active March 29, 2016 22:21
Show Gist options
  • Save kirkhunter/b64e867c5ca0c2def15f729b418764cf to your computer and use it in GitHub Desktop.
Save kirkhunter/b64e867c5ca0c2def15f729b418764cf to your computer and use it in GitHub Desktop.
MSAN 622 Homework 2: Javascript Anagrams (4/24)

Due 5pm PST Tuesday 3/29

For this homework you will submit as a fork of this gist

Create a Javascript function to find asociated anagrams in an input list of strings. For the input list, output every string (only once) that has an associated anagram elsewhere in the input list. See an example input and output below:

input_list = ['man', 'list', 'acme', 'talk', 'cat', 'beach', 'came', 'tac', 'naan', 'slit', 'act']

var is_anagram = function(word1, word2) {
	if (word1.length == word2.length) {
		var word1_chars = new Set()
		var word2_chars = new Set()
		for (var i = 0; i < word1.length; i++) {
			word1_chars.add(word1.charAt(i))
			word2_chars.add(word2.charAt(i))
		}
		for (var a of word1_chars) if (!word2_chars.has(a)) return false;
		return true
	}
    return false
};

var anagram_finder = function(input_list) {
	var anagrams = new Set();
	for (var word1 of input_list) {
        if (!anagrams.has(word1)) {
            for (var word2 of input_list) {
            	if (word1 !== word2) { 
            	    if (is_anagram(word1, word2)) {
            		    anagrams.add(word1);
            		    anagrams.add(word2);
            		}
            	}
            }
        }
	}
	return anagrams
};

var output = anagram_finder(input_list);

console.log(output);
// => ['list', 'acme', 'slit', 'cat', 'came', 'tac', 'act']

NOTE: The output words can be in any order

--

This Gist is part of the Spring 2016 University of San Francisco MSAN 622 course: Introduction to Data and Information Visualization (taught by Jonathan Dinu). Course materials are openly available on the class website (with lectures broadcast on Youtube) for the curious autodidact.

list_input = ['man', 'list', 'acme', 'talk', 'cat', 'beach', 'came', 'tac', 'naan', 'slit', 'act']
var is_anagram = function(word1, word2) {
if (word1.length == word2.length) {
var word1_chars = new Set()
var word2_chars = new Set()
for (var i = 0; i < word1.length; i++) {
word1_chars.add(word1.charAt(i))
word2_chars.add(word2.charAt(i))
}
for (var a of word1_chars) if (!word2_chars.has(a)) return false;
return true
}
return false
};
var anagram_finder = function(input_list) {
var anagrams = new Set();
for (var word1 of input_list) {
if (!anagrams.has(word1)) {
for (var word2 of input_list) {
if (word1 !== word2) {
if (is_anagram(word1, word2)) {
anagrams.add(word1);
anagrams.add(word2);
}
}
}
}
}
return anagrams
};
var output = anagram_finder(list_input)
console.log(output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment