JavaScript中的排列

问题描述 投票:2回答:3

这是我的问题:

对于给定的句子,查找给定字符集的出现次数。选择过滤后的单词并生成排列。 (句子和字符集只能有大写字母)

显示选定的单词和排列

例:

输入

sentence = "THIS IS AN ISSUE FROM JOHN" 
word = "IS"

输出:

{ 
  words: ["THIS", "IS", "ISSUE"], 
  permutations: [["THIS","IS","ISSUE"], ["IS","THIS","ISSUE"], ["ISSUE","THIS","IS"], ["THIS","ISSUE","IS"], ["IS","ISSUE","THIS"], ["ISSUE","IS","THIS"]] 
}

并且应满足以下标准:

  1. 返回类型应该是一个对象。
  2. getPermutations("THIS IS AN ISSUE FROM GIHAN", "IS") 应该返回: { "word": ["THIS","IS","ISSUE"], "permutations": [["THIS","IS","ISSUE"], ["IS","THIS","ISSUE"], ["ISSUE", "THIS", "IS"], ["THIS", "ISSUE", "IS"], ["IS", "ISSUE", "THIS"], ["ISSUE","IS","THIS"]] }
  3. 答案应对任何给定的输入有效。

这是我的代码:

function getPermutations(sentence, word) {
  var words = sentence.split(" ");
  var x = words[0] +" "+ words[1] +" "+ words[3];
  var inputArray = x.split(" ");
  var permutations = inputArray.reduce(function permute(res, item, key, arr) {
    return res.concat(arr.length > 1 && arr.slice(0, key).concat(arr.slice(key + 1)).reduce(permute, []).map(function(perm) { return [item].concat(perm); }) || item);

}, []);

  var output = { words: words,permutations :  permutations}; 


  return output;
}

console.log(getPermutations("THIS IS AN ISSUE FROM JOHN", "IS"));

有一些错误,所以它与此混淆。有什么建议吗?

javascript permutation
3个回答
0
投票

使用正则表达式(/\w*IS\w*/g)和match提取包含指定字符的单词。使用Set删除重复项,然后使用reduceflatmapfilter生成该数组的排列:

function permutations(arr) {
  return (arr.length === 1) ? arr : arr.reduce((acc, x, i) => {
    const remaining = [...new Set(arr)].filter((y, j) => i !== j);
    return [...acc, ...permutations(remaining).map(a => [x, a].flat())];
  }, []);
}

function getPermutations(str, word) {
  const words = [...new Set(
    (word && (str || '').match(new RegExp(`\\w*${word}\\w*`, 'g'))) || [])
  ];
  return { words, permutations: permutations(words) };
}

console.log(getPermutations('THIS IS AN ISSUE FROM JOHN', 'IS'));
console.log(getPermutations('THIS IS', 'IS'));
console.log(getPermutations('', 'IS'));
console.log(getPermutations(null, 'IS'));
console.log(getPermutations('', ''));
console.log(getPermutations('', null));

3
投票

你可以在每个空间拆分单词,filter只包含那些指定了word的单词。然后从单词数组中获取每个排列

function getPermutations(sentence, word) {
  const matches = sentence.split(" ").filter(w => w.includes(word));
  
  let permutations = permute(matches);
  
  return {
    word: matches,
    permutations
  }
}

/*
  https://stackoverflow.com/a/37580979/3082296
*/
function permute(permutation) {
  var length = permutation.length,
    result = [permutation.slice()],
    c = new Array(length).fill(0),
    i = 1,
    k, p;

  while (i < length) {
    if (c[i] < i) {
      k = i % 2 && c[i];
      p = permutation[i];
      permutation[i] = permutation[k];
      permutation[k] = p;
      ++c[i];
      i = 1;
      result.push(permutation.slice());
    } else {
      c[i] = 0;
      ++i;
    }
  }
  return result;
}

console.log(getPermutations("THIS IS AN ISSUE FROM GIHAN", "IS"))

注意:如果您使用逗号(,)或句点(。)等标点符号分隔单词,则在正则表达式中使用单词边界:

const matches = sentence.match(/\b(\w+)\b/g) 

参考:数组项代码的排列采取from this answer


0
投票
function getPermutations(sentence,word) {        
    var pieces = sentence.split(" ");
    var valid_pcs = [];
    var combinations = [[]];
    var combinations_no_duplicates = [];
    for (var i = 0; i < pieces.length; i++) {
        if (pieces[i].indexOf(word) !== -1)
            valid_pcs.push(pieces[i]);
    }
    for (var i = 0; i < valid_pcs.length; i++) {
        tmp = [];
        for (var j = 0; j < combinations.length; j++) {
            for (var k = 0; k < valid_pcs.length; k++)
                tmp.push(combinations[j].concat(valid_pcs[k]));
        }
        combinations = tmp;
    }
    for (var i = 0; i < combinations.length; i++) {
        const distinct = [...new Set(combinations[i])];
        if (distinct.length == combinations[i].length)
            combinations_no_duplicates.push(combinations[i]);
    }
    return {"word":valid_pcs,"permutations":combinations_no_duplicates};
}

console.log(getPermutations("THIS IS AN ISSUE FROM JOHN", "IS"));
© www.soinside.com 2019 - 2024. All rights reserved.