• 0

Generate all combinations of an array


Input :

[ 1, 2, 3 ]

Output :

[  ' ',  1,  2,  12,  3,  13,  23,  123  ]

Logic :

  • There are 2^n possible combinations for the array of size n
  • We have to generate binary code for all numbers from 0 to ( (2^n) - 1 )
  • For each binary code we need to generate corresponding number
  • For example, given array [ 1, 2, 3], we will generate binary code from 0 to 7
InputBinaryResult
[ 1, 2, 3 ]0000
[ 1, 2, 3 ]0013
[ 1, 2, 3 ]0102
[ 1, 2, 3 ]01123
[ 1, 2, 3 ]1001
[ 1, 2, 3 ]10113
[ 1, 2, 3 ]11012
[ 1, 2, 3 ]111123

Execution steps

ij2^ji & 2^jBinarydecimaltemp
001000''
1200''
2400''
1011111
12001
24001
201002''
12212
24002
3011131
122112
240012
401004''
1200''
24413
5011151
12001
244113
601006''
12212
244123
7011171
122112
2441123