What is the best algorithm to get all possible string combinations from a given array with a minimum & maximum length value.
Note: This adds complexity since the
Algorithm to get all possible string combinations from array up to certain length.
The algorithm is based on finding the Power set of indexes, which is in turn based on finding all the combinations (without repetition) of indexes with size: 1, 2,..., n
.
As my skills in your language of preference "tend to zero", here is a C# implementation that could be used as a benchmark:
using System;
namespace Combinatorics
{
class StringPowerSet
{
static string[] set = { "a", "b", "c" };
static int[] subSetIndexes;
//-------------------------------------------------------------
static void Main(string[] args)
{
PrintSet(set, "Initial set");
FindPowerSet(set.Length);
}
//-------------------------------------------------------------
private static void FindPowerSet(int n)
{
// Super set - all sets with size: 0, 1, ..., n - 1
for (int k = 0; k <= n - 1; k++)
{
subSetIndexes = new int[k];
CombinationsNoRepetition(k, 0, n - 1);
}
}
//-------------------------------------------------------------
private static void CombinationsNoRepetition(int k, int iBegin, int iEnd)
{
if (k == 0)
{
PrintSubSet();
return;
}
for (int i = iBegin; i <= iEnd; i++)
{
subSetIndexes[k - 1] = i;
++iBegin;
CombinationsNoRepetition(k - 1, iBegin, iEnd);
}
}
}
}
Here are the helper print functions:
//-------------------------------------------------------------
private static void PrintSubSet()
{
Console.Write("(");
for (int i = subSetIndexes.Length - 1; i >= 0; i--)
{
Console.Write(set[subSetIndexes[i]]);
if (i > 0)
{
Console.Write(" ,");
}
}
Console.WriteLine(")");
}
//-------------------------------------------------------------
private static void PrintSet(string[] arr, string label = "")
{
Console.WriteLine(label);
Console.Write("(");
for (int i = 0; i < arr.Length; i++)
{
Console.Write(arr[i]);
if (i < arr.Length - 1)
{
Console.Write(" ,");
}
}
Console.WriteLine(")");
}
Input:
{a, b, c}
Output:
() (a) (b) (c) (a, b) (a, c) (b, c)
Variables k
and n
in the call of function CombinationsNoRepetition
determine the length of the first set and the last sets, i.e. there are your min and max.