-2

I am new to c# and I need to perform a permutation without repetition for the arrays. For example, Below are the 2 string arrays.

string[] str1 = String[]{"E1","E2","E3"};
string[] str2 = String[]{"E1","E2","E3","E4"};

And I need to generate output for str1 as

{"E1","E2","E3","E1 E2","E1 E3","E2 E3","E1 E2 E3"} 

and for str2 as

{"E1","E2","E3","E4","E1 E2","E1 E3","E1 E4","E2 E3","E2 E4",
 "E3 E4","E1 E2 E3","E1 E2 E4","E1 E3 E4","E2 E3 E4","E1 E2 E3 E4"}`

Also, I would like to compare the output of str1 & str2. If any of the results are matching(ex.:E2 E3& E2 E3) then I need to return "Output is matching" but I am stuck on how to proceed with the below coding in c# and the output is repeating and also array length is static. Please guide me.

String[] str1 = { "E1", "E2", "E3" };

List<string> resultedValue = new List<string>();

for (int i = 0; i < str1.Length; i++)
 {
  for (int j = 0; j < str1.Length; j++)
   {
     if (i == j) resultedValue.Add(string.Format("[ {0} ]", str1[i]));
     else resultedValue.Add(string.Format("[ {0} {1} ]", str1[i], str1[j]));
   }
 }
 Console.WriteLine(resultedValue.ToArray());
user3129206
  • 117
  • 1
  • 7

1 Answers1

0

I couldn't remember where I got this code (possibly translated from another language), and it isn't very efficient, but it also isn't length constrained, but using LINQ, you can get the powerset of an IEnumerable, minus the empty set:

public static class IEnumerableExt {
    public static string Join(this IEnumerable<string> src, string sep) => String.Join(sep, src);

    public static bool IsEmpty<T>(this IEnumerable<T> src) => !src.Any();

    public static IEnumerable<IEnumerable<T>> AllCombinations<T>(this IEnumerable<T> start) {
        IEnumerable<IEnumerable<T>> HelperCombinations(IEnumerable<T> items) {
            if (items.IsEmpty())
                yield return items;
            else {
                var head = items.First();
                var tail = items.Skip(1);
                foreach (var sequence in HelperCombinations(tail)) {
                    yield return sequence; // Without first
                    yield return sequence.Prepend(head);
                }
            }
        }

        return HelperCombinations(start).Skip(1); // don't return the empty set
    }
}

With these extension methods, you can do:

var comboStr1 = str1.AllCombinations().Select(ss => ss.Join(" "));
var comboStr2 = str2.AllCombinations().Select(ss => ss.Join(" "));

var hsComboStr1 = comboStr1.ToHashSet();
var ans = comboStr2.Any(s2combo => hsComboStr1.Contains(s2combo));

to determine if the powersets of str1 and str2 share any members.

NetMage
  • 26,163
  • 3
  • 34
  • 55