Skip to main content
100%

MSAN 622 Homework 2: Javascript Anagrams (4/24)

✓ Published0🌍 Public
KKirkHunter
Last edited Mar 29, 2016
Created on Mar 29, 2016

A JavaScript program identifies and displays all words from a predefined array that have at least one anagram elsewhere in the list. The function `anagram_finder` iterates through the input, comparing each word pair using `is_anagram`, which checks character sets for equality. The output, printed to the console, includes words like 'list', 'cat', and 'act' that share rearranged letter groupings, while excluding unique words like 'man'. This example demonstrates basic algorithmic string comparison without external libraries.

AI-generated description

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.

Similar vizzes