Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Tips to create this method

 
Hussein Baghdadi
clojure forum advocate
Bartender
Posts: 3479
Clojure Mac Objective C
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 113
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Fun problem.

The simplest way to do it would be to run a for loop for each integer:
111-112-113-121-122-123...
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
Posts: 113
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1923
Linux Postgres Database Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
... and the keyword is: Permutation.
 
Maxim Katcharov
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic