How can I create a permutation ? [Answered]RSS

2 replies

Last post May 04, 2014 08:08 PM by Paul Linton

Member

159 Points

807 Posts

How can I create a permutation ?

May 03, 2014 11:48 PM|robby32|LINK

Hi
If I have 10 people and I want to arrange them in groups of two , how can I do this ?

Ex: if I have bob, peter, andy, John, mark , David etc
I want to get all combinations of pairs like

Bob - peter
Bob - andy
Bob - john
Etc etc

How can I do this ?
Thanks

Participant

1221 Points

408 Posts

Re: How can I create a permutation ?

May 04, 2014 06:25 PM|dahla|LINK

for simplicity you could represent them as integers and use this pseudo code

```List<int> list = ...
List<KeyValuePair<int,int>> permutations = new...

for(int a=0;a<list.Count;a++)
for(int b=0;b<list.Count;b++)
if(a!=b)
permutations.Add(new KeyValuePair<int,int>(a,b))```

Star

9555 Points

2785 Posts

Re: How can I create a permutation ?

May 04, 2014 08:08 PM|Paul Linton|LINK

(What you are asking for is Combinations - not permutations.  Combinations and Permutations are different things.)

Is the pair

bob - peter

the same as

peter - bob

in your problem domain?

If they are considered different then the previous answer will give you the result.  If they are considered the same then the outer loop should only run up to the second last item and the inner loop should start at the point after the current value of the outer loop.  You can do it doing some looping method (like the previous reply) or let linq do the work for you

```var names = new List<string>{"bob", "peter", "andy", "john", "mark", "david"};
var distinctPairs = names.SelectMany((n,i)=>names.Skip(i+1).Select(p => n + "-" + p));```

Got a c# problem? Try .NET Book Zero from Charles Petzold, it's a free pdf.