4

I'm trying to allow a user to enter text in a textbox, and have the program generate all possible combinations of it, except with a minimum of 3 characters and maximum of 6. I don't need useless words like 'as', 'a', 'i', 'to', etc cluttering up my array. I'll also be checking each combination against a dictionary to make sure it's a real word.

I have the dictionary complete (painstakingly generated, here's a link to it in return (WARNING: gigantic load time (for me)!)

Anyways, if the user enters 'ABCDEF' (in no particular order), how could I generate, for example:

'ABC'
'BAC'
'CAB'
...
'ABD'
'ABE'
'ABF'

etc... EVERY possible combination, no matter what order? I understand that there are a ridiculous amount of these combinations, but it only needs to be calculated once, so I'm not too worried about that.

I've found code samples to recursively find combinations (not permutations, I don't need those) of just the fixed-width string (ABCDEF, ABCDFE ... ACDBFE, etc). They don't do what I need, and I haven't the slightest clue about where to even start with this project.

This isn't homework, it started out as a personal project of mine that's grown to take over my life over such a simple problem... I can't believe I can't figure this out!

Scott
  • 5,170
  • 5
  • 45
  • 68

4 Answers4

2

It sounds to me like you're describing the Power Set

Here's an implementation I had lying around my personal library:

// Helper method to count set bits in an integer
public static int CountBits(int n)
{
    int count = 0;
    while (n != 0)
    {
        count++;
        n &= (n - 1);
    }
    return count;
}


public static IEnumerable<IEnumerable<T>> PowerSet<T>(
    IEnumerable<T> src, 
    int minSetSize = 0, 
    int maxSetSize = int.MaxValue)
{
    // we want fast random access to the source, so we'll
    // need to ToArray() it
    var cached = src.ToArray();
    var setSize = Math.Pow(2, cached.Length);
    for(int i=0; i < setSize; i++)
    {
        var subSetSize = CountBits(i);
        if(subSetSize < minSetSize || 
           subSetSize > maxSetSize)
        {
            continue;
        }
        T[] set = new T[subSetSize];

        var temp = i;
        var srcIdx = 0;
        var dstIdx = 0;
        while(temp > 0)
        {
            if((temp & 0x01) == 1)
            {
                set[dstIdx++] = cached[srcIdx];
            }
            temp >>= 1;
            srcIdx++;            
        }
        yield return set;
    }
    yield break;
}

And a quick test rig:

void Main()
{
    var src = "ABCDEF";
    var combos = PowerSet(src, 3, 6);

    // hairy joins for great prettiness
    Console.WriteLine(
        string.Join(" , ", 
            combos.Select(subset => 
                string.Concat("[", 
                    string.Join(",", subset) , "]")))
    );
}

Output:

[A,B,C] , [A,B,D] , [A,C,D] , [B,C,D] , [A,B,C,D] , [A,B,E] , [A,C,E] , [B,C,E] , [A,B,C,E] , 
[A,D,E] , [B,D,E] , [A,B,D,E] , [C,D,E] , [A,C,D,E] , [B,C,D,E] , [A,B,C,D,E] , [A,B,F] , 
[A,C,F] , [B,C,F] , [A,B,C,F] , [A,D,F] , [B,D,F] , [A,B,D,F] , [C,D,F] , [A,C,D,F] , 
[B,C,D,F] , [A,B,C,D,F] , [A,E,F] , [B,E,F] , [A,B,E,F] , [C,E,F] , [A,C,E,F] , [B,C,E,F] , 
[A,B,C,E,F] , [D,E,F] , [A,D,E,F] , [B,D,E,F] , [A,B,D,E,F] , [C,D,E,F] , [A,C,D,E,F] , 
[B,C,D,E,F] , [A,B,C,D,E,F]
JerKimball
  • 16,238
  • 3
  • 41
  • 54
0

Supposed, you also want stuff like "AAB" the "cross product" of your set of letters should be it.

Generation can be as simple as a LINQ:

            string myset = "ABCDE";
            var All = (from char l1 in myset 
                   from char l2 in myset 
                   from char l3 in myset 
                   select new string(new char[] { l1, l2, l3})).ToList();

Note: construction many strings and char Arrays is not fast. You may want to replace the new string and new char[] with a custom class like so:

select new MyCustomClass(l1, l2, l3).ToList();

If you don't want things like "AAB" (or "EEL") then I'd point you to wikipedia for "combinations".

To get from fixed-length to "any length from 3 to 6" join multiple sets, if the limits are dynamic then use a loop.

DasKrümelmonster
  • 5,342
  • 1
  • 22
  • 44
0

The best way to do this is to use a for loop and convert each character from an int to a char and concatenate them together in a string.

For example:

for(int i = 0; i < 26; i++)
{
    Console.WriteLine((char)i + 'A');        
}
Jake Anderson
  • 121
  • 1
  • 1
  • 7
0

From this link (under MIT license)

using System;
using System.Collections.Generic;
using System.Diagnostics;

// Copyright (c) 2010 Alex Regueiro
// Licensed under MIT license, available at <http://www.opensource.org/licenses/mit-license.php>.
// Published originally at <http://blog.noldorin.com/2010/05/combinatorics-in-csharp/>.
// Version 1.0, released 22nd May 2010.
public static class CombinatoricsUtilities
{
    // Error messages
    private const string errorMessageValueLessThanZero = "Value must be greater than zero, if specified.";
    private const string errorMessagesIndicesListInvalidSize = "List of indices must have same size as list of elements.";

