数组字符串的字谜

Anagram of strings of arrays

这个程序只能处理一个单词,但我想传递一组字符串(多个单词)。

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

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

我希望它能为此工作。

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;
}

因为您已经有了一个接受 1 个字符串的方法,为什么不为数组中的每个字符串调用它,然后使用 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)