I have been developing an anagram generator and facing a challenge in breaking off each new item in the array into a new line. The process involves slicing each array item and iterating through every character.
The desired output should be:
cat, cta, act, atc, tca, tac,
bat, bta, abt, atb, tba, tab,
rat, rta, art, atr, tra, tar,
However, the current output looks like:
cat, cta, act, atc, tca, tac, bat, bta, abt, atb, tba, tab, rat, rta, art, atr, tra, tar, splat, splta, spalt, spatl,...
The code I have implemented so far is as follows:
HTML:
<div id="anagrams"></div>
JS:
var arr = ['cat', 'bat', 'rat', 'splat'];
var allAnagrams = function(arr) {
var anagrams = {};
arr.forEach(function(str) {
var recurse = function(ana, str) {
if (str === '')
anagrams[ana] = 1;
for (var i = 0; i < str.length; i++)
recurse(ana + str[i], str.slice(0, i) + str.slice(i + 1));
};
recurse(' ', str);
});
return Object.keys(anagrams);
}
document.getElementById("anagrams").innerHTML = (allAnagrams(arr));
In order to achieve a new line per array item, I have attempted inserting breaks when the count of characters exceeds the number in the string/array item by modifying the code:
var arr = ['cat', 'bat', 'rat', 'splat'];
var allAnagrams = function(arr) {
var anagrams = {};
arr.forEach(function(str) {
var recurse = function(ana, str) {
if (str === '')
anagrams[ana] = 1;
for (var i = 0; i < str.length; i++) {
recurse(ana + str[i], str.slice(0, i) + str.slice(i + 1));
// check if string length is greater than the count and
// if it is, insert a break between the string
if (i >= str.length - 1) {
recurse(' <br>', str);
}
}
};
recurse(' ', str);
});
return Object.keys(anagrams);
}
document.getElementById("anagrams").innerHTML = (allAnagrams(arr));
Despite implementing these changes, the text still renders across a single line. Am I on the right track with this approach? I also experimented using ana
instead of i
, but realized that I need to utilize i
due to its role as the actual count - is my understanding correct?
You can view a working example on jsfiddle here: https://jsfiddle.net/4eqhd1m4/1/