Jump to content

How to check all combinations?

- - - - -

  • Please log in to reply
3 replies to this topic

#1
Turboorav

Turboorav

    Newbie

  • Members
  • Pip
  • 7 posts
I have a list of numbers and I want to check all the combinations. How can I do it?
Let's say I have a list that contains:
1,2,3,4

Then I want to check all the combinations that are unique:
1
1,2
1,2,3
1,2,4
1,2,3,4
1,3
1,3,4
1,4

2
2,3
2,3,4
2,4

3
3,4

4

#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others
One way would be to count, using the bits to indicate which numbers to include:
0001
0010
0011
0100
0101
...
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
JackomoLight

JackomoLight

    Newbie

  • Members
  • PipPipPip
  • 38 posts
Well haven't you studied about factorials? All possible(unique) combinations of a set of different(non-repetitive) n elements is given by n! ( n factorial) I bet there is a function in the math library for doing that but I never used it you can simply write 3 lines recursive function and you are done.

#4
solartic

solartic

    Learning Programmer

  • Members
  • PipPipPip
  • 95 posts
python's itertools has permutations and combinations funtions

from itertools import combinations

>>> for x in range(1,5): print list(combinations([1,2,3,4], x))
...
[(1,), (2,), (3,), (4,)]
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
[(1, 2, 3, 4)]




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users