Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to combine a list of words in C# like this?

I want to create an array like this

Array Input: {A, B, C}
Output: {A, B, C}, {AB, C}, {A, BC}, {ABC}

Array Input: {A, B, C, D}
Output: {A, B, C, D}, {AB, C, D}, {ABC, D}, {AB, CD}, {ABCD}, {A, BC, D}, {A, BCD}, {A B CD}

I was thinking about making it in C#, but I haven’t been able to solve it yet.

Can you code this algorithm?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Yes, in general case you can encode each possible split as 0 or 1 (true or false) to have all the combinations:

  A     B     C    D
     ^     ^     ^
  0 or 1  ...  0 or 1    

For instance:

  ABCD    - 000 (no splits)
  A,BCD   - 100 (split, then no splits)
  AB,CD   - 010 
  ABC,D   - 001
  AB,C,D  - 011
  A,B,CD  - 110
  ...
  A,B,C,D - 111 (all splits)        

Code:

private static IEnumerable<List<List<T>>> MySolution<T>(IEnumerable<T> source) {
  if (source is null)
    throw new ArgumentNullException(nameof(source));

  var array = source.ToArray();

  if (array.Length <= 0)
    yield break;

  for (int mask = 0; mask < 1 << (array.Length - 1); ++mask) {
    List<List<T>> result = new List<List<T>>();

    result.Add(new List<T>() { array[0] });

    for (int index = 0; index < array.Length - 1; ++index) {
      if ((mask & (1 << index)) != 0)
        result.Add(new List<T>() { });

      result[result.Count - 1].Add(array[index + 1]);
    }

    yield return result;
  }
}

Demo:

  char[] demo = new char[] { 'A', 'B', 'C', 'D' };

  var result = MySolution(demo)
    .Select(rec => "{" + string.Join(", ", rec
      .Select(item => string.Join("", item))) + "}");

  Console.WriteLine(string.Join(Environment.NewLine, result));

Output:

{ABCD}
{A, BCD}
{AB, CD}
{A, B, CD}
{ABC, D}
{A, BC, D}
{AB, C, D}
{A, B, C, D}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading