Alright so in my Data Structures class we have a program due sometime next week. I pretty much know how I'm going to do it, but I need help with one method of the program.

I need a way to go through every possible order of 6 unique numbers.
I will input the 6 numbers and this method needs to go through every possible order of them. I can't just do a few nested for loops or anything like that AFAIK.

I'm just looking to see if anyone has a good idea on how to do this. I have the rest of the program written out in my mind, but all I am missing is a good way to do this.

Any hints on anything that anyone could come up with would be much obliged.

Recommended Answers

All 5 Replies

Since they are unique numbers I'll suppose you have your numbers in a Set<Number>. I'll call it numbers. Then I would solve the problem recursively. Write a method something like Collection<List<Number>> allPossibleOrders(Set<Number> numbers) and in that method have an accumulator ArrayList<List<Number>> and a loop like for(Number n: numbers). For each n, construct a new set that contains all the numbers except n, call allPossibleOrders recursively, and for every list that it returns tack n onto the end and add it to the accumulator. Be sure that when the number set is empty you return a singleton collection containing an empty list, otherwise just return the accumulator and you are done.

I've never used Collection or List, but I'll look into them and the method you described. Thank you for your time and help!

If anyone else comes up with another idea I'll listen to it too.

So you are talking about permutation? Are you sure that the input numbers will always be unique? If not, you need a Set<Number> as bguild said to ensure that all numbers entered by a user (or you) are unique. Then you can apply a permutation algorithm and spit out each order. One good algorithm is Steinhous-Johnson-Trotter.

PS: Data structure for the set is not that important because it can be as simple as a set (or array). The algorithm is more concerned (that it must be correct).

It's due on Monday and I'll finally be able to work on it starting Saturday.

Yea the instructions state that the input numbers will be between 1-19 and will always be unique so that no number is used more than once.

I'll try both of you guys ideas and hopefully will get it to work so I can build the rest of the program around it.

Thanks again for the help guys!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.