我正在尝试使用以下过程从两个父数组(交叉)生成一个新的子数组。
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]
我定义的交叉规则是:
- 从中提取一个连续的子集,
parentArr1
并将其插入到一个新childArr
的子集的相同位置。 childArr
用来自子集的元素填充其余位置并保持子集周围parentArr2
元素的顺序。parentArr2
- 不应该有重复。
这是另一个例子:
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