[Solved] Next permutation algorithm c# and linq [closed]


You could try following code, it uses private field to stroe all permutations generated by methods finding permutations:

private static List<string> _permutations = new List<string>();
public static Main(string[] args)
{
  string testString = "abc";
  TestMethod(testString);
  // You need to handle case when you have last permuation in a list
  string nextPermutation = _permutations[_permutations.IndexOf(testString) + 1];
}

private static void Swap(ref char a, ref char b)
{
  if (a == b) return;

  a ^= b;
  b ^= a;
  a ^= b;
}

private static void GetPer(char[] list)
{
  int x = list.Length - 1;
  GetPer(list, 0, x);
}

private static void GetPer(char[] list, int k, int m)
{
  if (k == m)
  {
    _permutations.Add(new string(list));
  }
  else
    for (int i = k; i <= m; i++)
    {
      Swap(ref list[k], ref list[i]);
      GetPer(list, k + 1, m);
      Swap(ref list[k], ref list[i]);
    }
}

private static void TestMethod(string str)
{
  char[] arr = str.ToCharArray();
  GetPer(arr);
}

0

solved Next permutation algorithm c# and linq [closed]