File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Number Combinations Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Number Combinations" Watch "Number Combinations" New topic

Number Combinations

Gauri Shankar Iyer

Joined: Feb 23, 2009
Posts: 6
Say I have a number, 12345678.

I want to retrieve all the sub-numbers (if I may call it that) from this number, in forward order, without re-arranging or repeating digits.


[1,2,3,4,5,6,7,8] is valid.
[12,23,34,45,56,67,78] is valid.
[12,13,14,15,16,17,123,1345,1678,3456,378] are all valid.
[1234567,2348] are valid.
But 112, 213,5674 are not.

Any suggestions?
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46417
Go through the methods of the String class and you will find methods which allow you to take sub-strings. You may find it easier to turn 12345678 into "12345678".

Remind yourself of the five basic arithmetic operators. Remember there are not four, but five. The fifth is probably useful here.

Get yourself a List to put the resultant numbers into.
Embla Tingeling
Ranch Hand

Joined: Oct 22, 2009
Posts: 237
Gauri Shankar Iyer wrote:
Any suggestions?

So the initial number defines the allowed order among digits? And you're supposed to form all subnumbers which preserve the allowed order among digits? That's simpler than it looks really.

Say the initial number is 123. The first step is to split the initial number into individual digits and store them in an int array. To just print the digits will generate all subnumbers of length 1,

But how to generate all valid subnumbers of length 2? That can be done by introducing a second nested loop.

As you can see the nested loop starts from the index of the outer loop plus 1. This means it will only consider digits that safely can be added to the current number of the outer loop.

Now you can easily generate all valid 3 digit numbers by introducing yet another nested loop following the same pattern. (There should be one such number only by the way, namely the initial number).

That's all fine but what about if you don't know how many digits there are in the initial number? How can you have a variable number of nested loops? The answer is recursion. The above can be reformulated as a recursive method where each recursive call represents one step deeper down the loop nesting.
I agree. Here's the link:
subject: Number Combinations
It's not a secret anymore!