Combinations and PermutationsOften we have calculations that involve a number of combinations or permutations. With combinations we do not care the order of some, for example if we have four counties: UK, France, Germany and Ireland, then there are four combinations of three countries: {UK, France, Germany}, {UK, France, Ireland}, {France, Germany, Ireland} and {UK, Germany, Ireland}. With permutations we look at all the options including the sequence of the options. The results are then:
|
Try an example
- Four countries, pick three. Go
- Six colours, pick four. Go
- Six Football teams, pick two. Go
- Eight animals, pick three. Go
- I take a bet of any one from seven teams winning. How many bets is it?. Go
- I take a bet of any two from seven teams winning. How many bets is it?. Go
- I take a bet of any three from seven teams winning. How many bets is it?. Go
- I take a bet of any four from seven teams winning. How many bets is it?. Go
- I take a bet of any five from seven teams winning. How many bets is it?. Go
- I take a bet of any six from seven teams winning. How many bets is it?. Go
- I take a bet of any seven from seven teams winning. How many bets is it?. Go
Code
The code integrates the Combinatorics library (adding a reference of Combinatorics.dll):
using Combinatorics.Collections; public static string comb(string[] str, int vals) { Listlist = new List (str); string res = ""; var p = new Combinations (str, vals); res=String.Format("Number of combinations is {0}. Any {1} from {2}\r\n",p.Count,vals,str.Length); foreach (var v in p) { if (res.Length < 1500) res += "{" + string.Join(",", v) + "} "; else res += "."; } return(res); } public static string variations(string[] str, int vals) { List list = new List (str); string res = ""; var p = new Variations (list, vals, GenerateOption.WithoutRepetition); res = String.Format("Number of combinations is {0}. Any {1} from {2}\r\n", p.Count, vals, str.Length); foreach (var v in p) { if (res.Length < 1500) res += "{" + string.Join(",", v) + "} "; else res += "."; } return (res); } public static string perm(string[] str, int vals) { List list = new List (str); string res = ""; var p = new Permutations (str, GenerateOption.WithoutRepetition); res = String.Format("Number of combinations is {0}. Any {1} from {2}\r\n", p.Count, vals, str.Length); foreach (var v in p) { if (res.Length<1500) res += "{" + string.Join(",", v) + "} "; else res += "."; } return (res); }