jQuery in Action, 3rd edition
The moose likes Programming Diversions and the fly likes Tips to create this method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Other » Programming Diversions
Bookmark "Tips to create this method" Watch "Tips to create this method" New topic

Tips to create this method

Hussein Baghdadi
clojure forum advocate

Joined: Nov 08, 2003
Posts: 3479

Hey all.
I was thinking about the following problem.
I want to create a method that takes an array of integers as a parameter and prints all the possible values of these numbers.
I mean, if we pass the following array :
[1, 2, 3]
the method should prints :
1 2 3 - 1 3 2 - 3 2 1 - 3 1 2 ........
any tips how to create this method ?
Maxim Katcharov
Ranch Hand

Joined: Sep 07, 2004
Posts: 113
Fun problem.

The simplest way to do it would be to run a for loop for each integer:
and then eliminate values where a number appears more than once - but that would be a terrible solution to your problem.

You could also pop all the values onto a list, and go through them recursivley:

I'm sure there are better ways to do this, I can begin to think of one that involves flipping the numbers several times, if it'll work, I don't know.
Maxim Katcharov
Ranch Hand

Joined: Sep 07, 2004
Posts: 113
Ah, forgot to mention: the code above doesn't handle something like {1,2,2,3}, since it treats the 2's as different from each other. So you'd get both 1322, and 1322

This could probably be solved by sorting the list before starting, and then in the for loop, if [current number] == [last number checked], skip it.
Stefan Wagner
Ranch Hand

Joined: Jun 02, 2003
Posts: 1923

... and the keyword is: Permutation.

Maxim Katcharov
Ranch Hand

Joined: Sep 07, 2004
Posts: 113
Originally posted by Stefan Wagner:
... and the keyword is: Permutation.

Ah... I never could remember which was which - permutation or combination, that is. Always had to try both on the calculator during tests, and then see which answer was higher. Good times...
I agree. Here's the link: http://aspose.com/file-tools
subject: Tips to create this method
It's not a secret anymore!