How to create permutations of keyword without repetition for google adword in C#

1 Answer

0 votes
using System;
using System.IO;
using System.Collections.Generic;

namespace Permutations_Words
{
  class Class1
  {
    static void Main(string[] args)
    {
      permutation_words();
    }
    private static void permutation_words()
    {
      string[] stringInput = { "make", "money", "on", "the", "internet" };

      ShowPermutations<string>(stringInput, stringInput.Length);
    }
    static void ShowPermutations<T>(IEnumerable<T> input, int count)
    {
      string path_write = @"c:\temp\Test.txt"; // You can change the path and file name
      StreamWriter sw = File.CreateText(path_write);
      int j;

      foreach (IEnumerable<T> permutation in PermutationUtils.Permute<T>(input, count))
      {
        j = 0;
        foreach (T pword in permutation)
        {
          if (j == 0)
            sw.Write(pword);
          else
            sw.Write(" " + pword);
          j++;
        }
        sw.WriteLine();
      }
      foreach (IEnumerable<T> permutation in PermutationUtils.Permute<T>(input, count))
      {
        sw.Write("\"");
        j = 0;
        foreach (T pword in permutation)
        {
          if (j == 0)
            sw.Write(pword);
          else
            sw.Write(" " + pword);
          j++;
        }
        sw.Write("\"");
        sw.WriteLine();
      }
      foreach (IEnumerable<T> permutation in PermutationUtils.Permute<T>(input, count))
      {
        sw.Write("[");
        j = 0;
        foreach (T pword in permutation)
        {
          if (j == 0)
            sw.Write(pword);
          else
            sw.Write(" " + pword);
          j++;
        }
        sw.Write("]");
        sw.WriteLine();
      }
      sw.Close();
    }
  }
  class PermutationUtils
  {
    public static IEnumerable<IEnumerable<T>> Permute<T>(IEnumerable<T> list, int count)
    {
      if (count == 0)
      {
        yield return new T[0];
      }
      else
      {
        int startingElementIndex = 0;
        foreach (T startingElement in list)
        {
          IEnumerable<T> remainingItems = AllExcept(list, startingElementIndex);

          foreach (IEnumerable<T> permutationOfRemainder in Permute(remainingItems, count - 1))
          {
            yield return Concat<T>(new T[] { startingElement }, permutationOfRemainder);
          }
          startingElementIndex += 1;
        }
      }
    }
    public static IEnumerable<T> Concat<T>(IEnumerable<T> x, IEnumerable<T> y)
    {
      foreach (T item in x) { yield return item; }
      foreach (T item in y) { yield return item; }
    }
    public static IEnumerable<T> AllExcept<T>(IEnumerable<T> input, int indexToSkip)
    {
      int index = 0;
      foreach (T item in input)
      {
        if (index != indexToSkip) yield return item;
        index += 1;
      }
    }
  }
}


answered Apr 10, 2014 by avibootz
edited Jun 4, 2014 by avibootz
...