3

我正在尝试使用以下过程从两个父数组(交叉)生成一个新的子数组。

parentArr1 = [0,1,2,3,4,5,6,7,8,9]
parentArr2 = [9,8,7,6,5,4,3,2,1,0]
parent1Subset = [2,3,4,5]
childArr   = [9,8,2,3,4,5,7,6,1,0]

我定义的交叉规则是:

  1. 从中提取一个连续的子集,parentArr1并将其插入到一个新childArr的子集的相同位置。
  2. childArr用来自子集的元素填充其余位置并保持子集周围parentArr2元素的顺序。parentArr2
  3. 不应该有重复。

这是另一个例子:

parentArr1 = [0,1,2,3,4,5,6,7,8,9]
parentArr2 = [9,8,7,6,5,4,3,2,1,0]
parent1Subset = [7,8,9]
childArr   = [6,5,4,3,2,1,0,7,8,9]

我有很多失败的尝试来做到这一点。这是最接近的尝试。

const parentArr1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const parentArr2 = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0];
let parent1Subset = [2, 3, 4, 5];
let childArr = crossOver(parentArr1, parentArr2, parent1Subset);
// Expected ouput: 9, 8, 2, 3, 4, 5, 7, 6, 1, 0

function crossOver(pArr1, pArr2, pArr1Subset) {
    let _childArr = pArr1Subset.slice(); // suggestion from @r3wt
    for (let i = 0; i < pArr1.length; i++) {
        for (let j = 0; j < (pArr1.length - _childArr.length); j++) {
            if (!_childArr.includes(pArr2[i])) {
                _childArr.splice(i, 0, pArr2[i]);
            }
        }
    }
    return _childArr;
}
console.log("childArr: " + childArr);
// childArr: 9, 8, 7, 6, 2, 3, 4, 5, 1, 0
4

2 回答 2

3

您可以为数组 2 使用另一个索引器并检查实际值是否在交叉数组中。

function crossover(p1, p2, sub) {
    var j = 0;
    return p1.map(i => {
        if (sub.includes(i)) {
            return i;
        }
        while (sub.includes(p2[j])) ++j;
        return p2[j++];
    });
}

console.log(crossover([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [9, 8, 7, 6, 5, 4, 3, 2, 1, 0], [2, 3, 4, 5]).join(' '));
console.log(crossover([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [9, 8, 7, 6, 5, 4, 3, 2, 1, 0], [7, 8, 9]).join(' '));

于 2018-10-26T13:48:20.357 回答
2

希望这应该很容易理解:

    const parentArr1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
    const parentArr2 = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0];
    let parent1Subset = [2, 3, 4, 5];
    
    // First get the start index
    const startIndex = parentArr1.indexOf(parent1Subset[0]);
    
    // Get the start of the childArr
    const childArr = parentArr2.filter(n => parent1Subset.indexOf(n) < 0);
    
    // Splice in the subset
    childArr.splice(startIndex, 0, ...parent1Subset);
    
    console.log(childArr); // [9, 8, 2, 3, 4, 5, 7, 6, 1, 0]

于 2018-10-26T13:57:57.200 回答