From: ashu on
Hi,

I've a requirement as follows:

If I give parameter as 3 to a script, it should give following
combination of numbers:

1
2
3
12
13
23
123

If I give parameter as 4 to a script, it should give following
combination of numbers:

1
2
3
4
12
13
14
23
24
34
123
124
134
234
1234
--------------------------

The number of combination would be (2^n) - 1.

Could some one please help finding the logic/script for this?

Thank you,
Ashok M
+919663398009
From: Ben Finney on
ashu <ashu.magadum(a)gmail.com> writes:

> I've a requirement as follows:

What's causing this requirement? It sounds like a homework assignment.
What real-world problem is being addressed?

> If I give parameter as 3 to a script, it should give following
> combination of numbers:
>
> 1
> 2
> 3
[…]
> 123
>
> If I give parameter as 4 to a script, it should give following
> combination of numbers:
>
> 1
> 2
> 3
[…]
> 234
> 1234
> --------------------------
>
> The number of combination would be (2^n) - 1.
>
> Could some one please help finding the logic/script for this?

I would suggest using a language with combinations already implemented
in a standard library. Python is a good choice:

$ python2.6
[…]
>>> import itertools
>>> def sequence_combinations(seq_len):
... seq_full = range(1, seq_len+1)
... generators = itertools.chain(
... *(itertools.combinations(seq_full, sub_len)
... for sub_len in range(1, seq_len+1)))
... result = list(generators)
... return result
...

>>> sequence_combinations(3)
[(1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
>>> sequence_combinations(4)
[(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)]

>>> # to make it a bit clearer:
>>> import pprint
>>> pprint.pprint(sequence_combinations(4))
[(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)]

--
\ “What's another word for Thesaurus?” —Steven Wright |
`\ |
_o__) |
Ben Finney