Hiren
Hiren

Reputation: 1391

Combination of two characters

I am giving input as int and according to that input I want combination of two characters, FOR EXAMPLE I am giving input as 2 and I have two characters x and y so I want combinations like

    xx,yy,xy,yx

If Input is 3,I want

    xxx,xyy,xxy,xyx,yxx,yyy,yxy.yyx

and so on,I have try with following code,

     int input1 = 4;
        Double totalpossibilities = Math.Pow(2, input1);
        string[] PArray = new string[Convert.ToInt16(totalpossibilities)];
        char[] chars = new char[] { 'x', 'y'};

        for (int i = 0; i < totalpossibilities; i++)
        {
            string possibility = "" ;
            for (int j = 0; j < input1; j++)
            {
                Random random = new Random();
                int r = random.Next(chars.Length);
                char randomChar = chars[r];
                possibility = possibility + randomChar;

            }
            if (PArray.Contains(possibility))
            {
                i--;
            }
            else
                PArray[i] = possibility;
        }

But as you can see I am using random function So I takes too long to complete,Is there any different logic?

Upvotes: 1

Views: 1873

Answers (5)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 62002

Here's a solution with List<>. Generalizes to any number of letters.

static List<string> letters = new List<string> { "x", "y", };

static List<string> MakeList(int input)
{
  if (input < 0)
    throw new ArgumentOutOfRangeException();

  var li = new List<string> { "", };

  for (int i = 0; i < input; ++i)
    li = Multiply(li);

  return li;
}

static List<string> Multiply(List<string> origList)
{
  var resultList = new List<string>(origList.Count * letters.Count);
  foreach (var letter in letters)
    resultList.AddRange(origList.Select(s => letter + s));
  return resultList;
}

Upvotes: 0

ThisGuy
ThisGuy

Reputation: 2395

svenv answer is the correct (and very clever) answer to the question, but I thought I'd provide a generic solution to generating all permutations of set of tokens which might be useful for others who might have a similar problem.

public class Permutations
{
    public static string[][] GenerateAllPermutations(string[] tokens, int depth)
    {
        string[][] permutations = new string[depth][];

        permutations[0] = tokens;

        for (int i = 1; i < depth; i++)
        {
            string[] parent = permutations[i - 1];
            string[] current = new string[parent.Length * tokens.Length];

            for (int parentNdx = 0; parentNdx < parent.Length; parentNdx++)
                for (int tokenNdx = 0; tokenNdx < tokens.Length; tokenNdx++)
                    current[parentNdx * tokens.Length + tokenNdx] = parent[parentNdx] + tokens[tokenNdx];

            permutations[i] = current;
        }

        return permutations;
    }

    public static void Test()
    {
        string[] tokens = new string[] { "x", "y", "z" };
        int depth = 4;

        string[][] permutations = GenerateAllPermutations(tokens, depth);

        for (int i = 0; i < depth; i++)
        {
            foreach (string s in permutations[i])
                Console.WriteLine(s);

            Console.WriteLine(string.Format("Total permutations:  {0}", permutations[i].Length));
            Console.ReadKey();
        }
    }
}

Cheers,

Upvotes: 0

svenv
svenv

Reputation: 323

You could run a for loop from 0 to totalpossibilities. Convert i to binary, for example, at iteration 20 this would result in "10100". Pad the result to input1 characters, for example (for 8 places): 00010100 Then convert to a string and replace all zeroes with "x", all ones with "y".

        int places = 4;
        Double totalpossibilities = Math.Pow(2, places);

        for (int i = 0; i < totalpossibilities; i++)
        {
            string CurrentNumberBinary = Convert.ToString(i, 2).PadLeft(places, '0');

            CurrentNumberBinary = CurrentNumberBinary.Replace('0', 'x');
            CurrentNumberBinary = CurrentNumberBinary.Replace('1', 'y');
            Debug.WriteLine(CurrentNumberBinary);
        }

Upvotes: 3

Samy Arous
Samy Arous

Reputation: 6812

if you always have 2 characters then the simplest way is to use the integers combinatorial nature. if you take the binary form of all numbers from 2^n to 2^(n+1) - 1, you will notice that it represents all the possible combination of '0' and '1' of length n :).

For more than 2 characters, I'll use a similar approach but with a different base.

Upvotes: 0

Servy
Servy

Reputation: 203812

Using a copy of the Cartesian Product extension method copied verbatim from here:

static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) 
{ 
  IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; 
  return sequences.Aggregate( 
    emptyProduct, 
    (accumulator, sequence) => 
      from accseq in accumulator 
      from item in sequence 
      select accseq.Concat(new[] {item})); 
}

Then in your code you can have:

IEnumerable<char> possibleCharacters = "xy";//change to whatever
int numberOfDigits = 3;

var result = Enumerable.Repeat(possibleCharacters, numberOfDigits)
     .CartesianProduct()
     .Select(chars => new string(chars.ToArray()));

//display (or do whatever with) the results
foreach (var item in result)
{
    Console.WriteLine(item);
}

Upvotes: 4

Related Questions