Permutation and combination is a common mathematical problem, this paper describes the method of C # Implementation of permutation combination algorithm in the form of a complete example. Share it for everyone's reference. Here's how:
First, the mathematical arrangement of the combination, can be expressed as: permutation P (n,r)
In fact, the implementation of the arrangement, the combination is realized, the combination of C (n,r) is P (n,r)/P (R,R), the implementation of this function is relatively simple recursive algorithm, but considering the performance of recursion, the following 2 kinds of non-recursive methods, the specific code is as follows
Using system;using System.collections.generic;namespace test{class Program {static void Main (string[] args) { Console.WriteLine (P1 (6, 3)); Console.WriteLine (P2 (6, 3)); Console.WriteLine (C (6, 2)); }///<summary>/////</summary>//<param name= "N" ></param>//<para M name= "R" ></param>///<returns></returns> static long P1 (int N, int r) {if (R > N || R <= 0 | | N <= 0) throw new ArgumentException ("params invalid!"); Long T = 1; int i = N; while (I!=n-r) {try {checked {T *= i; }} catch {throw new OverflowException ("Overflow happens!"); }-I.; } return t; }///<summary>///Arrange Stack method///</summary>//<param name= "N" ></param>//<para M name= "R" ></param>//<returns></returns> static long P2 (int N, int r) {if (R > N | | R <= 0 | | N <= 0) throw new ArgumentException ("Arguments invalid!"); stack<int> s = new stack<int> (); Long iRlt = 1; int t; S.push (N); while ((t = S.peek ()) = N-r) {try {checked {iRlt *= t; }} catch {throw new OverflowException ("Overflow happens!"); } s.pop (); S.push (t-1); } return iRlt; }///<summary>////</summary>//<param name= "N" ></param>//<param NA Me= "R" ></param>///<returns></returns> static long C (int N, int R) {return P1 (N, R)/ P1 (R, R); } }}
I hope this article is helpful to everyone's C # programming.
In addition to the Declaration,
Running GuestArticles are original, reproduced please link to the form of the address of this article
A complete example of permutation and combination algorithm for C #
This address: http://www.paobuke.com/develop/c-develop/pbk23563.html
Related Content C # multi-thread thread control detailed C # connection to MySQL method "based on VS2010" C # sample code for parsing JSON with Litjson detail parsing C # Multithreading synchronization events and wait handles
How C # traverses dictionaryc# Access database through OLE DB method C # using StreamReader to read a file how to use Adomd.net to query cubes in C #
A complete example of permutation and combination algorithm for C #