@@ -9,49 +9,31 @@ namespace Advanced.Algorithms.Combinatorics
9
9
public class Variation
10
10
{
11
11
/*Variations are arrangements of selections of objects, where the order of the selected objects matters.
12
- To count k -element variations of n objects, we first need to choose a k -element combination and then
12
+ To count r -element variations of n objects, we first need to choose a r -element combination and then
13
13
a permutation of the selected objects*/
14
14
15
15
//Without repetition
16
- /* It is also the number of ways of putting r distinct balls into input.Count distinct boxes such that each box
16
+ /* It is also the number of ways of putting n distinct balls into r distinct boxes such that each box
17
17
receives at most one element. */
18
18
19
19
//With repetition
20
- /* It is the number of all ways of putting r distinct balls into input.Count distinct boxes */
20
+ /* It is the number of all ways of putting n distinct balls into r distinct boxes */
21
21
public static List < List < T > > Find < T > ( List < T > input , int r , bool withRepetition )
22
22
{
23
- var result = new List < List < T > > ( ) ;
23
+ var combinations = new List < List < T > > ( ) ;
24
24
25
- Recurse ( input , r , withRepetition , new List < T > ( ) , new HashSet < int > ( ) , result ) ;
25
+ combinations . AddRange ( Combination . Find ( input , r , withRepetition ) ) ;
26
26
27
- return result ;
28
- }
27
+ var variations = new List < List < T > > ( ) ;
29
28
30
- private static void Recurse < T > ( List < T > input , int r , bool withRepetition ,
31
- List < T > prefix , HashSet < int > prefixIndices ,
32
- List < List < T > > result )
33
- {
34
- if ( prefix . Count == r )
29
+ foreach ( var combination in combinations )
35
30
{
36
- result . Add ( new List < T > ( prefix ) ) ;
37
- return ;
31
+ variations . AddRange ( Permutation . Find ( combination , combination . Count ) ) ;
38
32
}
39
33
40
- for ( int j = 0 ; j < input . Count ; j ++ )
41
- {
42
- if ( prefixIndices . Contains ( j ) && ! withRepetition )
43
- {
44
- continue ;
45
- }
46
-
47
- prefix . Add ( input [ j ] ) ;
48
- prefixIndices . Add ( j ) ;
49
-
50
- Recurse ( input , r , withRepetition , prefix , prefixIndices , result ) ;
51
-
52
- prefix . RemoveAt ( prefix . Count - 1 ) ;
53
- prefixIndices . Remove ( j ) ;
54
- }
34
+ return variations ;
55
35
}
36
+
37
+
56
38
}
57
39
}
0 commit comments