    /// <summary>
    /// Gets all permutations (of a given size) of a given list, either with or without reptitions.
    /// </summary>
    /// <typeparam name="T">The type of the elements in the list.</typeparam>
    /// <param name="list">The list of which to get permutations.</param>
    /// <param name="action">The action to perform on each permutation of the list.</param>
    /// <param name="resultSize">The number of elements in each resulting permutation; or <see langword="null"/> to get
    /// premutations of the same size as <paramref name="list"/>.</param>
    /// <param name="withRepetition"><see langword="true"/> to get permutations with reptition of elements;
    /// <see langword="false"/> to get permutations without reptition of elements.</param>
    /// <exception cref="ArgumentNullException"><paramref name="list"/> is <see langword="null"/>. -or-
    /// <paramref name="action"/> is <see langword="null"/>.</exception>
    /// <exception cref="ArgumentException"><paramref name="resultSize"/> is less than zero.</exception>
    /// <remarks>
    /// The algorithm performs permutations in-place. <paramref name="list"/> is however not changed.
    /// </remarks>
    public static void GetPermutations<T>(this IList<T> list, Action<IList<T>> action, int? resultSize = null,
        bool withRepetition = false)
    {
        if (list == null)
            throw new ArgumentNullException("list");
        if (action == null)
            throw new ArgumentNullException("action");
        if (resultSize.HasValue && resultSize.Value <= 0)
            throw new ArgumentException(errorMessageValueLessThanZero, "resultSize");

        var result = new T[resultSize.HasValue ? resultSize.Value : list.Count];
        var indices = new int[result.Length];
        for (int i = 0; i < indices.Length; i++)
            indices[i] = withRepetition ? -1 : i - 1;

        int curIndex = 0;
        while (curIndex != -1)
        {
            indices[curIndex]++;
            if (indices[curIndex] == list.Count)
            {
                indices[curIndex] = withRepetition ? -1 : curIndex - 1;
                curIndex--;
            }
            else
            {
                result[curIndex] = list[indices[curIndex]];
                if (curIndex < indices.Length - 1)
                    curIndex++;
                else
                    action(result);
            }
        }
    }

    /// <summary>
    /// Gets all combinations (of a given size) of a given list, either with or without reptitions.
    /// </summary>
    /// <typeparam name="T">The type of the elements in the list.</typeparam>
    /// <param name="list">The list of which to get combinations.</param>
    /// <param name="action">The action to perform on each combination of the list.</param>
    /// <param name="resultSize">The number of elements in each resulting combination; or <see langword="null"/> to get
    /// premutations of the same size as <paramref name="list"/>.</param>
    /// <param name="withRepetition"><see langword="true"/> to get combinations with reptition of elements;
    /// <see langword="false"/> to get combinations without reptition of elements.</param>
    /// <exception cref="ArgumentNullException"><paramref name="list"/> is <see langword="null"/>. -or-
    /// <paramref name="action"/> is <see langword="null"/>.</exception>
    /// <exception cref="ArgumentException"><paramref name="resultSize"/> is less than zero.</exception>
    /// <remarks>
    /// The algorithm performs combinations in-place. <paramref name="list"/> is however not changed.
    /// </remarks>
    public static void GetCombinations<T>(this IList<T> list, Action<IList<T>> action, int? resultSize = null,
        bool withRepetition = false)
    {
        if (list == null)
            throw new ArgumentNullException("list");
        if (action == null)
            throw new ArgumentNullException("action");
        if (resultSize.HasValue && resultSize.Value <= 0)
            throw new ArgumentException(errorMessageValueLessThanZero, "resultSize");

        var result = new T[resultSize.HasValue ? resultSize.Value : list.Count];
        var indices = new int[result.Length];
        for (int i = 0; i < indices.Length; i++)
            indices[i] = withRepetition ? -1 : indices.Length - i - 2;

        int curIndex = 0;
        while (curIndex != -1)
        {
            indices[curIndex]++;
            if (indices[curIndex] == (curIndex == 0 ? list.Count : indices[curIndex - 1] + (withRepetition ? 1 : 0)))
            {
                indices[curIndex] = withRepetition ? -1 : indices.Length - curIndex - 2;
                curIndex--;
            }
            else
            {
                result[curIndex] = list[indices[curIndex]];
                if (curIndex < indices.Length - 1)
                    curIndex++;
                else
                    action(result);
            }
        }
    }

    /// <summary>
    /// Gets a specific permutation of a given list.
    /// </summary>
    /// <typeparam name="T">The type of the elements in the list.</typeparam>
    /// <param name="list">The list to permute.</param>
    /// <param name="indices">The indices of the elements in the original list at each index in the permuted list.
    /// </param>
    /// <returns>The specified permutation of the given list.</returns>
    /// <exception cref="ArgumentNullException"><paramref name="list"/> is <see langword="null"/>. -or-
    /// <paramref name="indices"/> is <see langword="null"/>.</exception>
    /// <exception cref="ArgumentException"><paramref name="indices"/> does not have the same size as
    /// <paramref name="list"/>.</exception>
    public static IList<T> Permute<T>(this IList<T> list, IList<int> indices)
    {
        if (list == null)
            throw new ArgumentNullException("list");
        if (indices == null)
            throw new ArgumentNullException("indices");
        if (list.Count != indices.Count)
            throw new ArgumentException(errorMessagesIndicesListInvalidSize, "indices");

        var result = new T[list.Count];
        for (int i = 0; i < result.Length; i++)
            result[i] = list[indices[i]];
        return result;
    }
}
Martheen
  • 4,893
  • 4
  • 28
  • 51