Search code examples
javascriptarraysstringanagram

Anagram of strings of arrays


This program is working for a single word but I want to pass an array of strings(more than one word).

let output = getAnagrams("CATCH"); //it is working for this

let output = getAnagrams(["catch", "Priest", "Monkey", "Bruise"]); 

I want it to work for this.

function swap(chars, i, j) {
    var tmp = chars[i];
    chars[i] = chars[j];
    chars[j] = tmp;
}
function getAnagrams(input) {
    let newInput = input.toString().toLowerCase();
    console.log(newInput);
    var counter = [],
        anagrams = [],
        chars = newInput.split(''),
        length = chars.length,
        i;

    for (i = 0; i < length; i++) {
        counter[i] = 0;
    }

    anagrams.push(newInput);
    i = 0;
    while (i < length) {
        if (counter[i] < i) {
            swap(chars, i % 2 === 1 ? Counter[i] : 0, i);
            counter[i]++;
            i = 0;
            anagrams.push(chars.join(''));
        } else {
            counter[i] = 0;
            i++;
        }
    }
    // return anagrams;
}

Solution

  • As you already have a method which takes 1 string, why not just call it for each string in your array and then flatten the returning the array using flatMap

    function getAnagrams(input) {
        let newInput = input.toString().toLowerCase();
        var counter = [],
            anagrams = [],
            chars = newInput.split(''),
            length = chars.length,
            i;
    
        for (i = 0; i < length; i++) {
            counter[i] = 0;
        }
    
        anagrams.push(newInput);
        i = 0;
        while (i < length) {
            if (counter[i] < i) {
                swap(chars, i % 2 === 1 ? counter[i] : 0, i);
                counter[i]++;
                i = 0;
                anagrams.push(chars.join(''));
            } else {
                counter[i] = 0;
                i++;
            }
        }
         return anagrams;
    }
    
    function swap(arr,i,j){
      const tmp = arr[i];
      arr[i] = arr[j]
      arr[j] = tmp
    }
    
    const result = ["catch", "Priest", "Monkey", "Bruise"].flatMap(i => getAnagrams(i))
    
    console.log(result)