The function works this way:
Set
is an instance variable, and is an array of type generic.nElement
is the size of all the subsets that you want. For example if you give it the value 3 the function will return all the subsets ofSet
of size 3The idea is that we create an array named
indices
(indices = index in French) that will follow the index that we want for each subset.We know that all of our subsets have a size of 3 elements so if
indices[2]
= 3 we have to incrementindices[1]
by 1 and set all of the followingindices[i]
toindices[i-1]+1
.
Example
Set = {1,2,3,4} nElement = 3
for the first subset the
indices = {0,1,2} -> {1,2,3}
for the second subset the
indices = {0,1,3} -> {1,2,4} indices[2] = 3
so weindices[1]++
andindices[2] = indices[1]+1
for the third subset the
indices = {0,2,3} -> {1,3,4} indices[2] = indices[2] = 3
so weindices[1]++
andindices[2] = indices[1]+1
butindices[1]
now= 2
and the max value thatindices[1]
can have is 2 soindices[0]++
andindices[1] = indices[0]+1
for the fourth subset the
indices = {1,2,3} -> {2,3,4}
Code
public List<T[]> GenerateCoupleOf(int nElement)
{
if (nElement < 1)
throw new Exception("nElement must be greater than 0");
List<T[]> tr = new List<T[]>();
T[] arr;
int[] indices = new int[nElement];
T[] temp_arr = new T[nElement];
for (int i = 0; i < indices.Length; i++)
indices[i] = i;
while (indices[0] <= Set.Length - 1 - ((Set.Length - 1) - (Set.Length - 1 - indices.Length + 0)) + 1)
{
for (int i = 0; i < indices.Length; i++)
temp_arr[i] = Set[indices[i]];
arr = new T[nElement];
for (int i = 0; i < indices.Length; i++)
arr[i] = Set[indices[i]];
tr.Add(arr);
indices[indices.Length - 1]++;
for (int i = indices.Length - 1; i > 0; i--)
{
if (indices[i] > Set.Length - 1 - ((Set.Length - 1) - (Set.Length - 1 - indices.Length + i)) + 1)
{
indices[i - 1]++;
for (int j = i; j < indices.Length; j++)
indices[j] = indices[j - 1] + 1;
}
}
}
return tr;
}
GenerateCoupleOf
? Why don't post the entire class? The code is extremely hard to read. \$\endgroup\$