Algorithm: Combination in C ++

Source: Internet
Author: User
I saw a post in the Forum a few days ago. I know the number of combinations. I want to use the formula CNR (= n! /(N-R )! R !) The number of combinations can be obtained. How can we use a program to obtain a combination sequence? Take integer data as an example:
Ex:
N = {1, 2, 3, 4, 5}
Obtain two values from the Five Elements in N.
12 13 14 15 23 24 25 34 35 45 -- 10 combinations
Here we can see that the combination is regular, and each combination always appears in the order of elements in N (the combination is not an arrangement, and 12 and 21 belong to the same combination). Secondly, based on the former, the adjacent combination increases sequentially from the last element to the element N.
This is very useful information. If we want to output each combination sequence, we can naturally think of the most intuitive solution-Recursive Backtracking. The friend on the Forum also used this idea to design the solution.
The code is given, and the combination sequence with the length of R is selected from the N-ordered integer data:

// Parameter description: A records the combination sequence. K1 is the combination coordinate, and K2 is the auxiliary parameter.
Void combination (int A [], int N, int R, int K1, int K2 )......{
If (k1 = r)... {// output the current sequence
For (INT I = 0; I <r; ++ I)
Cout <A [I] <"";
Cout <Endl;
}
Else
For (INT I = k2; I <n; ++ I )......{
A [k1] = I + 1; // assign values to subsequences
Combination (A, N, R, K1 + 1, I + 1); // Recursive Backtracking
}
}

The code is simple. Can this problem be solved now? Otherwise, I think that if the current set N is not ordered, if you want to perform specific processing on the R sequence obtained each time. This is not enough. To improve practicality, If you design it into a generic algorithm, whether it works better.
With preliminary ideas, we further consider that the n sequence should be defined by the user, and the container R should be used to store the combination sequence, and the user will set the operation for the current R combination sequence.

The following is a template function:

 

// Parameter description: begin and end are two-way iterators, Col is the coordinate, the initial value is 0, and the number of loop cycles is determined by the length difference between N and R. func User-Defined Functions
Template <class bidit, class func>
Void combination_recursive (bidit n_begin, bidit n_end, int n_col,
Bidit r_begin, bidit r_end, int r_col, int loop, func )...{

Int r_size = r_end-r_begin; // get the r Length
Int curr_n_col = n_col;
Int curr_loop = loop;

If (r_col = r_size) // generates a combination sequence
Func (r_begin, r_end );

Else
For (INT I = 0; I <= loop; ++ I )...{

Bidit r_it = r_begin; // obtain the location of the r iterator.
For (INT r_cnt = 0; r_cnt <r_col; ++ r_cnt)
++ R_it;
Bidit n_it = n_begin; // obtain the N iterator position
For (INT n_cnt = 0; n_cnt <n_col + I; ++ n_cnt)
++ N_it;

* R_it = * n_it; // value assignment

++ Curr_n_col;
// Recursive Backtracking
Combination_recursive (n_begin, n_end, curr_n_col,
R_begin, r_end, r_col + 1, curr_loop, func );

-- Curr_loop;
}
}

Function usage:
Ex:

At this point, the original idea was realized. However, there is another problem. The combination algorithm uses recursion. during large-scale input, the depth of the stack will consume a lot of memory space. Secondly, although our user-defined functions can implement the required operations, they are of limited use and cannot flexibly filter the desired composite sequence.
The words related to the "Combination" are "arranged". In the STL Algorithm Library, next_permutation is a good example (see another article "STL algorithm: next_permutation analysis), can we design a fan-type algorithm like this to solve our problem? The answer is yes. Because the two properties of the combination are obtained in the initial example, it means that the combination is ordered, and the next combination sequence can be obtained from a combination sequence.
The following is a function prototype of combination:

Template <class bidit>
Bool next_combination (bidit n_begin, bidit n_end,
Bidit r_begin, bidit r_end );

Template <class bidit, class Pred>
Bool next_combination (bidit n_begin, bidit n_end,
Bidit r_begin, bidit r_end
PRED equal );

Template <class bidit>
Bool prev_combination (bidit n_begin, bidit n_end,
Bidit r_begin, bidit r_end );

Template <class bidit, class Pred>
Bool prev_combination (bidit n_begin, bidit n_end,
Bidit r_begin, bidit r_end,
PRED equal );

The algorithm is completed in a linear time and overlapped. The specific implementation of the algorithm is complicated. Next_combination & prev_combination both use the forward index from the end, and set the mark based on the current element of Compare N and R to generate the next combination sequence.

Function usage:
Ex:

# Include <iostream>
# Include "combination. H"

Using namespace STD;

Int main ()...{
Char N [] = "abcdefg ";
Char R [] = "ABC ";
Int COUNT = 0;
Do ...{
Cout <r <Endl;
++ Count;
}
While (next_combination (N, N + 7, R, R + 3 ));
Cout <count <Endl;
Cout <"finished" <Endl;
System ("pause ");
}

If prev_combination is used, replace R with the largest combination sequence char R [] = "EFG ".

Note: although the algorithms in this article are completely written by me, they are not all designed by me. We will learn from the Internet and books. You are welcome to discuss them.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.