Put together the words that are made of exactly the same letters.
What to build
A program that invents a key for each word, so that words which belong together share a key.
Requirements
- Read a line of words.
- Group words that are anagrams of each other. Repeated words go in the same group.
- Print one group per line, with its words separated by single spaces.
- Keep the groups in the order their first word appeared, and the words in each group in input order.
Input
One line of lower-case words separated by single spaces.
Output
One line per group.
Constraints
There are from 1 to 200 words, each of up to 20 letters.
Example
Input:
listen silent enlist cat act
Output:
listen silent enlist
cat act
Why it works
Sorting the letters gives every anagram the same text, so the hard question "are these two related?" turns into a simple lookup. A Map keeps the groups in the order they were first created.
Examples
Example 1 · Input
listen silent enlist cat act
Expected output
listen silent enlist cat act
Example 2 · Input
abc
Expected output
abc
Hints
Hint 1
Two words are anagrams when their letters, once sorted, are the same.
Hint 2
word.split("").sort().join("") gives a key for each word.
Hint 3
A Map from key to a list of words keeps the groups in first-seen order.
Solution
Show one correct solution (try it yourself first)
const words = prompt().split(" ");
const groups = new Map();
for (const word of words) {
const key = word.split("").sort().join("");
if (!groups.has(key)) {
groups.set(key, []);
}
groups.get(key).push(word);
}
for (const group of groups.values()) {
console.log(group.join(" "));
}