2016-08-23 67 views
0

我试图在一种情况下将项目从列表复制到另一个列表。 我有三个列表。第一个列表包含例如10个点的列表,第二个列表包含每个列表的总距离(成本或健身)(10个列表 - > 10个总距离)。在一个条件下从列表中复制项目

下面的图片: 第一个列表包含10个列表(每个列表包含分) - 第二个列表“健身” enter image description here 第三列表是空的,应该充满一个条件的项目。首先,我将第二个列表中的所有值加起来。 以上数字为例:totalFitness = 4847 + 5153 + 5577 + 5324 ...

将第一个列表中的点列表添加到第三个列表中的条件是: 例如: ---->(Fitness [0]/totalFitness)< =比率。

但它不工作,在这里你可以看到我尝试代码:

class RunGA 
{ 
    public static List<List<Point3d>> createGenerations(List<List<Point3d>> firstGeneration, List<int> firstFitness, int generationSize) 
    { 
    List<List<Point3d>> currentGeneration = new List<List<Point3d>>(); 

    int totalFitness; 
    int actualFitness; 
    totalFitness = firstFitness[0] + firstFitness[1]; 
    double ratio = 1/10; 

    for(int k = 2; k < firstFitness.Count; k++) 
    { 
    actualFitness = firstFitness[k]; 
    totalFitness += actualFitness; 
    } 

    for(int i = 0; i < firstFitness.Count; i++) 
    { 
    double selected = firstFitness[i]/totalFitness; 
    if(selected < ratio) 
    { 
    currentGeneration.Add(firstGeneration[i]); 
    } 
    } 
    return currentGeneration; 
    } 
} 

第三列表仍然是空的。如果我将条件更改为:if(selected <= ratio) ,则第一个列表中的整个列表将被复制到第三个列表。但是我想要复制的是:具有“最佳”适应性的点的列表。

这是什么,我做错了?我完全没有线索,我已经尝试了一些变化,但仍然无法正常工作。如果你能认为我是初学者,我将不胜感激。

+1

这听起来像你可能需要学习如何使用调试器来逐步通过你的代码。使用一个好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏离的位置。如果你打算做任何编程,这是一个重要的工具。进一步阅读:** [如何调试小程序](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)** –

+2

LINQ Union,Where,Sum,Aggregate methods肯定会有助于实现这一目标。 – Aybe

回答

0

我发现了另一个解决这个问题的方法。

我仍然有这些数据:

的List1:

  1. ListOfPoints =一个
  2. ListOfPoints = B
  3. ListOfPoints = C
  4. ListOfPoints = d

列表2 :

  1. B的
  2. 健身的健身
  3. 的C健身
  4. 健身d

我想实现是什么:取那些ListOfPoints,其中有最好的健身,把他们成List3。剩下的所有ListOfPoints,放到另一个List4中。

这是我想到的解决方案: 将List1作为Keys和List2作为值放入字典中,并通过LINQ对其进行排序。现在将已排序的Keys转移到List3中。使用for-Loop将排序列表的前半部分放入List4中,将后半部分放入List5中。

这里是我的代码:

List<List<Point3d>> currentGeneration = handoverPopulation.ToList(); 
List<double> currentFitness = handoverFitness.ToList(); 
Dictionary<List<Point3d>, double> dict = new Dictionary<List<Point3d>, double>(); 
foreach(List<Point3d> key in currentGeneration) 
{ 
    foreach(double valuee in currentFitness) 
    { 
    if(!dict.ContainsKey(key)) 
    { 
     if(!dict.ContainsValue(valuee)) 
     {dict.Add(key, valuee);} 
    } 
    } 
} 
var item = from pair in dict orderby pair.Value ascending select pair; 
List<List<Point3d>> currentGenerationSorted = new List<List<Point3d>>(); 
currentGenerationSorted = item.Select(kvp => kvp.Key).ToList(); 

List<List<Point3d>> newGeneration = new List<List<Point3d>>(); 
List<List<Point3d>> newGenerationExtra = new List<List<Point3d>>(); 

int p = currentGenerationSorted.Count/2; 
for(int i = 0; i < p; i++) 
{newGeneration.Add(currentGenerationSorted[i]);} 

for(int j = p; j < currentGenerationSorted.Count; j++) 
{newGenerationExtra.Add(currentGenerationSorted[j]);} 

希望这有助于其他人谁面临同样的问题。

相关问题