1

I was wondering if any algorithm of that kind does exist, I don't have the slightest idea on how to program it...

For exemple if you give it [1;5;7] it should returns [(1,5);(1,7);(5,1);(5,7);(7,1);(7,5)]

I don't want to use any for loop.

Do you have any clue on how to achieve this ?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
gdcvdqpl
  • 146
  • 5

2 Answers2

1

You have two cases: list is empty -> return empty list; list is not empty -> take first element x, for each element y yield (x, y) and make a recursive call on the tail of the list. Haskell:

pairs :: [a] -> [(a, a)]
pairs [] = []
pairs (x:xs) = [(x, x') | x' <- xs] ++ pairs xs

--*Main> pairs [1..10]
--[(1,2),(1,3),(1,4),(1,5),(1,6),(1,7),(1,8),(1,9),(1,10),(2,3),(2,4),(2,5),(2,6),(2,7),(2,8),(2,9),(2,10),(3,4),(3,5),(3,6),(3,7),(3,8),(3,9),(3,10),(4,5),(4,6),(4,7),(4,8),(4,9),(4,10),(5,6),(5,7),(5,8),(5,9),(5,10),(6,7),(6,8),(6,9),(6,10),(7,8),(7,9),(7,10),(8,9),(8,10),(9,10)]
hilberts_drinking_problem
  • 11,322
  • 3
  • 22
  • 51
-1

I don't know is the algorithm used is a recursive one or not, but what are you asking for is the itertools.combinations('ABCD', 2) method from Python and I suppose the same thing is implemented in other programming language, so you can probably use the native method.

But if you need to write your own, then you can take a look at Algorithm to return all combinations of k elements from n (on this site) for some ideas

Community
  • 1
  • 1
Gianluca
  • 3,227
  • 2
  • 34
  • 35