using System;
using System.Collections.Generic;
using System.Text;
namespace permute1
{
class Program
{
static void Main(string[] args)
{
List<String> list = new List<String>();
list.Add("A");
list.Add("B");
list.Add("C");
generate(list);
}
public static void output(List<String> A)
{
foreach (String s in A)
{
System.Console.Write(s);
}
System.Console.WriteLine("");
}
public static bool IsEven(int value)
{
return value % 2 == 0;
}
public static void swap(List<String> A, int position1, int position2)
{
String temp = A[position1]; // Copy the first position's element
A[position1] = A[position2]; // Assign to the second element
A[position2] = temp; // Assign to the first element
}
public static void generate(List<String> A)
{
//HEAP'S ALGORITHM FOR GENERATING PERMUTATIONS
int n = A.Count;
int[] c = new int[n];
for (int i = 0; i < n; i++)
{
c[i] = 0;
}
output(A);
for (int i = 0; i < n; )
{
if (c[i] < i)
{
if (IsEven(i))
{
swap(A, 0, i);
}
else
{
swap(A, c[i], i);
}
output(A);
c[i] += 1;
i = 0;
}
else
{
c[i] = 0;
i += 1;
}
}
}
}
}
In general I have code such as:method algorithm()
{
initializing code
.
.
output(A);
while(condition)
if (something)
code
.
.
output(A);
more code
.
.
else
other code
.
.
endwhile
}
And I want to transform this so I can call it via:p = new algorithm()
while(p.hasnext())
A = p.next()
endwhile
This means my next() method should somehow jump back into the middle of the while loop after the output(A) statement at the "more code" spot, which isn't easy (or is impossible). class permuter
{
List<String> A;
int[] c;
int n;
int i;
public permuter(List<String> I)
{
this.A = new List<String>(I);
this.n = A.Count;
this.c = new int[n];
for (int j = 0; j < n; j++)
{
c[j] = 0;
}
}
public bool hasnext()
{
return (this.i < this.n);
}
public bool IsEven(int value)
{
return value % 2 == 0;
}
public void swap(List<String> A, int position1, int position2)
{
String temp = A[position1]; // Copy the first position's element
A[position1] = A[position2]; // Assign to the second element
A[position2] = temp; // Assign to the first element
}
public List<String> next()
{
while (i < n)
{
if (c[i] < i)
{
if (IsEven(i))
{
swap(A, 0, i);
}
else
{
swap(A, c[i], i);
}
c[i] += 1;
i = 0;
return (A);
}
else
{
c[i] = 0;
i += 1;
}
}
return (new List<String>());
}
}
It's not perfect. static void Main(string[] args)
{
List<String> list = new List<String>();
list.Add("A");
list.Add("B");
list.Add("C");
permuter p = new permuter(list);
output(list);
while (p.hasnext())
{
List<String> L = p.next();
output(L);
}
}
Is there a general method for handling these situations?Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.
”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.
Our community of experts have been thoroughly vetted for their expertise and industry experience.