Skip to content

Instantly share code, notes, and snippets.

@vincentpham1991
Last active March 29, 2016 22:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vincentpham1991/67104a415314c00f7885f4c3effc6f6a to your computer and use it in GitHub Desktop.
Save vincentpham1991/67104a415314c00f7885f4c3effc6f6a 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 anagram_finder = function(list) {

  // WRITE SOLUTION HERE...

};

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.

input_list = ['man', 'list', 'acme', 'talk', 'cat', 'beach', 'came', 'tac', 'naan', 'slit', 'act']
var anagram_finder = function(list) {
// WRITE SOLUTION HERE...
var anagram_list = []
for (i = 0; i < list.length; i++){
var word = list[i];
if (anagram_list.indexOf(word) === -1){
var word_split = word.split("").sort().join("");
var add_word = false;
for (j = i + 1; j < list.length; j++){
var next_word = list[j];
var next_word_split = next_word.split("").sort().join("");
if (word_split === next_word_split){
anagram_list.push(next_word);
add_word = true;
}
}
if (add_word === true){
anagram_list.push(word)
}
}
}
return (anagram_list);
};
var output = anagram_finder(input_list);
console.log(output);
// => ['list', 'acme', 'slit', 'cat', 'came', 'tac', 'act']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment