#codingexercise
Generate Lexicographically ordered combinations of a string
public static void Combine(ref String numbers, ref StringBuilder candidate, ref SortedList<String, String> combinations, int level, int start)
{
for (int i = start; i < numbers.Length; i++)
{
if (candidate.ToString().Contains(numbers[i]) == false)
{
candidate[level] = numbers[i];
combinations.Add(candidate.ToString(), candidate.ToString());
if (i < numbers.Length - 1)
Combine(ref numbers, ref candidate, ref combinations, level + 1, start + 1);
candidate[level] = '\0';
}
}
}
static void ToPrint(SortedList<String, String> combinations, string prefix)
{
Console.WriteLine("---------------------------------------");
for (int i = 0; i < combinations.Count; i++)
Console.WriteLine(prefix + combinations.ElementAt(i).Key);
Console.WriteLine("---------------------------------------");
}
static void Main(string[] args)
{
var a = "321";
var b = new StringBuilder();
for (int i = 0; i < a.Length; i++)
b.Append('\0');
int start = 0;
int level = 0;
var combinations = new SortedList<String, String>();
Combine(ref a, ref b, ref combinations, level, start);
var prefix = String.Empty;
ToPrint(combinations, prefix);
}
---------------------------------------
1
2
21
3
31
32
321
---------------------------------------
If the starting input string is already sorted from left to right, then the following permutations do not require a SortedList and the additions to a dictionary are already sorted and the results are the same for each prefix
static void Main(string[] args){
var a = "123";
var b = new StringBuilder();
var used = new bool[a.Length];
int start = 0;
int end = a.Length - 1;
var permutations = new Dictionary<String, String>();
for ( int i = end ; i>= start; i--){
var prefix = a.Substring(0, start);
Permute(a, b, used, start, end, ref permutations);
ToPrint(permutations, prefix);
permutations = new Dictionary<String, String>();
}
}
No comments:
Post a Comment