Search code examples
c#recursiontraveling-salesman

List reset on every recursion when attempting to permute


I am attempting to generate all the permutations of a list but every time I recurse the list I pass in gets reset back to its original state, what's up with that?

public static void PermuteAndSolve(List<City> cities, int recursionLevel, int Length)
    {
        if (recursionLevel == Length)
        {
            foreach (City city in cities)
            {
                Console.Write(city.name);
            }
            Console.WriteLine("");
        }
        else
        {
            for (int i = recursionLevel; i <= Length; i++)
            {
                swap(cities, recursionLevel, Length);
                PermuteAndSolve(cities, recursionLevel + 1, Length);
                swap(cities, recursionLevel, Length);


            }
        }
    }

I know swap works correctly.


Solution

  • Turns out I'm an idiot and I added the extra swap after the recursion by accident. Real code should read:

    public static void PermuteAndSolve(List<City> cities, int recursionLevel, int Length)
        {
            if (recursionLevel == Length)
            {
                foreach (City city in cities)
                {
                    Console.Write(city.name);
                }
                Console.WriteLine("");
            }
            else
            {
                for (int i = recursionLevel; i <= Length; i++)
                {
                    swap(cities, recursionLevel, Length);
                    PermuteAndSolve(cities, recursionLevel + 1, Length);                    
                }
            }
        }