Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to show all combinations of numbers in the list

Tags:

algorithm

How would I build a recursive function to show all the possibilities of signs in the list of numbers e.g. (5, 3, 12, 9, 15). The list won't change, just the signs for each number.

For example, the results would be:
(-5, 3, 12, 9, 15)
(-5, -3, 12, 9, 15)
(-5, -3, -12, 9, 15)
(-5, -3, -12, -9, 15)

And so on, until all the combinations of this list are displayed.

I've tried a few different ways, including trying to adapt code from other similar questions here, but majority of them include changing the list itself.

Thanks!

like image 314
Akira Iris Avatar asked Dec 01 '25 06:12

Akira Iris


1 Answers

Generate all possible 5-elements binary list e.g. [0,0,0,0,0], [0,0,0,0,1], [0,0,0,1,0] .. [1,1,0,0,1] ... [1,1,1,1,1]. Now, for each of these lists, do the following.

If there is a 1 in x'th position in the list then replace the number at this position with its negative in your original list.

Now the problem is : how to generate all lists of 5 boolean digits recursively (Binary trees?).

like image 128
Dilawar Avatar answered Dec 12 '25 13:12

Dilawar