把这段代码从matlab转换为c#%交叉变换 %输入变量:pop:父代种群,pc:交叉的概率 %输出变量:newpop:交叉后的种群 function [new_pop] = crossover(pop, pc) [px,~] = size(pop); % 判断路径点数是奇数或偶数 parity = mod(px, 2); new_pop = {}; for i = 1:2:px-1 singal_now_pop = pop{i, 1}; singal_next_pop = pop{i+1, 1}; [lia, lib] = ismember(singal_now_pop, singal_next_pop); [~, n] = find(lia == 1); [~, m] = size(n); if (rand < pc) && (m >= 3) % 生成一个2-m-1之间的随机数 r = round(rand(1,1)*(m-3)) +2; crossover_index1 = n(1, r); crossover_index2 = lib(crossover_index1); new_pop{i, 1} = [singal_now_pop(1:crossover_index1), singal_next_pop(crossover_index2+1:end)]; new_pop{i+1, 1} = [singal_next_pop(1:crossover_index2), singal_now_pop(crossover_index1+1:end)]; else new_pop{i, 1} =singal_now_pop; new_pop{i+1, 1} = singal_next_pop; end if parity == 1 new_pop{px, 1} = pop{px, 1}; end end
时间: 2023-06-17 20:06:54 浏览: 106
以下是C#代码实现:
```csharp
public List<List<int>> Crossover(List<List<int>> pop, double pc)
{
int px = pop.Count;
int parity = px % 2;
List<List<int>> new_pop = new List<List<int>>();
for (int i = 0; i < px - 1; i += 2)
{
List<int> singal_now_pop = new List<int>(pop[i]);
List<int> singal_next_pop = new List<int>(pop[i + 1]);
IEnumerable<int> common = singal_now_pop.Intersect(singal_next_pop);
List<int> n = new List<int>();
foreach (int c in common)
{
int index = singal_now_pop.IndexOf(c);
if (index >= 0)
{
n.Add(index);
}
}
if ((new Random().NextDouble() < pc) && (n.Count >= 3))
{
int r = new Random().Next(2, n.Count - 1);
int crossover_index1 = n[r];
int crossover_index2 = singal_next_pop.IndexOf(singal_now_pop[crossover_index1]);
List<int> child1 = new List<int>(singal_now_pop.GetRange(0, crossover_index1));
child1.AddRange(singal_next_pop.GetRange(crossover_index2 + 1, singal_next_pop.Count - crossover_index2 - 1));
List<int> child2 = new List<int>(singal_next_pop.GetRange(0, crossover_index2));
child2.AddRange(singal_now_pop.GetRange(crossover_index1 + 1, singal_now_pop.Count - crossover_index1 - 1));
new_pop.Add(child1);
new_pop.Add(child2);
}
else
{
new_pop.Add(singal_now_pop);
new_pop.Add(singal_next_pop);
}
}
if (parity == 1)
{
new_pop.Add(pop[px - 1]);
}
return new_pop;
}
```
注意,在C#中,需要使用`List<List<int>>`来表示二维数组。另外,C#中的随机数生成需要使用`System.Random`类,而不是`rand`函数。`Intersect`方法可以用来获取两个列表的交集,而`GetRange`方法可以用来获取列表的一部分。
阅读全文