0

I'm a newbee programmer, and i'm actually doing some programming challenges. And here's my question:

How can I create a function that returns all rearranging possibilities of an array?

Exemple (in pseudo-code):

Array = ["aba", "bbb", "bab"] //this array have 6 possible arrangements

function arrayRearangement(Array) {
   //receive the array and return all array arrangement possibilities (6)
}
arrayRearrangement(Array) = [["aba", "bbb", "bab"], 
                             ["aba", "bab", "bbb"],
                             ["bbb", "aba", "bab"], 
                             ["bbb", "bab", "aba"],
                             ["bab", "bbb", "aba"],
                             ["bab", "aba", "bbb"]]

If possible, please, give-me the solution in pseudo-code (I prefer to implement by myself).

But It can be written in your favorite programming language.

Obs.: Sorry about any possible english mistake, or if the topic is repeated, i have been searched a lot and don't found anything

amit
  • 175,853
  • 27
  • 231
  • 333
Beomond
  • 3
  • 2

1 Answers1

0

You are probably want to learn more about backtracking in order to achieve it.

In backtracking, you use recursion to go over all possible solutions of the problem.

In your case (pseudo code):

GetAllPermutations(elements):
  result = []
  GetAllPermutations(set(elements), [], result)
  return result

GetAllPermutations(elements, so_far, result):
  if elements.empty():
    result.add(so_far)
    return
  for x in elements:
    elements.remove(x)  // Note while implementing: this is problematic since modifying while iterating, there are ways to overcome it
    so_far.append(x)
    // This is the recursive call, which "assumes" x is set and checks all possible other solutions
    GetAllPermutations(elements, so_far, result)
    // set back the state for next iterations where x is viable selection
    so_far.remove_last()
    elements.add(x)
amit
  • 175,853
  • 27
  • 231
  • 333