我是javascript的新手,我对这种统一的交叉内容非常困惑
我有两个像这样的数组
var ParentOne = ["j1","j2","j3","j4","j5"];
var ParentTwo = ["j3","j4","j2","j1","j4"];
怎么做
我刚刚编写了rand Selection数组
function uniqueRandomInts(upperLimit, amount) {
var possibleNumbers = _.range(upperLimit + 1);
var shuffled = _.shuffle(possibleNumbers);
return shuffled.slice(0, amount);
}
答案 0 :(得分:1)
http://codepen.io/anon/pen/BpBOoB
由于您对js不熟悉,因此链接的codepen是用ES6语法编写的。特别是,它利用解构来帮助进行数组长度重新排序和数组连接以及const
与var
的使用。
特别是,当前接受的答案未涵盖用例。如果父母的身材不一样会怎么样?
通过迭代一个父节点或另一个父节点,如果父节点比另一个父节点短,则第二个父节点的数据将丢失。如果父项比另一项更长,那么两个额外的周期都会被浪费,因为短父上没有匹配的数据,并且错误被引入子数组,每个缺失undefined
数组索引。
在下面的代码中,我们首先对父数组进行排序,因此最短的是第一个。创建子项后,我们将最长父项的剩余数据连接到子数组的末尾。
const parentOne = ['j1','j2','j3','j4','j5'];
const parentTwo = ['j3','j4','j2','j1','j4'];
const parentThree = ['j1','j2','j3','j4','j5', '#', '##', '###'];
const parentFour = ['j3','j4','j2','j1','j4'];
const parentFive = ['j1','j2','j3','j4','j5', '#', '##', '###'];
const parentSix = ['j3','j4','j2','j1','j4'];
// ensure parentOne is the shortest
const fn = (...parents) => {
// ensure shortest parent is first
[parents] = parents[1].length < parents[0].length ? [[parents[1], parents[0]]] : [[parents[0], parents[1]]];
// iterate over shortest parent
let child = parents[0].map((item, i) => parents[Math.round(Math.random())][i]);
// add the remaining elements from the longest array to the child
if (parents[1].length > parents[0].length) {
child = [...child, ...parents[1].slice(parents[0].length)];
}
return child;
}
console.log(fn(parentOne, parentTwo));
console.log(fn(parentThree, parentFour));
console.log(fn(parentFive, parentSix));
console.log('---');
答案 1 :(得分:1)
你可以依赖这样一个事实:两个父阵列都具有相同的长度,然后将随机项映射到一个新数组。
var p1 = ["j1", "j2", "j3", "j4", "j5"],
p2 = ["j3", "j4", "j2", "j1", "j4"],
output = p1.map(function(_, i) {
return [p1, p2][Math.round(Math.random())][i];
});
console.log(output);
ES6
var parent1 = ["j1", "j2", "j3", "j4", "j5"],
parent2 = ["j3", "j4", "j2", "j1", "j4"],
crossover = (p1, p2) => p1.map((_, i) => [p1, p2][Math.round(Math.random())][i]),
output = crossover(parent1, parent2);
console.log(output);
答案 2 :(得分:0)
看起来您想要创建一个输出数组,其中每个元素都是从两个输入数组中的一个中随机选择的。这很简单,可以使用循环和基本的随机和舍入函数。
var ParentOne = ["j1","j2","j3","j4","j5"],
ParentTwo = ["j3","j4","j2","j1","j4"],
parents = [ParentOne, ParentTwo],
output = []; output.length = ParentOne.length;
for (var i = 0; i < output.length; i++) {
output[i] = parents[Math.round(Math.random())][i]
}