有时列表不会初始化

本文关键字:初始化 列表 | 更新日期: 2023-09-27 18:33:59

已解决:我自己想通了。我在 2 天内无法选择答案。谢谢大家!

我有这个奇怪的错误。有时我的列表是 0,当我看不出原因时。每次我单步执行调试器时,它都可以工作。这让我发疯。请帮忙!顺便说一下,这是旅行销售员分支和绑定。

 public static BSSFPair generateBSSF(ref City[] Cities, int numberOfTrials)
    {
        int n = Cities.Length;
        //Declare variable for updating.
        double minCostOfBSSF = double.PositiveInfinity;
        List<int> minRandomCityOrder = new List<int>();
        //Try many random paths, and keep track of the minimum-cost path. Then select the minimum-cost path as the BSSF.
        for (int iteration = 0; iteration < numberOfTrials; iteration++)
        {
            //Choose a random path.
            List<int> randomCityOrder = new List<int>(generateRandomOrderInts(n)); //a list of ints of cities. Each city int only occurs once.
            //Determine cost of route using the TSPSolution class.
            System.Collections.ArrayList cities = new System.Collections.ArrayList(); //a list of City objects
            foreach (int i in randomCityOrder)
            {
                cities.Add(Cities[i]);
            }
            ProblemAndSolver.TSPSolution bssf = new ProblemAndSolver.TSPSolution(cities);
            double costOfBSSF = bssf.costOfRoute();
            //Update the minimums.
            if (costOfBSSF < minCostOfBSSF)
            {
                minCostOfBSSF = costOfBSSF;
                minRandomCityOrder = new List<int>(randomCityOrder);
            }
        }
        //return the path and the cost of the BSSF.
//<---- This is where the method with the bug was called.
        return new BSSFPair(minCostOfBSSF, convertCityListToEdges(minRandomCityOrder)); //<---- THIS IS WHERE THE METHOD WITH THE BUG WAS CALLED.
    }

此方法是发生错误的地方:

    /// <summary>
    /// Converts a list of cities (WITHOUT THE LAST CITY BEING A DUPLICATE OF THE FIRST CITY) to a list of edges
    /// (WITH THE LAST EDGE GOING BACK TO THE START OF THE FIRST EDGE because it wraps around so you can easily draw it).
    /// </summary>
    /// <param name="minRandomCityOrder"></param>
    /// <returns></returns>
    public static List<Edge> convertCityListToEdges(List<int> minRandomCityOrder)
    {
        if(minRandomCityOrder.Count < 2)
        {
//Right here->
            throw new NotImplementedException();  //<------- RIGHT HERE. minRandomCityOrder count is 0. How did that happen?
        }
        int n = minRandomCityOrder.Count;
        //Convert the BSSF path to a list of edges.
        List<Edge> newBssfPath = new List<Edge>();
        int prev = minRandomCityOrder[0];
        for (int i = 1; i < n; i++)
        {
            newBssfPath.Add(new Edge(prev, minRandomCityOrder[i]));
            prev = minRandomCityOrder[i];
        }
        //Add edge from end to start.
        newBssfPath.Add(new Edge(minRandomCityOrder[n - 1], minRandomCityOrder[0]));
        return newBssfPath;
    }

由以下代码调用的实用程序函数。我自己测试过,它永远不会返回空列表。

    /// <summary>
    /// Generate a list of ints in the range [0, (maximum-1)] (Inclusive) in a random order. Each int occurs only once in the list.
    /// </summary>
    /// <param name="maximum"> "maximum" is the upper bound, and is not included in the list.</param>
    /// <returns>the random-ordered list.</returns>
    private static List<int> generateRandomOrderInts(int maximum)
    {
        if (maximum < 1)
        {
            throw new NotImplementedException();
        }
        Random random = new Random();
        List<int> intsToAdd = new List<int>();
        List<int> randomOrderList = new List<int>();
        for (int i = 0; i < maximum; i++)
        {
            intsToAdd.Add(i);
        }
        while (intsToAdd.Count > 0)
        {
            //Returns a random int between 0 and n-1, inclusive.
            int randomInt = random.Next(intsToAdd.Count);
            randomOrderList.Add(intsToAdd[randomInt]);
            intsToAdd.RemoveAt(randomInt);
        }
        return randomOrderList;
    }

有时列表不会初始化

我发现了问题所在。在此方法中:

  public static BSSFPair generateBSSF(ref City[] Cities, int numberOfTrials)
    {
        int n = Cities.Length;
        //Declare variable for updating.
        double minCostOfBSSF = double.PositiveInfinity;
        List<int> minRandomCityOrder = new List<int>();//<--------------here
    ...

它以空开始。问题在于,这假设最小值(初始化为无穷大)将被更新,然后 minRandomCityOrder 将获得一个初始化为它的新列表。但是,如果我随机选择成本为无穷大的路径,那么它将永远不会更新。

所以,这就是修复我的代码的原因:

  public static BSSFPair generateBSSF(ref City[] Cities, int numberOfTrials)
    {
        int n = Cities.Length;
        //Declare variable for updating.
        double minCostOfBSSF = double.PositiveInfinity;
        List<int> minRandomCityOrder = new List<int>(generateRandomOrderInts(n)); //<---fixed
  ...

现在,如果它没有更新到目前为止的最佳解决方案,它不会破坏代码,只会有一个垃圾路径来计算。

我想这种情况true并且您的列表被重置:

//Update the minimums.
if (costOfBSSF < minCostOfBSSF)
{
    minCostOfBSSF = costOfBSSF;
    minRandomCityOrder = new List<int>(randomCityOrder);
}

这并不意味着您正在使用randomCityOrder项数初始化列表,而是该列表具有此初始容量。如果你想拥有这个数量的项目,你可以尝试:

minRandomCityOrder = Enumerable.Range(0, randomCityOrder).ToList();

。但我不知道在你的算法中是否有意义。我只是在展示什么是可能的。